firebase 9.12.1 → 9.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.esm.js +1 -1
  4. package/app/dist/index.mjs +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.esm.js +1 -1
  7. package/compat/app/dist/index.mjs +1 -1
  8. package/compat/dist/index.esm.js +2 -2
  9. package/compat/dist/index.node.cjs +2 -2
  10. package/compat/dist/index.rn.cjs.js +2 -2
  11. package/firebase-analytics-compat.js +1 -1
  12. package/firebase-analytics.js +1 -1
  13. package/firebase-app-check-compat.js +1 -1
  14. package/firebase-app-check.js +1 -1
  15. package/firebase-app-compat.js +2 -2
  16. package/firebase-app.js +5 -5
  17. package/firebase-auth-compat.js +1 -1
  18. package/firebase-auth-cordova.js +1 -1
  19. package/firebase-auth-react-native.js +1 -1
  20. package/firebase-auth.js +1 -1
  21. package/firebase-compat.js +3 -3
  22. package/firebase-compat.js.map +1 -1
  23. package/firebase-database-compat.js +1 -1
  24. package/firebase-database-compat.js.map +1 -1
  25. package/firebase-database.js +1 -1
  26. package/firebase-database.js.map +1 -1
  27. package/firebase-firestore-compat.js +1 -1
  28. package/firebase-firestore-compat.js.map +1 -1
  29. package/firebase-firestore-lite.js +1 -1
  30. package/firebase-firestore-lite.js.map +1 -1
  31. package/firebase-firestore.js +1 -1
  32. package/firebase-firestore.js.map +1 -1
  33. package/firebase-functions-compat.js +1 -1
  34. package/firebase-functions.js +1 -1
  35. package/firebase-installations-compat.js +1 -1
  36. package/firebase-installations.js +1 -1
  37. package/firebase-messaging-compat.js +1 -1
  38. package/firebase-messaging-compat.js.map +1 -1
  39. package/firebase-messaging-sw.js +1 -1
  40. package/firebase-messaging-sw.js.map +1 -1
  41. package/firebase-messaging.js +1 -1
  42. package/firebase-messaging.js.map +1 -1
  43. package/firebase-performance-compat.js +1 -1
  44. package/firebase-performance-standalone-compat.es2017.js +7 -7
  45. package/firebase-performance-standalone-compat.js +1 -1
  46. package/firebase-performance.js +1 -1
  47. package/firebase-remote-config-compat.js +1 -1
  48. package/firebase-remote-config.js +1 -1
  49. package/firebase-storage-compat.js +1 -1
  50. package/firebase-storage-compat.js.map +1 -1
  51. package/firebase-storage.js +1 -1
  52. package/firebase-storage.js.map +1 -1
  53. package/package.json +28 -28
@@ -1,10 +1,10 @@
1
- !function(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(){"use strict";function i(e){var t=n(e);return r.encodeByteArray(t,!0)}const t={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw u(t)},u=function(e){return new Error("Firebase Database ("+t.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},n=function(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n},r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],a=u+1<n.length,o=a?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var a=c<e.length?n[e.charAt(c)]:64;++c;var o=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==a||null==o)throw Error();r.push(i<<2|s>>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},s=function(e){return i(e).replace(/\./g,"")},a=function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=c(e[r],t[r]));return e}function h(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function o(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(h())}function l(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function d(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function p(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function g(){const e=h();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function m(){return!0===t.NODE_ADMIN}function v(){return"object"==typeof indexedDB}function y(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function _(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}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.")}const e=()=>w().__FIREBASE_DEFAULTS__,b=()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}},I=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&a(e[1]);return t&&JSON.parse(t)}},T=()=>{try{return e()||b()||I()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},E=()=>{var e;return null===(e=T())||void 0===e?void 0:e.config};var k,C,S;class A{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function N(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[s(JSON.stringify({alg:"none",type:"JWT"})),s(JSON.stringify(i)),""].join(".")}class R extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,R.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,x.prototype.create)}}class x{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(D,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new R(i,s,n)}}const D=/\{\$([^}]+)}/g;function P(e){return JSON.parse(e)}function O(e){return JSON.stringify(e)}function M(e){let t={},n={},r={},i="";try{var s=e.split(".");t=P(a(s[0])||""),n=P(a(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function L(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function F(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function U(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function q(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function V(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return;var i=e[a],s=t[a];if(B(i)&&B(s)){if(!V(i,s))return}else if(i!==s)return}for(const o of r)if(!n.includes(o))return;return 1}function B(e){return null!==e&&"object"==typeof e}function j(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function K(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function $(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class z{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],a=this.chain_[2],o=this.chain_[3],c=this.chain_[4],l,u;for(let p=0;p<80;p++){u=p<40?p<20?(l=o^s&(a^o),1518500249):(l=s^a^o,1859775393):p<60?(l=s&a|o&(s|a),2400959708):(l=s^a^o,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[p]&4294967295;c=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=h}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]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function W(e,t){const n=new G(e,t);return n.subscribe.bind(n)}class G{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,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=H),void 0===r.error&&(r.error=H),void 0===r.complete&&(r.complete=H);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),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 H(){}function Q(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function Y(e,t){return`${e} failed: ${t} argument `}function J(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(Y(e,t)+"must be a valid function.")}function X(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(Y(e,t)+"must be a valid context object.")}function Z(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)})}const ee=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},te=1e3,ne=2,re=144e5,ie=.5;function se(e,t=te,n=ne){var r=t*Math.pow(n,e),i=Math.round(ie*r*(Math.random()-.5)*2);return Math.min(re,r+i)}function ae(e){return e&&e._delegate?e._delegate:e}class oe{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const ce="[DEFAULT]";class le{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)){const r=new A;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),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:ce})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=ce){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const 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=ce){return this.instances.has(e)}getOptions(e=ce){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===ce?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=ce){return!this.component||this.component.multipleInstances?e:ce}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class ue{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const 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){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new le(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const he=[];(C=k=k||{})[C.DEBUG=0]="DEBUG",C[C.VERBOSE=1]="VERBOSE",C[C.INFO=2]="INFO",C[C.WARN=3]="WARN",C[C.ERROR=4]="ERROR",C[C.SILENT=5]="SILENT";const de={debug:k.DEBUG,verbose:k.VERBOSE,info:k.INFO,warn:k.WARN,error:k.ERROR,silent:k.SILENT},pe=k.INFO,fe={[k.DEBUG]:"log",[k.VERBOSE]:"log",[k.INFO]:"info",[k.WARN]:"warn",[k.ERROR]:"error"},ge=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=fe[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class me{constructor(e){this.name=e,this._logLevel=pe,this._logHandler=ge,this._userLogHandler=null,he.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in k))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?de[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,k.DEBUG,...e),this._logHandler(this,k.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,k.VERBOSE,...e),this._logHandler(this,k.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,k.INFO,...e),this._logHandler(this,k.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,k.WARN,...e),this._logHandler(this,k.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,k.ERROR,...e),this._logHandler(this,k.ERROR,...e)}}const ve=(t,e)=>e.some(e=>t instanceof e);let ye,_e;const we=new WeakMap,be=new WeakMap,Ie=new WeakMap,Te=new WeakMap,Ee=new WeakMap;let ke={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return be.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Ie.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ae(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function Ce(r){return r!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(_e=_e||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(r)?function(...e){return r.apply(Ne(this),e),Ae(we.get(this))}:function(...e){return Ae(r.apply(Ne(this),e))}:function(e,...t){var n=r.call(Ne(this),e,...t);return Ie.set(n,e.sort?e.sort():[e]),Ae(n)}}function Se(e){return"function"==typeof e?Ce(e):(e instanceof IDBTransaction&&(s=e,be.has(s)||(t=new Promise((e,t)=>{const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",i),s.removeEventListener("abort",i)},r=()=>{e(),n()},i=()=>{t(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",r),s.addEventListener("error",i),s.addEventListener("abort",i)}),be.set(s,t))),ve(e,ye=ye||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,ke):e);var s,t}function Ae(e){if(e instanceof IDBRequest)return function(s){const e=new Promise((e,t)=>{const n=()=>{s.removeEventListener("success",r),s.removeEventListener("error",i)},r=()=>{e(Ae(s.result)),n()},i=()=>{t(s.error),n()};s.addEventListener("success",r),s.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&we.set(e,s)}).catch(()=>{}),Ee.set(e,s),e}(e);if(Te.has(e))return Te.get(e);var t=Se(e);return t!==e&&(Te.set(e,t),Ee.set(t,e)),t}const Ne=e=>Ee.get(e);function Re(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const a=indexedDB.open(e,t),o=Ae(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Ae(a.result),e.oldVersion,e.newVersion,Ae(a.transaction))}),n&&a.addEventListener("blocked",()=>n()),o.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",()=>i())}).catch(()=>{}),o}function xe(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",()=>t()),Ae(n).then(()=>{})}const De=["get","getKey","getAll","getAllKeys","count"],Pe=["put","add","delete","clear"],Oe=new Map;function Me(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Oe.get(t))return Oe.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,a=Pe.includes(i);if(i in(s?IDBIndex:IDBObjectStore).prototype&&(a||De.includes(i))){var n=async function(e,...t){var n=this.transaction(e,a?"readwrite":"readonly");let r=n.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),a&&n.done]))[0]};return Oe.set(t,n),n}}}ke={...S=ke,get:(e,t,n)=>Me(e,t)||S.get(e,t,n),has:(e,t)=>!!Me(e,t)||S.has(e,t)};class Le{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const Fe="@firebase/app",Ue=new me("@firebase/app");var qe;const Ve="[DEFAULT]",Be={"@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/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","fire-js":"fire-js",firebase:"fire-js-all"},je=new Map,Ke=new Map;function $e(t,n){try{t.container.addComponent(n)}catch(e){Ue.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function ze(e,t){e.container.addOrOverwriteComponent(t)}function We(e){var t=e.name;if(Ke.has(t))return Ue.debug(`There were multiple attempts to register component ${t}.`),!1;Ke.set(t,e);for(const n of je.values())$e(n,e);return!0}function Ge(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const He=new x("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","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","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}."});class Qe{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new oe("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 He.create("app-deleted",{appName:this._name})}}const Ye="9.12.1";function Je(e,t={}){let n=e;if("object"!=typeof t){const i=t;t={name:i}}var r=Object.assign({name:Ve,automaticDataCollectionEnabled:!1},t);const i=r.name;if("string"!=typeof i||!i)throw He.create("bad-app-name",{appName:String(i)});if(n=n||E(),!n)throw He.create("no-options");var s=je.get(i);if(s){if(V(n,s.options)&&V(r,s.config))return s;throw He.create("duplicate-app",{appName:i})}const a=new ue(i);for(const o of Ke.values())a.addComponent(o);r=new Qe(n,r,a);return je.set(i,r),r}function Xe(e=Ve){var t=je.get(e);if(!t&&e===Ve)return Je();if(!t)throw He.create("no-app",{appName:e});return t}async function Ze(e){var t=e.name;je.has(t)&&(je.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function et(e,t,n){let r=null!==(s=Be[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const a=[`Unable to register library "${r}" with version "${t}":`];return i&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&a.push("and"),s&&a.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void Ue.warn(a.join(" "))}We(new oe(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function tt(e,t){if(null!==e&&"function"!=typeof e)throw He.create("invalid-log-argument");!function(s,e){for(const t of he){let i=null;e&&e.level&&(i=de[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.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&&void 0!==i?i:e.logLevel)&&s({level:k[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function nt(e){var t;t=e,he.forEach(e=>{e.setLogLevel(t)})}const rt="firebase-heartbeat-database",it=1,st="firebase-heartbeat-store";let at=null;function ot(){return at=at||Re(rt,it,{upgrade:(e,t)=>{0===t&&e.createObjectStore(st)}}).catch(e=>{throw He.create("idb-open",{originalErrorMessage:e.message})}),at}async function ct(e,t){var n;try{const r=await ot(),i=r.transaction(st,"readwrite"),s=i.objectStore(st);return await s.put(t,lt(e)),i.done}catch(e){e instanceof R?Ue.warn(e.message):(n=He.create("idb-set",{originalErrorMessage:null===e||void 0===e?void 0:e.message}),Ue.warn(n.message))}}function lt(e){return`${e.name}!${e.options.appId}`}class ut{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new dt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate();var t=e.getPlatformInfoString();const n=ht();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";var e=ht(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const s=n.find(e=>e.agent===i.agent);if(s){if(s.dates.push(i.date),pt(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),pt(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),t=s(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function ht(){const e=new Date;return e.toISOString().substring(0,10)}class dt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!v()&&y().then(()=>!0).catch(()=>!1)}async read(){return await this._canUseIndexedDBPromise&&await async function(e){var t;try{const n=await ot();return n.transaction(st).objectStore(st).get(lt(e))}catch(e){e instanceof R?Ue.warn(e.message):(t=He.create("idb-get",{originalErrorMessage:null===e||void 0===e?void 0:e.message}),Ue.warn(t.message))}}(this.app)||{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return ct(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return ct(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function pt(e){return s(JSON.stringify({version:2,heartbeats:e})).length}qe="",We(new oe("platform-logger",e=>new Le(e),"PRIVATE")),We(new oe("heartbeat",e=>new ut(e),"PRIVATE")),et(Fe,"0.8.2",qe),et(Fe,"0.8.2","esm2017"),et("fire-js","");var ft=Object.freeze({__proto__:null,SDK_VERSION:Ye,_DEFAULT_ENTRY_NAME:Ve,_addComponent:$e,_addOrOverwriteComponent:ze,_apps:je,_clearComponents:function(){Ke.clear()},_components:Ke,_getProvider:Ge,_registerComponent:We,_removeServiceInstance:function(e,t,n=Ve){Ge(e,t).clearInstance(n)},deleteApp:Ze,getApp:Xe,getApps:function(){return Array.from(je.values())},initializeApp:Je,onLog:tt,registerVersion:et,setLogLevel:nt,FirebaseError:R});class gt{constructor(e,t){this._delegate=e,this.firebase=t,$e(e,new oe("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),Ze(this._delegate)))}_getService(e,t=Ve){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=Ve){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){$e(this._delegate,e)}_addOrOverwriteComponent(e){ze(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const mt=new x("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 vt(i){const s={},a={__esModule:!0,initializeApp:function(e,t={}){var n=Je(e,t);if(L(s,n.name))return s[n.name];var r=new i(n,a);return s[n.name]=r},app:o,registerVersion:et,setLogLevel:nt,onLog:tt,apps:null,SDK_VERSION:Ye,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;We(n)&&"PUBLIC"===n.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw mt.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&c(e,n.serviceProps),a[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?a[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:ft}};function o(e){if(e=e||Ve,!L(s,e))throw mt.create("no-app",{appName:e});return s[e]}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),o.App=i,a}var yt=function e(){const t=vt(gt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:W,ErrorFactory:x,deepExtend:c}),t}();const _t=new me("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){_t.warn(`
1
+ !function(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(){"use strict";function i(e){var t=n(e);return r.encodeByteArray(t,!0)}const t={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw u(t)},u=function(e){return new Error("Firebase Database ("+t.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},n=function(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n},r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],a=u+1<n.length,o=a?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var a=c<e.length?n[e.charAt(c)]:64;++c;var o=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==a||null==o)throw Error();r.push(i<<2|s>>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},s=function(e){return i(e).replace(/\./g,"")},a=function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=c(e[r],t[r]));return e}function h(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function o(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(h())}function l(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function d(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function p(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function g(){const e=h();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function m(){return!0===t.NODE_ADMIN}function v(){return"object"==typeof indexedDB}function y(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function _(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}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.")}const e=()=>w().__FIREBASE_DEFAULTS__,b=()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}},I=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&a(e[1]);return t&&JSON.parse(t)}},T=()=>{try{return e()||b()||I()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},E=()=>{var e;return null===(e=T())||void 0===e?void 0:e.config};var k,S,C;class A{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function N(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[s(JSON.stringify({alg:"none",type:"JWT"})),s(JSON.stringify(i)),""].join(".")}class R extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,R.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,x.prototype.create)}}class x{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(D,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new R(i,s,n)}}const D=/\{\$([^}]+)}/g;function P(e){return JSON.parse(e)}function O(e){return JSON.stringify(e)}function M(e){let t={},n={},r={},i="";try{var s=e.split(".");t=P(a(s[0])||""),n=P(a(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function L(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function F(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function U(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function q(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function V(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return;var i=e[a],s=t[a];if(B(i)&&B(s)){if(!V(i,s))return}else if(i!==s)return}for(const o of r)if(!n.includes(o))return;return 1}function B(e){return null!==e&&"object"==typeof e}function j(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function K(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function $(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class W{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],a=this.chain_[2],o=this.chain_[3],c=this.chain_[4],l,u;for(let p=0;p<80;p++){u=p<40?p<20?(l=o^s&(a^o),1518500249):(l=s^a^o,1859775393):p<60?(l=s&a|o&(s|a),2400959708):(l=s^a^o,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[p]&4294967295;c=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=h}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]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function z(e,t){const n=new G(e,t);return n.subscribe.bind(n)}class G{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,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=H),void 0===r.error&&(r.error=H),void 0===r.complete&&(r.complete=H);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),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 H(){}function Q(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function Y(e,t){return`${e} failed: ${t} argument `}function J(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(Y(e,t)+"must be a valid function.")}function X(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(Y(e,t)+"must be a valid context object.")}function Z(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)})}const ee=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},te=1e3,ne=2,re=144e5,ie=.5;function se(e,t=te,n=ne){var r=t*Math.pow(n,e),i=Math.round(ie*r*(Math.random()-.5)*2);return Math.min(re,r+i)}function ae(e){return e&&e._delegate?e._delegate:e}class oe{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const ce="[DEFAULT]";class le{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)){const r=new A;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),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:ce})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=ce){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const 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=ce){return this.instances.has(e)}getOptions(e=ce){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===ce?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=ce){return!this.component||this.component.multipleInstances?e:ce}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class ue{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const 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){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new le(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const he=[];(S=k=k||{})[S.DEBUG=0]="DEBUG",S[S.VERBOSE=1]="VERBOSE",S[S.INFO=2]="INFO",S[S.WARN=3]="WARN",S[S.ERROR=4]="ERROR",S[S.SILENT=5]="SILENT";const de={debug:k.DEBUG,verbose:k.VERBOSE,info:k.INFO,warn:k.WARN,error:k.ERROR,silent:k.SILENT},pe=k.INFO,fe={[k.DEBUG]:"log",[k.VERBOSE]:"log",[k.INFO]:"info",[k.WARN]:"warn",[k.ERROR]:"error"},ge=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=fe[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class me{constructor(e){this.name=e,this._logLevel=pe,this._logHandler=ge,this._userLogHandler=null,he.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in k))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?de[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,k.DEBUG,...e),this._logHandler(this,k.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,k.VERBOSE,...e),this._logHandler(this,k.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,k.INFO,...e),this._logHandler(this,k.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,k.WARN,...e),this._logHandler(this,k.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,k.ERROR,...e),this._logHandler(this,k.ERROR,...e)}}const ve=(t,e)=>e.some(e=>t instanceof e);let ye,_e;const we=new WeakMap,be=new WeakMap,Ie=new WeakMap,Te=new WeakMap,Ee=new WeakMap;let ke={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return be.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Ie.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ae(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function Se(r){return r!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(_e=_e||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(r)?function(...e){return r.apply(Ne(this),e),Ae(we.get(this))}:function(...e){return Ae(r.apply(Ne(this),e))}:function(e,...t){var n=r.call(Ne(this),e,...t);return Ie.set(n,e.sort?e.sort():[e]),Ae(n)}}function Ce(e){return"function"==typeof e?Se(e):(e instanceof IDBTransaction&&(s=e,be.has(s)||(t=new Promise((e,t)=>{const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",i),s.removeEventListener("abort",i)},r=()=>{e(),n()},i=()=>{t(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",r),s.addEventListener("error",i),s.addEventListener("abort",i)}),be.set(s,t))),ve(e,ye=ye||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,ke):e);var s,t}function Ae(e){if(e instanceof IDBRequest)return function(s){const e=new Promise((e,t)=>{const n=()=>{s.removeEventListener("success",r),s.removeEventListener("error",i)},r=()=>{e(Ae(s.result)),n()},i=()=>{t(s.error),n()};s.addEventListener("success",r),s.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&we.set(e,s)}).catch(()=>{}),Ee.set(e,s),e}(e);if(Te.has(e))return Te.get(e);var t=Ce(e);return t!==e&&(Te.set(e,t),Ee.set(t,e)),t}const Ne=e=>Ee.get(e);function Re(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const a=indexedDB.open(e,t),o=Ae(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Ae(a.result),e.oldVersion,e.newVersion,Ae(a.transaction))}),n&&a.addEventListener("blocked",()=>n()),o.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",()=>i())}).catch(()=>{}),o}function xe(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",()=>t()),Ae(n).then(()=>{})}const De=["get","getKey","getAll","getAllKeys","count"],Pe=["put","add","delete","clear"],Oe=new Map;function Me(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Oe.get(t))return Oe.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,a=Pe.includes(i);if(i in(s?IDBIndex:IDBObjectStore).prototype&&(a||De.includes(i))){var n=async function(e,...t){var n=this.transaction(e,a?"readwrite":"readonly");let r=n.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),a&&n.done]))[0]};return Oe.set(t,n),n}}}ke={...C=ke,get:(e,t,n)=>Me(e,t)||C.get(e,t,n),has:(e,t)=>!!Me(e,t)||C.has(e,t)};class Le{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const Fe="@firebase/app",Ue=new me("@firebase/app");var qe;const Ve="[DEFAULT]",Be={"@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/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","fire-js":"fire-js",firebase:"fire-js-all"},je=new Map,Ke=new Map;function $e(t,n){try{t.container.addComponent(n)}catch(e){Ue.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function We(e,t){e.container.addOrOverwriteComponent(t)}function ze(e){var t=e.name;if(Ke.has(t))return Ue.debug(`There were multiple attempts to register component ${t}.`),!1;Ke.set(t,e);for(const n of je.values())$e(n,e);return!0}function Ge(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const He=new x("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","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","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}."});class Qe{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new oe("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 He.create("app-deleted",{appName:this._name})}}const Ye="9.13.0";function Je(e,t={}){let n=e;if("object"!=typeof t){const i=t;t={name:i}}var r=Object.assign({name:Ve,automaticDataCollectionEnabled:!1},t);const i=r.name;if("string"!=typeof i||!i)throw He.create("bad-app-name",{appName:String(i)});if(n=n||E(),!n)throw He.create("no-options");var s=je.get(i);if(s){if(V(n,s.options)&&V(r,s.config))return s;throw He.create("duplicate-app",{appName:i})}const a=new ue(i);for(const o of Ke.values())a.addComponent(o);r=new Qe(n,r,a);return je.set(i,r),r}function Xe(e=Ve){var t=je.get(e);if(!t&&e===Ve)return Je();if(!t)throw He.create("no-app",{appName:e});return t}async function Ze(e){var t=e.name;je.has(t)&&(je.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function et(e,t,n){let r=null!==(s=Be[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const a=[`Unable to register library "${r}" with version "${t}":`];return i&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&a.push("and"),s&&a.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void Ue.warn(a.join(" "))}ze(new oe(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function tt(e,t){if(null!==e&&"function"!=typeof e)throw He.create("invalid-log-argument");!function(s,e){for(const t of he){let i=null;e&&e.level&&(i=de[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.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&&void 0!==i?i:e.logLevel)&&s({level:k[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function nt(e){var t;t=e,he.forEach(e=>{e.setLogLevel(t)})}const rt="firebase-heartbeat-database",it=1,st="firebase-heartbeat-store";let at=null;function ot(){return at=at||Re(rt,it,{upgrade:(e,t)=>{0===t&&e.createObjectStore(st)}}).catch(e=>{throw He.create("idb-open",{originalErrorMessage:e.message})}),at}async function ct(e,t){var n;try{const r=await ot(),i=r.transaction(st,"readwrite"),s=i.objectStore(st);return await s.put(t,lt(e)),i.done}catch(e){e instanceof R?Ue.warn(e.message):(n=He.create("idb-set",{originalErrorMessage:null===e||void 0===e?void 0:e.message}),Ue.warn(n.message))}}function lt(e){return`${e.name}!${e.options.appId}`}class ut{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new dt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate();var t=e.getPlatformInfoString();const n=ht();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";var e=ht(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const s=n.find(e=>e.agent===i.agent);if(s){if(s.dates.push(i.date),pt(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),pt(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),t=s(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function ht(){const e=new Date;return e.toISOString().substring(0,10)}class dt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!v()&&y().then(()=>!0).catch(()=>!1)}async read(){return await this._canUseIndexedDBPromise&&await async function(e){var t;try{const n=await ot();return n.transaction(st).objectStore(st).get(lt(e))}catch(e){e instanceof R?Ue.warn(e.message):(t=He.create("idb-get",{originalErrorMessage:null===e||void 0===e?void 0:e.message}),Ue.warn(t.message))}}(this.app)||{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return ct(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return ct(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function pt(e){return s(JSON.stringify({version:2,heartbeats:e})).length}qe="",ze(new oe("platform-logger",e=>new Le(e),"PRIVATE")),ze(new oe("heartbeat",e=>new ut(e),"PRIVATE")),et(Fe,"0.8.3",qe),et(Fe,"0.8.3","esm2017"),et("fire-js","");var ft=Object.freeze({__proto__:null,SDK_VERSION:Ye,_DEFAULT_ENTRY_NAME:Ve,_addComponent:$e,_addOrOverwriteComponent:We,_apps:je,_clearComponents:function(){Ke.clear()},_components:Ke,_getProvider:Ge,_registerComponent:ze,_removeServiceInstance:function(e,t,n=Ve){Ge(e,t).clearInstance(n)},deleteApp:Ze,getApp:Xe,getApps:function(){return Array.from(je.values())},initializeApp:Je,onLog:tt,registerVersion:et,setLogLevel:nt,FirebaseError:R});class gt{constructor(e,t){this._delegate=e,this.firebase=t,$e(e,new oe("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),Ze(this._delegate)))}_getService(e,t=Ve){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=Ve){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){$e(this._delegate,e)}_addOrOverwriteComponent(e){We(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const mt=new x("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 vt(i){const s={},a={__esModule:!0,initializeApp:function(e,t={}){var n=Je(e,t);if(L(s,n.name))return s[n.name];var r=new i(n,a);return s[n.name]=r},app:o,registerVersion:et,setLogLevel:nt,onLog:tt,apps:null,SDK_VERSION:Ye,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;ze(n)&&"PUBLIC"===n.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw mt.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&c(e,n.serviceProps),a[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?a[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:ft}};function o(e){if(e=e||Ve,!L(s,e))throw mt.create("no-app",{appName:e});return s[e]}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),o.App=i,a}var yt=function e(){const t=vt(gt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:z,ErrorFactory:x,deepExtend:c}),t}();const _t=new me("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){_t.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
  `);const KP=self.firebase.SDK_VERSION;KP&&0<=KP.indexOf("LITE")&&_t.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
- `)}const wt=yt;et("@firebase/app-compat","0.1.37",void 0);wt.registerVersion("firebase","9.12.1","app-compat");var bt="@firebase/installations",It="0.5.15";const Tt=1e4,Et=`w:${It}`,kt="FIS_v2",Ct="https://firebaseinstallations.googleapis.com/v1",St=36e5;const At=new x("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 Nt(e){return e instanceof R&&e.code.includes("request-failed")}function Rt({projectId:e}){return`${Ct}/projects/${e}/installations`}function xt(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function Dt(e,t){var n=(await t.json()).error;return At.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Pt({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Ot(e,{refreshToken:t}){const n=Pt(e);return n.append("Authorization",(t=t,`${kt} ${t}`)),n}async function Mt(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function Lt(t){return new Promise(e=>{setTimeout(e,t)})}const Ft=/^[cdef][\w-]{21}$/,Ut="";function qt(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return Ft.test(e)?e:Ut}catch(e){return Ut}}function Vt(e){return`${e.appName}!${e.appId}`}const Bt=new Map;function jt(e,t){var n=Vt(e);Kt(n,t),function(e,t){const n=function(){!$t&&"BroadcastChannel"in self&&($t=new BroadcastChannel("[Firebase] FID Change"),$t.onmessage=e=>{Kt(e.data.key,e.data.fid)});return $t}();n&&n.postMessage({key:e,fid:t});0===Bt.size&&$t&&($t.close(),$t=null)}(n,t)}function Kt(e,t){var n=Bt.get(e);if(n)for(const r of n)r(t)}let $t=null;const zt="firebase-installations-store";let Wt=null;function Gt(){return Wt=Wt||Re("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(zt)}}),Wt}async function Ht(e,t){var n=Vt(e);const r=await Gt(),i=r.transaction(zt,"readwrite"),s=i.objectStore(zt);var a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||jt(e,t.fid),t}async function Qt(e){var t=Vt(e);const n=await Gt(),r=n.transaction(zt,"readwrite");await r.objectStore(zt).delete(t),await r.done}async function Yt(e,t){var n=Vt(e);const r=await Gt(),i=r.transaction(zt,"readwrite"),s=i.objectStore(zt);var a=await s.get(n),o=t(a);return void 0===o?await s.delete(n):await s.put(o,n),await i.done,!o||a&&a.fid===o.fid||jt(e,o.fid),o}async function Jt(n){let r;var e=await Yt(n.appConfig,e=>{var t=Zt(e||{fid:qt(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Xt(e.appConfig);for(;1===t.registrationStatus;)await Lt(100),t=await Xt(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await Jt(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(At.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=Rt(e),i=Pt(e),s=t.getImmediate({optional:!0});!s||(a=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",a);var a={fid:n,authVersion:kt,appId:e.appId,sdkVersion:Et};const o={method:"POST",headers:i,body:JSON.stringify(a)},c=await Mt(()=>fetch(r,o));if(c.ok){a=await c.json();return{fid:a.fid||n,registrationStatus:2,refreshToken:a.refreshToken,authToken:xt(a.authToken)}}throw await Dt("Create Installation",c)}(t,n);return Ht(t.appConfig,e)}catch(e){throw Nt(e)&&409===e.customData.serverCode?await Qt(t.appConfig):await Ht(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===Ut?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Xt(e){return Yt(e,e=>{if(!e)throw At.create("installation-not-found");return Zt(e)})}function Zt(e){return 1===(t=e).registrationStatus&&t.registrationTime+Tt<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function en({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Rt(i)}/${s}/authTokens:generate`);var i,s;const a=Ot(e,n),o=t.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",c);var c={installation:{sdkVersion:Et,appId:e.appId}};const l={method:"POST",headers:a,body:JSON.stringify(c)},u=await Mt(()=>fetch(r,l));if(u.ok)return xt(await u.json());throw await Dt("Generate Auth Token",u)}async function tn(r,i=!1){let s;var e=await Yt(r.appConfig,e=>{if(!rn(e))throw At.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+St}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await nn(e.appConfig);for(;1===n.authToken.requestStatus;)await Lt(100),n=await nn(e.appConfig);var r=n.authToken;return 0===r.requestStatus?tn(e,t):r}(r,i),e;if(!navigator.onLine)throw At.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await en(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await Ht(t.appConfig,e),r}catch(e){throw!Nt(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await Ht(t.appConfig,r)):await Qt(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function nn(e){return Yt(e,e=>{if(!rn(e))throw At.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Tt<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function rn(e){return void 0!==e&&2===e.registrationStatus}async function sn(e,t=!1){var n,r=e;return await((n=(await Jt(r)).registrationPromise)&&await n),(await tn(r,t)).token}function an(e){return At.create("missing-app-config-values",{valueName:e})}const on="installations",cn=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw an("App Configuration");if(!e.name)throw an("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw an(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:Ge(t,"heartbeat"),_delete:()=>Promise.resolve()}},ln=e=>{const t=Ge(e.getProvider("app").getImmediate(),on).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await Jt(t);return(r||tn(t)).catch(console.error),n.fid}(t),getToken:e=>sn(t,e)}};We(new oe(on,cn,"PUBLIC")),We(new oe("installations-internal",ln,"PRIVATE")),et(bt,It),et(bt,It,"esm2017");const un="analytics",hn="firebase_id",dn="origin",pn="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",fn="https://www.googletagmanager.com/gtag/js",gn=new me("@firebase/analytics");function mn(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function vn(r,i,s,a){return async function(e,t,n){try{"event"===e?await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await mn(r);for(const l of e){var a=c.find(e=>e.measurementId===l),o=a&&n[a.appId];if(!o){t=[];break}t.push(o)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){gn.error(e)}}(r,i,s,t,n):"config"===e?await async function(e,t,n,r,i,s){var a=r[i];try{if(a)await t[a];else{const c=await mn(n);var o=c.find(e=>e.measurementId===i);o&&await t[o.appId]}}catch(e){gn.error(e)}e("config",i,s)}(r,i,s,a,t,n):"consent"===e?r("consent","update",n):r("set",t)}catch(e){gn.error(e)}}}const yn=new x("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-intialized 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.'}),_n=30;const wn=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 bn(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=pn.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw yn.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function In(e,t=wn,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw yn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw yn.create("no-api-key")}var a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const o=new kn;return setTimeout(async()=>{o.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=wn){var a;const{appId:o,measurementId:c}=n;try{await Tn(i,e)}catch(e){if(c)return gn.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===(a=e)||void 0===a?void 0:a.message}]`),{appId:o,measurementId:c};throw e}try{const l=await bn(n);return s.deleteThrottleMetadata(o),l}catch(e){const u=e;if(!En(u)){if(s.deleteThrottleMetadata(o),c)return gn.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===u||void 0===u?void 0:u.message}]`),{appId:o,measurementId:c};throw e}const h=503===Number(null===(a=null===u||void 0===u?void 0:u.customData)||void 0===a?void 0:a.httpStatus)?se(r,s.intervalMillis,_n):se(r,s.intervalMillis),d={throttleEndTimeMillis:Date.now()+h,backoffCount:r+1};return s.setThrottleMetadata(o,d),gn.debug(`Calling attemptFetch again in ${h} millis`),t(n,d,i,s)}}({appId:r,apiKey:i,measurementId:s},a,o,t)}function Tn(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(yn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function En(e){if(!(e instanceof R&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class kn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Cn(t,e,n,r,i,s,a){const o=In(t);o.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&gn.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=>gn.error(e)),e.push(o);var c=async function(){if(!v())return gn.warn(yn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await y()}catch(e){return gn.warn(yn.create("indexeddb-unavailable",{errorInfo:null===e||void 0===e?void 0:e.toString()}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([o,c]);!function(e){var t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(fn)&&n.src.includes(e))return n}(s)&&function(e,t){const n=document.createElement("script");n.src=`${fn}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const h=null!==(c=null==a?void 0:a.config)&&void 0!==c?c:{};return h[dn]="firebase",h.update=!0,null!=u&&(h[hn]=u),i("config",l.measurementId,h),l.measurementId}class Sn{constructor(e){this.app=e}_delete(){return delete An[this.app.options.appId],Promise.resolve()}}let An={},Nn=[];const Rn={};let xn="dataLayer",Dn="gtag",Pn,On,Mn=!1;function Ln(e){if(Mn)throw yn.create("already-initialized");e.dataLayerName&&(xn=e.dataLayerName),e.gtagName&&(Dn=e.gtagName)}function Fn(e,t,n){!function(){const e=[];var t;d()&&e.push("This is a browser extension environment."),_()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=yn.create("invalid-analytics-context",{errorInfo:t}),gn.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw yn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw yn.create("no-api-key");gn.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!=An[s])throw yn.create("already-exists",{id:s});return Mn||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(xn),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=vn(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(An,Nn,Rn,xn,Dn),On=r,Pn=i,Mn=!0),An[s]=Cn(e,Nn,Rn,t,Pn,xn,n),new Sn(e)}async function Un(){if(d())return!1;if(!_())return!1;if(!v())return!1;try{return await y()}catch(e){return!1}}function qn(e,t,n){e=ae(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(On,An[e.app.options.appId],t,n).catch(e=>gn.error(e))}function Vn(e,t,n){e=ae(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(On,An[e.app.options.appId],t,n).catch(e=>gn.error(e))}function Bn(e,t,n){e=ae(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(On,An[e.app.options.appId],t,n).catch(e=>gn.error(e))}function jn(e,t){e=ae(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(An[e.app.options.appId],t).catch(e=>gn.error(e))}function Kn(e,t,n,r){e=ae(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(On,An[e.app.options.appId],t,n,r).catch(e=>gn.error(e))}const $n="@firebase/analytics";We(new oe(un,(e,{options:t})=>{return Fn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),We(new oe("analytics-internal",function(e){try{const r=e.getProvider(un).getImmediate();return{logEvent:(e,t,n)=>Kn(r,e,t,n)}}catch(e){throw yn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),et($n,"0.8.3"),et($n,"0.8.3","esm2017");var zn,Wn;class Gn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){Kn(this._delegate,e,t,n)}setCurrentScreen(e,t){qn(this._delegate,e,t)}setUserId(e,t){Vn(this._delegate,e,t)}setUserProperties(e,t){Bn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){jn(this._delegate,e)}}(KC=zn=zn||{}).ADD_SHIPPING_INFO="add_shipping_info",KC.ADD_PAYMENT_INFO="add_payment_info",KC.ADD_TO_CART="add_to_cart",KC.ADD_TO_WISHLIST="add_to_wishlist",KC.BEGIN_CHECKOUT="begin_checkout",KC.CHECKOUT_PROGRESS="checkout_progress",KC.EXCEPTION="exception",KC.GENERATE_LEAD="generate_lead",KC.LOGIN="login",KC.PAGE_VIEW="page_view",KC.PURCHASE="purchase",KC.REFUND="refund",KC.REMOVE_FROM_CART="remove_from_cart",KC.SCREEN_VIEW="screen_view",KC.SEARCH="search",KC.SELECT_CONTENT="select_content",KC.SELECT_ITEM="select_item",KC.SELECT_PROMOTION="select_promotion",KC.SET_CHECKOUT_OPTION="set_checkout_option",KC.SHARE="share",KC.SIGN_UP="sign_up",KC.TIMING_COMPLETE="timing_complete",KC.VIEW_CART="view_cart",KC.VIEW_ITEM="view_item",KC.VIEW_ITEM_LIST="view_item_list",KC.VIEW_PROMOTION="view_promotion",KC.VIEW_SEARCH_RESULTS="view_search_results";const Hn=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new Gn(t,n)};Wn={Analytics:Gn,settings:Ln,isSupported:Un,EventName:zn},wt.INTERNAL.registerComponent(new oe("analytics-compat",Hn,"PUBLIC").setServiceProps(Wn).setMultipleInstances(!0)),wt.registerVersion("@firebase/analytics-compat","0.1.16");const Qn=new Map,Yn={activated:!1,tokenObservers:[]},Jn={initialized:!1,enabled:!1};function Xn(e){return Qn.get(e)||Yn}function Zn(e,t){Qn.set(e,t)}const er="https://content-firebaseappcheck.googleapis.com/v1",tr="exchangeDebugToken",nr={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class rr{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))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 A,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new A,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){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const ir=new x("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 sr(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function ar(e){if(!Xn(e).activated)throw ir.create("use-before-activation",{appName:e.name})}function or(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=cr(n)+"d:"),r&&(s+=cr(r)+"h:"),s+=cr(i)+"m:"+cr(t)+"s",s}function cr(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function lr({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});!i||(c=await i.getHeartbeatsHeader())&&(r["X-Firebase-Client"]=c);var s={method:"POST",body:JSON.stringify(t),headers:r};let a;try{a=await fetch(e,s)}catch(e){throw ir.create("fetch-network-error",{originalErrorMessage:null===e||void 0===e?void 0:e.message})}if(200!==a.status)throw ir.create("fetch-status-error",{httpStatus:a.status});let o;try{o=await a.json()}catch(e){throw ir.create("fetch-parse-error",{originalErrorMessage:null===e||void 0===e?void 0:e.message})}var c=o.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw ir.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${o.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:o.token,expireTimeMillis:c+s,issuedAtTimeMillis:c}}const ur="firebase-app-check-database",hr=1,dr="firebase-app-check-store",pr="debug-token";let fr=null;function gr(){return fr||(fr=new Promise((t,n)=>{try{const e=indexedDB.open(ur,hr);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(ir.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(dr,{keyPath:"compositeKey"})}}catch(e){n(ir.create("storage-open",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}}),fr)}async function mr(e,t){const n=await gr(),r=n.transaction(dr,"readwrite"),i=r.objectStore(dr),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(ir.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function vr(e){const t=await gr(),i=t.transaction(dr,"readonly"),n=i.objectStore(dr),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(ir.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function yr(e){return`${e.options.appId}-${e.name}`}const _r=new me("@firebase/app-check");async function wr(t){if(v()){let e=void 0;try{e=await vr(yr(t))}catch(e){_r.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function br(e,t){return v()?mr(yr(e),t).catch(e=>{_r.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Ir(){let e=void 0;try{e=await vr(pr)}catch(e){}if(e)return e;var t,n=Z();return t=n,mr(pr,t).catch(e=>_r.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function Tr(){return Jn.enabled}async function Er(){var e=Jn;if(e.enabled&&e.token)return e.token.promise;throw Error(`
7
+ `)}const wt=yt;et("@firebase/app-compat","0.1.38",void 0);wt.registerVersion("firebase","9.13.0","app-compat");var bt="@firebase/installations",It="0.5.16";const Tt=1e4,Et=`w:${It}`,kt="FIS_v2",St="https://firebaseinstallations.googleapis.com/v1",Ct=36e5;const At=new x("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 Nt(e){return e instanceof R&&e.code.includes("request-failed")}function Rt({projectId:e}){return`${St}/projects/${e}/installations`}function xt(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function Dt(e,t){var n=(await t.json()).error;return At.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Pt({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Ot(e,{refreshToken:t}){const n=Pt(e);return n.append("Authorization",(t=t,`${kt} ${t}`)),n}async function Mt(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function Lt(t){return new Promise(e=>{setTimeout(e,t)})}const Ft=/^[cdef][\w-]{21}$/,Ut="";function qt(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return Ft.test(e)?e:Ut}catch(e){return Ut}}function Vt(e){return`${e.appName}!${e.appId}`}const Bt=new Map;function jt(e,t){var n=Vt(e);Kt(n,t),function(e,t){const n=function(){!$t&&"BroadcastChannel"in self&&($t=new BroadcastChannel("[Firebase] FID Change"),$t.onmessage=e=>{Kt(e.data.key,e.data.fid)});return $t}();n&&n.postMessage({key:e,fid:t});0===Bt.size&&$t&&($t.close(),$t=null)}(n,t)}function Kt(e,t){var n=Bt.get(e);if(n)for(const r of n)r(t)}let $t=null;const Wt="firebase-installations-store";let zt=null;function Gt(){return zt=zt||Re("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(Wt)}}),zt}async function Ht(e,t){var n=Vt(e);const r=await Gt(),i=r.transaction(Wt,"readwrite"),s=i.objectStore(Wt);var a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||jt(e,t.fid),t}async function Qt(e){var t=Vt(e);const n=await Gt(),r=n.transaction(Wt,"readwrite");await r.objectStore(Wt).delete(t),await r.done}async function Yt(e,t){var n=Vt(e);const r=await Gt(),i=r.transaction(Wt,"readwrite"),s=i.objectStore(Wt);var a=await s.get(n),o=t(a);return void 0===o?await s.delete(n):await s.put(o,n),await i.done,!o||a&&a.fid===o.fid||jt(e,o.fid),o}async function Jt(n){let r;var e=await Yt(n.appConfig,e=>{var t=Zt(e||{fid:qt(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Xt(e.appConfig);for(;1===t.registrationStatus;)await Lt(100),t=await Xt(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await Jt(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(At.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=Rt(e),i=Pt(e),s=t.getImmediate({optional:!0});!s||(a=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",a);var a={fid:n,authVersion:kt,appId:e.appId,sdkVersion:Et};const o={method:"POST",headers:i,body:JSON.stringify(a)},c=await Mt(()=>fetch(r,o));if(c.ok){a=await c.json();return{fid:a.fid||n,registrationStatus:2,refreshToken:a.refreshToken,authToken:xt(a.authToken)}}throw await Dt("Create Installation",c)}(t,n);return Ht(t.appConfig,e)}catch(e){throw Nt(e)&&409===e.customData.serverCode?await Qt(t.appConfig):await Ht(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===Ut?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Xt(e){return Yt(e,e=>{if(!e)throw At.create("installation-not-found");return Zt(e)})}function Zt(e){return 1===(t=e).registrationStatus&&t.registrationTime+Tt<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function en({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Rt(i)}/${s}/authTokens:generate`);var i,s;const a=Ot(e,n),o=t.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",c);var c={installation:{sdkVersion:Et,appId:e.appId}};const l={method:"POST",headers:a,body:JSON.stringify(c)},u=await Mt(()=>fetch(r,l));if(u.ok)return xt(await u.json());throw await Dt("Generate Auth Token",u)}async function tn(r,i=!1){let s;var e=await Yt(r.appConfig,e=>{if(!rn(e))throw At.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+Ct}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await nn(e.appConfig);for(;1===n.authToken.requestStatus;)await Lt(100),n=await nn(e.appConfig);var r=n.authToken;return 0===r.requestStatus?tn(e,t):r}(r,i),e;if(!navigator.onLine)throw At.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await en(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await Ht(t.appConfig,e),r}catch(e){throw!Nt(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await Ht(t.appConfig,r)):await Qt(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function nn(e){return Yt(e,e=>{if(!rn(e))throw At.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Tt<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function rn(e){return void 0!==e&&2===e.registrationStatus}async function sn(e,t=!1){var n,r=e;return await((n=(await Jt(r)).registrationPromise)&&await n),(await tn(r,t)).token}function an(e){return At.create("missing-app-config-values",{valueName:e})}const on="installations",cn=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw an("App Configuration");if(!e.name)throw an("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw an(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:Ge(t,"heartbeat"),_delete:()=>Promise.resolve()}},ln=e=>{const t=Ge(e.getProvider("app").getImmediate(),on).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await Jt(t);return(r||tn(t)).catch(console.error),n.fid}(t),getToken:e=>sn(t,e)}};ze(new oe(on,cn,"PUBLIC")),ze(new oe("installations-internal",ln,"PRIVATE")),et(bt,It),et(bt,It,"esm2017");const un="analytics",hn="firebase_id",dn="origin",pn="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",fn="https://www.googletagmanager.com/gtag/js",gn=new me("@firebase/analytics");function mn(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function vn(r,i,s,a){return async function(e,t,n){try{"event"===e?await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await mn(r);for(const l of e){var a=c.find(e=>e.measurementId===l),o=a&&n[a.appId];if(!o){t=[];break}t.push(o)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){gn.error(e)}}(r,i,s,t,n):"config"===e?await async function(e,t,n,r,i,s){var a=r[i];try{if(a)await t[a];else{const c=await mn(n);var o=c.find(e=>e.measurementId===i);o&&await t[o.appId]}}catch(e){gn.error(e)}e("config",i,s)}(r,i,s,a,t,n):"consent"===e?r("consent","update",n):r("set",t)}catch(e){gn.error(e)}}}const yn=new x("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-intialized 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.'}),_n=30;const wn=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 bn(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=pn.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw yn.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function In(e,t=wn,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw yn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw yn.create("no-api-key")}var a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const o=new kn;return setTimeout(async()=>{o.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=wn){var a;const{appId:o,measurementId:c}=n;try{await Tn(i,e)}catch(e){if(c)return gn.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===(a=e)||void 0===a?void 0:a.message}]`),{appId:o,measurementId:c};throw e}try{const l=await bn(n);return s.deleteThrottleMetadata(o),l}catch(e){const u=e;if(!En(u)){if(s.deleteThrottleMetadata(o),c)return gn.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===u||void 0===u?void 0:u.message}]`),{appId:o,measurementId:c};throw e}const h=503===Number(null===(a=null===u||void 0===u?void 0:u.customData)||void 0===a?void 0:a.httpStatus)?se(r,s.intervalMillis,_n):se(r,s.intervalMillis),d={throttleEndTimeMillis:Date.now()+h,backoffCount:r+1};return s.setThrottleMetadata(o,d),gn.debug(`Calling attemptFetch again in ${h} millis`),t(n,d,i,s)}}({appId:r,apiKey:i,measurementId:s},a,o,t)}function Tn(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(yn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function En(e){if(!(e instanceof R&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class kn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Sn(t,e,n,r,i,s,a){const o=In(t);o.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&gn.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=>gn.error(e)),e.push(o);var c=async function(){if(!v())return gn.warn(yn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await y()}catch(e){return gn.warn(yn.create("indexeddb-unavailable",{errorInfo:null===e||void 0===e?void 0:e.toString()}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([o,c]);!function(e){var t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(fn)&&n.src.includes(e))return n}(s)&&function(e,t){const n=document.createElement("script");n.src=`${fn}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const h=null!==(c=null==a?void 0:a.config)&&void 0!==c?c:{};return h[dn]="firebase",h.update=!0,null!=u&&(h[hn]=u),i("config",l.measurementId,h),l.measurementId}class Cn{constructor(e){this.app=e}_delete(){return delete An[this.app.options.appId],Promise.resolve()}}let An={},Nn=[];const Rn={};let xn="dataLayer",Dn="gtag",Pn,On,Mn=!1;function Ln(e){if(Mn)throw yn.create("already-initialized");e.dataLayerName&&(xn=e.dataLayerName),e.gtagName&&(Dn=e.gtagName)}function Fn(e,t,n){!function(){const e=[];var t;d()&&e.push("This is a browser extension environment."),_()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=yn.create("invalid-analytics-context",{errorInfo:t}),gn.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw yn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw yn.create("no-api-key");gn.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!=An[s])throw yn.create("already-exists",{id:s});return Mn||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(xn),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=vn(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(An,Nn,Rn,xn,Dn),On=r,Pn=i,Mn=!0),An[s]=Sn(e,Nn,Rn,t,Pn,xn,n),new Cn(e)}async function Un(){if(d())return!1;if(!_())return!1;if(!v())return!1;try{return await y()}catch(e){return!1}}function qn(e,t,n){e=ae(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(On,An[e.app.options.appId],t,n).catch(e=>gn.error(e))}function Vn(e,t,n){e=ae(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(On,An[e.app.options.appId],t,n).catch(e=>gn.error(e))}function Bn(e,t,n){e=ae(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(On,An[e.app.options.appId],t,n).catch(e=>gn.error(e))}function jn(e,t){e=ae(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(An[e.app.options.appId],t).catch(e=>gn.error(e))}function Kn(e,t,n,r){e=ae(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(On,An[e.app.options.appId],t,n,r).catch(e=>gn.error(e))}const $n="@firebase/analytics";ze(new oe(un,(e,{options:t})=>{return Fn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),ze(new oe("analytics-internal",function(e){try{const r=e.getProvider(un).getImmediate();return{logEvent:(e,t,n)=>Kn(r,e,t,n)}}catch(e){throw yn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),et($n,"0.8.4"),et($n,"0.8.4","esm2017");var Wn,zn;class Gn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){Kn(this._delegate,e,t,n)}setCurrentScreen(e,t){qn(this._delegate,e,t)}setUserId(e,t){Vn(this._delegate,e,t)}setUserProperties(e,t){Bn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){jn(this._delegate,e)}}(KS=Wn=Wn||{}).ADD_SHIPPING_INFO="add_shipping_info",KS.ADD_PAYMENT_INFO="add_payment_info",KS.ADD_TO_CART="add_to_cart",KS.ADD_TO_WISHLIST="add_to_wishlist",KS.BEGIN_CHECKOUT="begin_checkout",KS.CHECKOUT_PROGRESS="checkout_progress",KS.EXCEPTION="exception",KS.GENERATE_LEAD="generate_lead",KS.LOGIN="login",KS.PAGE_VIEW="page_view",KS.PURCHASE="purchase",KS.REFUND="refund",KS.REMOVE_FROM_CART="remove_from_cart",KS.SCREEN_VIEW="screen_view",KS.SEARCH="search",KS.SELECT_CONTENT="select_content",KS.SELECT_ITEM="select_item",KS.SELECT_PROMOTION="select_promotion",KS.SET_CHECKOUT_OPTION="set_checkout_option",KS.SHARE="share",KS.SIGN_UP="sign_up",KS.TIMING_COMPLETE="timing_complete",KS.VIEW_CART="view_cart",KS.VIEW_ITEM="view_item",KS.VIEW_ITEM_LIST="view_item_list",KS.VIEW_PROMOTION="view_promotion",KS.VIEW_SEARCH_RESULTS="view_search_results";const Hn=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new Gn(t,n)};zn={Analytics:Gn,settings:Ln,isSupported:Un,EventName:Wn},wt.INTERNAL.registerComponent(new oe("analytics-compat",Hn,"PUBLIC").setServiceProps(zn).setMultipleInstances(!0)),wt.registerVersion("@firebase/analytics-compat","0.1.17");const Qn=new Map,Yn={activated:!1,tokenObservers:[]},Jn={initialized:!1,enabled:!1};function Xn(e){return Qn.get(e)||Yn}function Zn(e,t){Qn.set(e,t)}const er="https://content-firebaseappcheck.googleapis.com/v1",tr="exchangeDebugToken",nr={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class rr{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))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 A,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new A,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){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const ir=new x("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 sr(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function ar(e){if(!Xn(e).activated)throw ir.create("use-before-activation",{appName:e.name})}function or(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=cr(n)+"d:"),r&&(s+=cr(r)+"h:"),s+=cr(i)+"m:"+cr(t)+"s",s}function cr(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function lr({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});!i||(c=await i.getHeartbeatsHeader())&&(r["X-Firebase-Client"]=c);var s={method:"POST",body:JSON.stringify(t),headers:r};let a;try{a=await fetch(e,s)}catch(e){throw ir.create("fetch-network-error",{originalErrorMessage:null===e||void 0===e?void 0:e.message})}if(200!==a.status)throw ir.create("fetch-status-error",{httpStatus:a.status});let o;try{o=await a.json()}catch(e){throw ir.create("fetch-parse-error",{originalErrorMessage:null===e||void 0===e?void 0:e.message})}var c=o.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw ir.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${o.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:o.token,expireTimeMillis:c+s,issuedAtTimeMillis:c}}const ur="firebase-app-check-database",hr=1,dr="firebase-app-check-store",pr="debug-token";let fr=null;function gr(){return fr||(fr=new Promise((t,n)=>{try{const e=indexedDB.open(ur,hr);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(ir.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(dr,{keyPath:"compositeKey"})}}catch(e){n(ir.create("storage-open",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}}),fr)}async function mr(e,t){const n=await gr(),r=n.transaction(dr,"readwrite"),i=r.objectStore(dr),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(ir.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function vr(e){const t=await gr(),i=t.transaction(dr,"readonly"),n=i.objectStore(dr),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(ir.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function yr(e){return`${e.options.appId}-${e.name}`}const _r=new me("@firebase/app-check");async function wr(t){if(v()){let e=void 0;try{e=await vr(yr(t))}catch(e){_r.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function br(e,t){return v()?mr(yr(e),t).catch(e=>{_r.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Ir(){let e=void 0;try{e=await vr(pr)}catch(e){}if(e)return e;var t,n=Z();return t=n,mr(pr,t).catch(e=>_r.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function Tr(){return Jn.enabled}async function Er(){var e=Jn;if(e.enabled&&e.token)return e.token.promise;throw Error(`
8
8
  Can't get debug token in production mode.
9
- `)}const kr={error:"UNKNOWN_ERROR"};async function Cr(e,t=!1){var n=e.app;ar(n);const r=Xn(n);let i=r.token,s=void 0;if(i&&!xr(i)&&(Zn(n,Object.assign(Object.assign({},r),{token:void 0})),i=void 0),i||(o=await r.cachedTokenPromise)&&(xr(o)?i=o:await br(n,void 0)),!t&&i&&xr(i))return{token:i.token};let a=!1;if(Tr()){r.exchangeTokenPromise||(r.exchangeTokenPromise=lr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${er}/projects/${n}/apps/${r}:${tr}?key=${i}`,body:{debug_token:t}}}(n,await Er()),e.heartbeatServiceProvider).finally(()=>{r.exchangeTokenPromise=void 0}),a=!0);var o=await r.exchangeTokenPromise;return await br(n,o),Zn(n,Object.assign(Object.assign({},r),{token:o})),{token:o.token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().finally(()=>{r.exchangeTokenPromise=void 0}),a=!0),i=await r.exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?_r.warn(e.message):_r.error(e),s=e}let c;return i?s?c=xr(i)?{token:i.token,internalError:s}:Dr(s):(c={token:i.token},Zn(n,Object.assign(Object.assign({},r),{token:i})),await br(n,i)):c=Dr(s),a&&Rr(n,c),c}function Sr(e,t,n,r){var i=e["app"];const s=Xn(i);var a={next:n,error:r,type:t};if(Zn(i,Object.assign(Object.assign({},s),{tokenObservers:[...s.tokenObservers,a]})),s.token&&xr(s.token)){const o=s.token;Promise.resolve().then(()=>{n({token:o.token}),Nr(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Nr(e))}function Ar(e,t){const n=Xn(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),Zn(e,Object.assign(Object.assign({},n),{tokenObservers:r}))}function Nr(e){var t=e["app"],n=Xn(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new rr(async()=>{var e=Xn(r);let t;if(t=e.token?await Cr(n,!0):await Cr(n),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=Xn(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},nr.RETRIAL_MIN_WAIT,nr.RETRIAL_MAX_WAIT)}(e),Zn(t,Object.assign(Object.assign({},n),{tokenRefresher:r}))),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function Rr(e,t){for(const n of Xn(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function xr(e){return 0<e.expireTimeMillis-Date.now()}function Dr(e){return{token:(t=kr,r.encodeString(JSON.stringify(t),!1)),error:e};var t}class Pr{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=Xn(this.app)["tokenObservers"];for(const t of e)Ar(this.app,t.next);return Promise.resolve()}}const Or="https://www.google.com/recaptcha/api.js",Mr="https://www.google.com/recaptcha/enterprise.js";function Lr(t,n){var e=Xn(t);const r=new A;Zn(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=qr(t);e=sr(!1);return e?Ur(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Or,t.onload=e,document.head.appendChild(t)}(()=>{var e=sr(!1);if(!e)throw new Error("no recaptcha");Ur(t,n,e,i,r)}),r.promise}function Fr(t,n){var e=Xn(t);const r=new A;Zn(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=qr(t);e=sr(!0);return e?Ur(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Mr,t.onload=e,document.head.appendChild(t)}(()=>{var e=sr(!0);if(!e)throw new Error("no recaptcha");Ur(t,n,e,i,r)}),r.promise}function Ur(r,i,s,a,o){s.ready(()=>{var e,t,n;e=r,t=s.render(a,{sitekey:i,size:"invisible"}),n=Xn(e),Zn(e,Object.assign(Object.assign({},n),{reCAPTCHAState:Object.assign(Object.assign({},n.reCAPTCHAState),{widgetId:t})})),o.resolve(s)})}function qr(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function Vr(r){ar(r);const i=await Xn(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=Xn(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class Br{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){zr(this._throttleData);var t=await Vr(this._app).catch(e=>{throw ir.create("recaptcha-error")});let e;try{e=await lr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${er}/projects/${n}/apps/${r}:exchangeRecaptchaV3Token?key=${i}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=$r(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ir.create("throttled",{time:or(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=Ge(e,"heartbeat"),Lr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Br&&this._siteKey===e._siteKey}}class jr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){zr(this._throttleData);var t=await Vr(this._app).catch(e=>{throw ir.create("recaptcha-error")});let e;try{e=await lr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${er}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=$r(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ir.create("throttled",{time:or(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=Ge(e,"heartbeat"),Fr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof jr&&this._siteKey===e._siteKey}}class Kr{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=M(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof Kr&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function $r(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=se(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function zr(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw ir.create("throttled",{time:or(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Wr(e=Xe(),t){const n=Ge(e=ae(e),"app-check");if(Jn.initialized||function(){var e=w();const t=Jn;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new A;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Ir())}}(),Tr()&&Er().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.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw ir.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=Xn(t),i=Object.assign(Object.assign({},r),{activated:!0});i.provider=e,i.cachedTokenPromise=wr(t).then(e=>(e&&xr(e)&&(Zn(t,Object.assign(Object.assign({},Xn(t)),{token:e})),Rr(t,{token:e.token})),e)),i.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,Zn(t,i),i.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),Xn(e).isTokenAutoRefreshEnabled&&Sr(r,"INTERNAL",()=>{}),r}const Gr="app-check-internal";We(new oe("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new Pr(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(Gr).initialize()})),We(new oe(Gr,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>Cr(t,e),addTokenListener:e=>Sr(t,"INTERNAL",e),removeTokenListener:e=>Ar(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),et("@firebase/app-check","0.5.15");const Hr=new x("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 Qr{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new Br(e):e instanceof jr||e instanceof Br||e instanceof Kr?e:new Kr({getToken:e.getToken}),this._delegate=Wr(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw Hr.create("use-before-activation",{appName:this.app.name});!function(e,t){var n=e.app;const r=Xn(n);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),Zn(n,Object.assign(Object.assign({},r),{isTokenAutoRefreshEnabled:t}))}(this._delegate,e)}getToken(e){if(!this._delegate)throw Hr.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Cr(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw Hr.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Sr(e,"EXTERNAL",r,i),()=>Ar(e.app,r)}(this._delegate,e,t)}}const Yr=e=>{var t=e.getProvider("app-compat").getImmediate();return new Qr(t)};function Jr(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}wt.INTERNAL.registerComponent(new oe("appCheck-compat",Yr,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:jr,ReCaptchaV3Provider:Br,CustomProvider:Kr})),wt.registerVersion("@firebase/app-check-compat","0.2.15");const Xr={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},Zr={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 ei(){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 ti(){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 registed 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 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-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."}}const ni=ei,ri=new x("auth","Firebase",ei()),ii=new me("@firebase/auth");function si(e,...t){ii.logLevel<=k.ERROR&&ii.error(`Auth (${Ye}): ${e}`,...t)}function ai(e,...t){throw ui(e,...t)}function oi(e,...t){return ui(e,...t)}function ci(e,t,n){var r=Object.assign(Object.assign({},ni()),{[t]:n});const i=new x("auth","Firebase",r);return i.create(t,{appName:e.name})}function li(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&ai(e,"argument-error"),ci(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function ui(e,...t){if("string"==typeof e)return ri.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function hi(e,t,...n){if(!e)throw ui(t,...n)}function di(e){var t="INTERNAL ASSERTION FAILED: "+e;throw si(t),new Error(t)}function pi(e,t){e||di(t)}const fi=new Map;function gi(e){pi(e instanceof Function,"Expected a class definition");let t=fi.get(e);return t?pi(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,fi.set(e,t)),t}function mi(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function vi(){return"http:"===yi()||"https:"===yi()}function yi(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class _i{constructor(e,t){pi((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=o()||p()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(vi()||d()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function wi(e,t){pi(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class bi{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void di("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:void di("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:void di("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Ii={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:"internal-error",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",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"},Ti=new _i(3e4,6e4);function Ei(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function ki(i,s,a,o,e={}){return Ci(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var n=j(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),bi.fetch()(Ai(i,i.config.apiHost,a,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Ci(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Ii),e);try{const a=new Ni(t),o=await Promise.race([n(),a.promise]);a.clearNetworkTimeout();var i=await o.json();if("needConfirmation"in i)throw Ri(t,"account-exists-with-different-credential",i);if(o.ok&&!("errorMessage"in i))return i;{const c=o.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Ri(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Ri(t,"email-already-in-use",i);if("USER_DISABLED"===l)throw Ri(t,"user-disabled",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw ci(t,s,u);ai(t,s)}}catch(e){if(e instanceof R)throw e;ai(t,"network-request-failed")}}async function Si(e,t,n,r,i={}){var s=await ki(e,t,n,r,i);return"mfaPendingCredential"in s&&ai(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Ai(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?wi(e.config,i):`${e.config.apiScheme}://${i}`}class Ni{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(oi(this.auth,"network-request-failed")),Ti.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Ri(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=oi(e,t,r);return i.customData._tokenResponse=n,i}function xi(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Di(e){return 1e3*Number(e)}function Pi(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return si("JWT malformed, contained fewer than 3 sections"),null;try{var i=a(n);return i?JSON.parse(i):(si("Failed to decode base64 JWT payload"),null)}catch(e){return si("Caught error parsing JWT payload as JSON",null===e||void 0===e?void 0:e.toString()),null}}async function Oi(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof R&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class Mi{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){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return 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?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class Li{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=xi(this.lastLoginAt),this.creationTime=xi(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Fi(e){var t=e.auth,n=await e.getIdToken(),r=await Oi(e,async function(e,t){return ki(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));hi(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,a,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=Jr(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,a=t,[...s.filter(t=>!a.some(e=>e.providerId===t.providerId)),...a]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new Li(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class Ui{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){hi(e.idToken,"internal-error"),hi(void 0!==e.idToken,"internal-error"),hi(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,hi(n=Pi(t),"internal-error"),hi(void 0!==n.exp,"internal-error"),hi(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return hi(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:a}=(s=t,await{accessToken:(a=await Ci(i=e,{},async()=>{var e=j({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=Ai(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",bi.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:a.expires_in,refreshToken:a.refresh_token});this.updateTokensAndExpiration(n,r,Number(a))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new Ui;return n&&(hi("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(hi("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(hi("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 Ui,this.toJSON())}_performRefresh(){return di("not implemented")}}function qi(e,t){hi("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Vi{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=Jr(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Mi(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.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 Li(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Oi(this,this.stsTokenManager.getToken(this.auth,e));return hi(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 function(e,t=!1){const n=ae(e);var r=await n.getIdToken(t),i=Pi(r);hi(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,a=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:xi(Di(i.auth_time)),issuedAtTime:xi(Di(i.iat)),expirationTime:xi(Di(i.exp)),signInProvider:a||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=ae(e);await Fi(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(hi(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){return new Vi(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){hi(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await Fi(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await Oi(this,async function(e,t){return ki(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 n=null!==(a=t.displayName)&&void 0!==a?a:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(o=t.phoneNumber)&&void 0!==o?o:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,a=null!==(c=t.tenantId)&&void 0!==c?c:void 0,o=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:p,stsTokenManager:f}=t;hi(u&&f,e,"internal-error");var g=Ui.fromJSON(this.name,f);hi("string"==typeof u,e,"internal-error"),qi(n,e.name),qi(r,e.name),hi("boolean"==typeof h,e,"internal-error"),hi("boolean"==typeof d,e,"internal-error"),qi(i,e.name),qi(s,e.name),qi(a,e.name),qi(o,e.name),qi(c,e.name),qi(l,e.name);const m=new Vi({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:g,createdAt:c,lastLoginAt:l});return p&&Array.isArray(p)&&(m.providerData=p.map(e=>Object.assign({},e))),o&&(m._redirectEventId=o),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new Ui;r.updateFromServerResponse(t);var i=new Vi({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Fi(i),i}}class Bi{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){}}Bi.type="NONE";const ji=Bi;function Ki(e,t,n){return`firebase:${e}:${t}:${n}`}class $i{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=Ki(this.userKey,r.apiKey,i),this.fullPersistenceKey=Ki("persistence",r.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?Vi._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence!==e){var t=await this.getCurrentUser();return 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,n="authUser"){if(!t.length)return new $i(gi(ji),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||gi(ji);const s=Ki(n,e.config.apiKey,e.name);let a=null;for(const u of t)try{var o=await u._get(s);if(o){var c=Vi._fromJSON(e,o);u!==i&&(a=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new $i(i,e,n)}}function zi(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Qi(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Wi(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(Ji(t))return"Blackberry";if(Xi(t))return"Webos";if(Gi(t))return"Safari";if((t.includes("chrome/")||Hi(t))&&!t.includes("edge/"))return"Chrome";if(Yi(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function Wi(e=h()){return/firefox\//i.test(e)}function Gi(e=h()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function Hi(e=h()){return/crios\//i.test(e)}function Qi(e=h()){return/iemobile/i.test(e)}function Yi(e=h()){return/android/i.test(e)}function Ji(e=h()){return/blackberry/i.test(e)}function Xi(e=h()){return/webos/i.test(e)}function Zi(e=h()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function es(e=h()){return Zi(e)||Yi(e)||Xi(e)||Ji(e)||/windows phone/i.test(e)||Qi(e)}function ts(e,t=[]){let n;switch(e){case"Browser":n=zi(h());break;case"Worker":n=`${zi(h())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Ye}/${r}`}class ns{constructor(e){this.auth=e,this.queue=[]}pushCallback(r,e){var t=n=>new Promise((e,t)=>{try{e(r(n))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);const n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const r of t)try{r()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null===e||void 0===e?void 0:e.message})}}}}class rs{constructor(e,t,n){this.app=e,this.heartbeatServiceProvider=t,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ss(this),this.idTokenSubscription=new ss(this),this.beforeStateQueue=new ns(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=ri,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,n){return n&&(this._popupRedirectResolver=gi(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await $i.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0)}}async initializeCurrentUser(e){var t,n,r,i=await this.assertedPersistence.getCurrentUser();let s=i,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===s||void 0===s?void 0:s._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(s=r.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return hi(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 Fi(e)}catch(e){if("auth/network-request-failed"!==(null===e||void 0===e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?ae(e):null;return t&&hi(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&&hi(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 await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(gi(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new x("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(hi(t=e&&gi(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await $i.create(this,[gi(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?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?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?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return hi(s,this,"internal-error"),s.then(()=>i(this.currentUser)),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}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 hi(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=ts(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);var t=await(null===(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getHeartbeatsHeader());return t&&(e["X-Firebase-Client"]=t),e}}function is(e){return ae(e)}class ss{constructor(e){this.auth=e,this.observer=null,this.addObserver=W(e=>this.observer=e)}get next(){return hi(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function as(e,t,n){const r=is(e);hi(r._canInitEmulator,r,"emulator-config-failed"),hi(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=os(t);var{host:a,port:o}=function(e){const t=os(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:cs(r.substr(s.length+1))}}var[a,s]=r.split(":");return{host:a,port:cs(s)}}}(t);r.config.emulator={url:`${s}//${a}${null===o?"":`:${o}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const 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)}"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",e):e())}()}function os(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function cs(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class ls{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return di("not implemented")}_getIdTokenResponse(e){return di("not implemented")}_linkToIdToken(e,t){return di("not implemented")}_getReauthenticationResolver(e){return di("not implemented")}}async function us(e,t){return ki(e,"POST","/v1/accounts:resetPassword",Ei(e,t))}async function hs(e,t){return ki(e,"POST","/v1/accounts:update",t)}async function ds(e,t){return ki(e,"POST","/v1/accounts:sendOobCode",Ei(e,t))}class ps extends ls{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new ps(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new ps(e,t,"emailLink",n)}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 async function(e,t){return Si(e,"POST","/v1/accounts:signInWithPassword",Ei(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Si(e,"POST","/v1/accounts:signInWithEmailLink",Ei(e,t))}(e,{email:this._email,oobCode:this._password});default:ai(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return hs(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Si(e,"POST","/v1/accounts:signInWithEmailLink",Ei(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:ai(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function fs(e,t){return Si(e,"POST","/v1/accounts:signInWithIdp",Ei(e,t))}class gs extends ls{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new gs(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):ai("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:n,signInMethod:r}=t,t=Jr(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new gs(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return fs(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,fs(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,fs(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=j(t)}return e}}const ms={USER_NOT_FOUND:"user-not-found"};class vs extends ls{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new vs({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new vs({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Si(e,"POST","/v1/accounts:signInWithPhoneNumber",Ei(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Si(e,"POST","/v1/accounts:signInWithPhoneNumber",Ei(e,t));if(n.temporaryProof)throw Ri(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Si(e,"POST","/v1/accounts:signInWithPhoneNumber",Ei(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),ms)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const 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:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new vs({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class ys{constructor(e){var t=K($(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);hi(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=K($(e=e)).link,n=t?K($(t)).deep_link_id:null,((r=K($(e)).deep_link_id)?K($(r)).link:null)||r||n||t||e);try{return new ys(t)}catch(e){return null}}}class _s{constructor(){this.providerId=_s.PROVIDER_ID}static credential(e,t){return ps._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=ys.parseLink(t);return hi(n,"argument-error"),ps._fromEmailAndCode(e,n.code,n.tenantId)}}_s.PROVIDER_ID="password",_s.EMAIL_PASSWORD_SIGN_IN_METHOD="password",_s.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class ws{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 bs extends ws{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Is extends bs{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return hi("providerId"in t&&"signInMethod"in t,"argument-error"),gs._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return hi(e.idToken||e.accessToken,"argument-error"),gs._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Is.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Is.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:a}=e;if(!(n||r||t||i))return null;if(!a)return null;try{return new Is(a)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Ts extends bs{constructor(){super("facebook.com")}static credential(e){return gs._fromParams({providerId:Ts.PROVIDER_ID,signInMethod:Ts.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Ts.credentialFromTaggedObject(e)}static credentialFromError(e){return Ts.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Ts.credential(e.oauthAccessToken)}catch(e){return null}}}Ts.FACEBOOK_SIGN_IN_METHOD="facebook.com",Ts.PROVIDER_ID="facebook.com";class Es extends bs{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return gs._fromParams({providerId:Es.PROVIDER_ID,signInMethod:Es.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Es.credentialFromTaggedObject(e)}static credentialFromError(e){return Es.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Es.credential(t,n)}catch(e){return null}}}Es.GOOGLE_SIGN_IN_METHOD="google.com",Es.PROVIDER_ID="google.com";class ks extends bs{constructor(){super("github.com")}static credential(e){return gs._fromParams({providerId:ks.PROVIDER_ID,signInMethod:ks.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ks.credentialFromTaggedObject(e)}static credentialFromError(e){return ks.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return ks.credential(e.oauthAccessToken)}catch(e){return null}}}ks.GITHUB_SIGN_IN_METHOD="github.com",ks.PROVIDER_ID="github.com";class Cs extends ls{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return fs(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,fs(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,fs(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new Cs(t,r):null}static _create(e,t){return new Cs(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Ss extends ws{constructor(e){hi(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Ss.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Ss.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Cs.fromJSON(e);return hi(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return Cs._create(n,t)}catch(e){return null}}}class As extends bs{constructor(){super("twitter.com")}static credential(e,t){return gs._fromParams({providerId:As.PROVIDER_ID,signInMethod:As.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return As.credentialFromTaggedObject(e)}static credentialFromError(e){return As.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return As.credential(t,n)}catch(e){return null}}}async function Ns(e,t){return Si(e,"POST","/v1/accounts:signUp",Ei(e,t))}As.TWITTER_SIGN_IN_METHOD="twitter.com",As.PROVIDER_ID="twitter.com";class Rs{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await Vi._fromIdTokenResponse(e,n,r),s=xs(n);return new Rs({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=xs(n);return new Rs({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function xs(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Ds extends R{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,Ds.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new Ds(e,t,n,r)}}function Ps(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Ds._fromErrorAndOperation(t,e,n,r);throw e})}function Os(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Ms(e,t){const n=ae(e);await Fs(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await ki(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Os(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function Ls(e,t,n=!1){var r=await Oi(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Rs._forOperation(e,"link",r)}async function Fs(e,t,n){await Fi(t);const r=Os(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";hi(r.has(n)===e,t.auth,i)}async function Us(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await Oi(e,Ps(r,i,t,e),n);hi(s.idToken,r,"internal-error");var a=Pi(s.idToken);hi(a,r,"internal-error");var o=a["sub"];return hi(e.uid===o,r,"user-mismatch"),Rs._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null===e||void 0===e?void 0:e.code)&&ai(r,"user-mismatch"),e}}async function qs(e,t,n=!1){var r=await Ps(e,"signIn",t),r=await Rs._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function Vs(e,t){return qs(is(e),t)}async function Bs(e,t){var n=ae(e);return await Fs(!1,n,t.providerId),Ls(n,t)}async function js(e,t){return Us(ae(e),t)}async function Ks(e,t){const n=is(e);var r=await Si(n,"POST","/v1/accounts:signInWithCustomToken",Ei(n,{token:t,returnSecureToken:!0})),r=await Rs._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class $s{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?zs._fromServerResponse(e,t):ai(e,"internal-error")}}class zs extends $s{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new zs(t)}}function Ws(e,t,n){var r;hi(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),hi(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(hi(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(hi(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function Gs(e,t,n){var r=ae(e),i={requestType:"PASSWORD_RESET",email:t};n&&Ws(r,i,n),await ds(r,i)}async function Hs(e,t){await ki(e=ae(e),"POST","/v1/accounts:update",Ei(e,{oobCode:t}))}async function Qs(e,t){var n=ae(e),r=await us(n,{oobCode:t}),i=r.requestType;switch(hi(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":hi(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":hi(r.mfaInfo,n,"internal-error");default:hi(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=$s._fromServerResponse(is(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function Ys(e,t,n){var r=ae(e),i={requestType:"EMAIL_SIGNIN",email:t};hi(n.handleCodeInApp,r,"argument-error"),n&&Ws(r,i,n),await ds(r,i)}async function Js(e,t){var n=vi()?mi():"http://localhost",n=(await ki(e=ae(e),"POST","/v1/accounts:createAuthUri",Ei(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function Xs(e,t){var n=ae(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&Ws(n.auth,r,t);var r=(await ds(n.auth,r))["email"];r!==e.email&&await e.reload()}async function Zs(e,t,n){var r=ae(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&Ws(r.auth,i,n);var i=(await ds(r.auth,i))["email"];i!==e.email&&await e.reload()}async function ea(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=ae(e);var r=await i.getIdToken(),r=await Oi(i,async function(e,t){return ki(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function ta(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await Oi(e,hs(r,i));await e._updateTokensIfNecessary(r,!0)}class na{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class ra extends na{constructor(e,t,n,r){super(e,t,n),this.username=r}}class ia extends na{constructor(e,t){super(e,"facebook.com",t)}}class sa extends ra{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class aa extends na{constructor(e,t){super(e,"google.com",t)}}class oa extends ra{constructor(e,t,n){super(e,"twitter.com",t,n)}}function ca(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=Pi(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new na(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new ia(r,n);case"github.com":return new sa(r,n);case"google.com":return new aa(r,n);case"twitter.com":return new oa(r,n,e.screenName||null);case"custom":case"anonymous":return new na(r,null);default:return new na(r,t,n)}}(n)}class la{constructor(e,t,n){this.type=e,this.credential=t,this.auth=n}static _fromIdtoken(e,t){return new la("enroll",e,t)}static _fromMfaPendingCredential(e){return new la("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)&&void 0!==t&&t.pendingCredential)return la._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return la._fromIdtoken(e.multiFactorSession.idToken)}return null}}class ua{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=is(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>$s._fromServerResponse(s,e));hi(a.mfaPendingCredential,s,"internal-error");const o=la._fromMfaPendingCredential(a.mfaPendingCredential);return new ua(o,t,async e=>{var t=await e._process(s,o);delete a.mfaInfo,delete a.mfaPendingCredential;var n=Object.assign(Object.assign({},a),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Rs._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return hi(i.user,s,"internal-error"),Rs._forOperation(i.user,i.operationType,n);default:ai(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class ha{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>$s._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new ha(e)}async getSession(){return la._fromIdtoken(await this.user.getIdToken(),this.user.auth)}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Oi(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r=await this.user.getIdToken(),r=await Oi(this.user,(n=this.user.auth,e={idToken:r,mfaEnrollmentId:t},ki(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Ei(n,e))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(r);try{await this.user.reload()}catch(e){if("auth/user-token-expired"!==(null===e||void 0===e?void 0:e.code))throw e}}}const da=new WeakMap;const pa="__sak";class fa{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(pa,"1"),this.storage.removeItem(pa),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 ga extends fa{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(Gi(e=h())||Zi(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=es(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);g()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){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]}}ga.type="LOCAL";const ma=ga;class va extends fa{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}va.type="SESSION";const ya=va;class _a{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));if(e)return e;e=new _a(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),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:n,eventType:r,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 wa(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}_a.receivers=[];class ba{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){const o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=wa("",20);o.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},a);l={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),o.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[o.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function Ia(){return window}function Ta(){return void 0!==Ia().WorkerGlobalScope&&"function"==typeof Ia().importScripts}const Ea="firebaseLocalStorageDb",ka="firebaseLocalStorage",Ca="fbase_key";class Sa{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 Aa(e,t){return e.transaction([ka],t?"readwrite":"readonly").objectStore(ka)}function Na(){const r=indexedDB.open(Ea,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(ka,{keyPath:Ca})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(ka)?n(e):(e.close(),t=indexedDB.deleteDatabase(Ea),await new Sa(t).toPromise(),n(await Na()))})})}async function Ra(e,t,n){var r=Aa(e,!0).put({fbase_key:t,value:n});return new Sa(r).toPromise()}function xa(e,t){var n=Aa(e,!0).delete(t);return new Sa(n).toPromise()}class Da{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 Na(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Ta()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=_a._getInstance(Ta()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new ba(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;var e=await Na();return await Ra(e,pa,"1"),await xa(e,pa),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ra(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=Aa(e,!1).get(t);return void 0===(n=await new Sa(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>xa(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=Aa(e,!1).getAll();return new Sa(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(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()}}Da.type="LOCAL";const Pa=Da;function Oa(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=oi("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function Ma(e){return`__${e}${Math.floor(1e6*Math.random())}`}class La{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new Fa(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class Fa{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;hi(r,"argument-error",{appName:t}),this.container=r,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=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{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!")}}const Ua=Ma("rcb"),qa=new _i(3e4,6e4);class Va{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null===(e=Ia().grecaptcha)||void 0===e||!e.render)}load(s,a=""){var e;return hi((e=a).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(a)?Promise.resolve(Ia().grecaptcha):new Promise((t,n)=>{const i=Ia().setTimeout(()=>{n(oi(s,"network-request-failed"))},qa.get());Ia()[Ua]=()=>{Ia().clearTimeout(i),delete Ia()[Ua];const e=Ia().grecaptcha;if(e){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=a,t(e)}else n(oi(s,"internal-error"))},Oa(`https://www.google.com/recaptcha/api.js??${j({onload:Ua,render:"explicit",hl:a})}`).catch(()=>{clearTimeout(i),n(oi(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null===(t=Ia().grecaptcha)||void 0===t||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class Ba{async load(e){return new La(e)}clearedOneInstance(){}}const ja="recaptcha",Ka={theme:"light",type:"image"};class $a{constructor(e,t=Object.assign({},Ka),n){this.parameters=t,this.type=ja,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=is(n),this.isInvisible="invisible"===this.parameters.size,hi("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof e?document.getElementById(e):e;hi(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?Ba:Va),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.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(){hi(!this.parameters.sitekey,this.auth,"argument-error"),hi(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),hi("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=Ia()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){hi(!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(){hi(vi()&&!Ta(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).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 ki(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");hi(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return hi(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class za{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=vs._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function Wa(t,n,r){var i,s,a,o,c,l,u=await r.verify();try{hi("string"==typeof u,t,"argument-error"),hi(r.type===ja,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return hi("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await ki(c,"POST","/v2/accounts/mfaEnrollment:start",Ei(c,l))).phoneSessionInfo.sessionInfo;hi("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return hi(d,t,"missing-multi-factor-info"),(o={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await ki(t,"POST","/v2/accounts/mfaSignIn:start",Ei(t,o))).phoneResponseInfo.sessionInfo}var p=(s=t,a={phoneNumber:e.phoneNumber,recaptchaToken:u},await ki(s,"POST","/v1/accounts:sendVerificationCode",Ei(s,a)))["sessionInfo"];return p}finally{r._reset()}}class Ga{constructor(e){this.providerId=Ga.PROVIDER_ID,this.auth=is(e)}verifyPhoneNumber(e,t){return Wa(this.auth,e,ae(t))}static credential(e,t){return vs._fromVerification(e,t)}static credentialFromResult(e){var t=e;return Ga.credentialFromTaggedObject(t)}static credentialFromError(e){return Ga.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?vs._fromTokenResponse(t,n):null}}function Ha(e,t){return t?gi(t):(hi(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}Ga.PROVIDER_ID="phone",Ga.PHONE_SIGN_IN_METHOD="phone";class Qa extends ls{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return fs(e,this._buildIdpRequest())}_linkToIdToken(e,t){return fs(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return fs(e,this._buildIdpRequest())}_buildIdpRequest(e){const 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 Ya(e){return qs(e.auth,new Qa(e),e.bypassAuthState)}function Ja(e){var{auth:t,user:n}=e;return hi(n,t,"internal-error"),Us(n,new Qa(e),e.bypassAuthState)}async function Xa(e){var{auth:t,user:n}=e;return hi(n,t,"internal-error"),Ls(n,new Qa(e),e.bypassAuthState)}class Za{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,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:n,postBody:r,tenantId:i,error:s,type:a}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Ya;case"linkViaPopup":case"linkViaRedirect":return Xa;case"reauthViaPopup":case"reauthViaRedirect":return Ja;default:ai(this.auth,"internal-error")}}resolve(e){pi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){pi(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()}}const eo=new _i(2e3,1e4);class to extends Za{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,to.currentPopupAction&&to.currentPopupAction.cancel(),to.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return hi(e,this.auth,"internal-error"),e}async onExecution(){pi(1===this.filter.length,"Popup operations only handle one event");var e=wa();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(oi(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(oi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,to.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(oi(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(t,eo.get())};t()}}to.currentPopupAction=null;const no="pendingRedirect",ro=new Map;class io extends Za{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=ro.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=co(t),r=oo(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}ro.set(this.auth._key(),t)}return this.bypassAuthState||ro.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function so(e,t){return oo(e)._set(co(t),"true")}function ao(e,t){ro.set(e._key(),t)}function oo(e){return gi(e._redirectPersistence)}function co(e){return Ki(no,e.config.apiKey,e.name)}function lo(e,t,n){return async function(e,t,n){var r=is(e);li(e,t,ws);const i=Ha(r,n);return await so(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function uo(e,t,n){return async function(e,t,n){var r=ae(e);li(r.auth,t,ws);const i=Ha(r.auth,n);await so(i,r.auth);var s=await fo(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function ho(e,t,n){return async function(e,t,n){var r=ae(e);li(r.auth,t,ws);const i=Ha(r.auth,n);await Fs(!1,r,t.providerId),await so(i,r.auth);var s=await fo(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function po(e,t,n=!1){const r=is(e);var i=Ha(r,t);const s=new io(r,i,n),a=await s.execute();return a&&!n&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}async function fo(e){var t=wa(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class go{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 n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return vo(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!vo(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(oi(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(mo(e))}saveEventToCache(e){this.cachedEventUids.add(mo(e)),this.lastProcessedEventTime=Date.now()}}function mo(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function vo({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function yo(e,t={}){return ki(e,"GET","/v1/projects",t)}const _o=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,wo=/^https?/;async function bo(e){if(!e.config.emulator){var t=(await yo(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=mi(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!wo.test(n))return!1;if(_o.test(e))return r===e;const s=e.replace(/\./g,"\\."),a=new RegExp("^(.+\\."+s+"|"+s+")$","i");return a.test(r)}(n))return}catch(e){}ai(e,"unauthorized-domain")}}const Io=new _i(3e4,6e4);function To(){const t=Ia().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let Eo=null;function ko(e){var i;return Eo=Eo||(i=e,new Promise((e,t)=>{function n(){To(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{To(),t(oi(i,"network-request-failed"))},timeout:Io.get()})}if(null!==(r=null===(r=Ia().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=Ia().gapi)||void 0===r||!r.load){var r=Ma("iframefcb");return Ia()[r]=()=>{gapi.load?n():t(oi(i,"network-request-failed"))},Oa(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw Eo=null,e})),Eo}const Co=new _i(5e3,15e3),So="__/auth/iframe",Ao="emulator/auth/iframe",No={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Ro=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function xo(a){const e=await ko(a);var t=Ia().gapi;return hi(t,a,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;hi(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?wi(t,Ao):`https://${e.config.authDomain}/${So}`;const r={apiKey:t.apiKey,appName:e.name,v:Ye};(t=Ro.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${j(r).slice(1)}`}(a),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:No,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=oi(a,"network-request-failed"),r=Ia().setTimeout(()=>{t(n)},Co.get());function i(){Ia().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const Do={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Po{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Oo(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let o="";const c=Object.assign(Object.assign({},Do),{width:r.toString(),height:i.toString(),top:s,left:a});s=h().toLowerCase();n&&(o=Hi(s)?"_blank":n),Wi(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,a=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=h()]=[s],Zi(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==o)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",o),new Po(null);const u=window.open(t||"",o,a);hi(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Po(u)}const Mo="__/auth/handler",Lo="emulator/auth/handler";function Fo(e,t,n,r,i,s){hi(e.config.authDomain,e,"auth-domain-config-required"),hi(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Ye,eventId:i};if(t instanceof ws){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",U(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,c]of Object.entries(s||{}))a[o]=c}if(t instanceof bs){const u=t.getScopes().filter(e=>""!==e);0<u.length&&(a.scopes=u.join(","))}e.tenantId&&(a.tid=e.tenantId);const l=a;for(const h of Object.keys(l))void 0===l[h]&&delete l[h];return`${e=[e["config"]][0],e.emulator?wi(e,Lo):`https://${e.authDomain}/${Mo}`}?${j(l).slice(1)}`}const Uo="webStorageSupport";const qo=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=ya,this._completeRedirectFn=po,this._overrideRedirectResult=ao}async _openPopup(e,t,n,r){var i;return pi(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),Oo(e,Fo(e,t,n,mi(),r),wa())}async _openRedirect(e,t,n,r){return await this._originValidation(e),r=Fo(e,t,n,mi(),r),Ia().location.href=r,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(pi(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await xo(t),n=new go(t);return e.register("authEvent",e=>{return hi(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(Uo,{type:Uo},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[Uo];void 0!==t&&r(!!t),ai(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=bo(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return es()||Gi()||Zi()}};class Vo extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return di("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new Vo(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},ki(e,"POST","/v2/accounts/mfaEnrollment:finalize",Ei(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},ki(e,"POST","/v2/accounts/mfaSignIn:finalize",Ei(e,t))}}class Bo{constructor(){}static assertion(e){return Vo._fromCredential(e)}}Bo.FACTOR_ID="phone";var jo="@firebase/auth",Ko="0.20.10";class $o{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null===e||void 0===e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){hi(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var zo,Wo,Go;function Ho(){return window}zo="authIdTokenMaxAge",null===(Wo=T())||void 0===Wo||Wo[`_${zo}`],Go="Browser",We(new oe("auth",(e,{options:r})=>{var t=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");const{apiKey:i,authDomain:s}=t.options;return((e,t)=>{hi(i&&!i.includes(":"),"invalid-api-key",{appName:e.name}),hi(!(null!==s&&void 0!==s&&s.includes(":")),"argument-error",{appName:e.name});var n={apiKey:i,authDomain:s,clientPlatform:Go,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:ts(Go)},n=new rs(e,t,n);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(gi);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(n,r),n})(t,n)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),We(new oe("auth-internal",e=>{var t=is(e.getProvider("auth").getImmediate());return e=t,new $o(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),et(jo,Ko,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Go)),et(jo,Ko,"esm2017");async function Qo(e,t,n){var r=Ho()["BuildInfo"];pi(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(pi(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return Zi()?s.ibi=r.packageName:Yi()?s.apn=r.packageName:ai(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,Fo(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function Yo(r){const i=Ho()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=h(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const Jo=20;class Xo extends go{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function Zo(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<Jo;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:oi(e,"no-auth-event")}}async function ec(e){var t=await nc()._get(rc(e));return t&&await nc()._remove(rc(e)),t}function tc(e,t){var n,r,i;const s=(n=ic(t=t),a=n.link?decodeURIComponent(n.link):void 0,r=ic(a).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=ic(i).link)||i||r||a||t);if(s.includes("/__/auth/callback")){var a=ic(s),a=a.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(a.firebaseError)):null,a=null===(a=null===(a=null==a?void 0:a.code)||void 0===a?void 0:a.split("auth/"))||void 0===a?void 0:a[1],a=a?oi(a):null;return a?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:a,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function nc(){return gi(ma)}function rc(e){return Ki("authEvent",e.config.apiKey,e.name)}function ic(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return K(t.join("?"))}const sc=class{constructor(){this._redirectPersistence=ya,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=po,this._overrideRedirectResult=ao}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new Xo(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){ai(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,o=Ho(),hi("function"==typeof(null===(s=null==o?void 0:o.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),hi(void 0!==(null===(s=null==o?void 0:o.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),hi("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),hi("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),hi("function"==typeof(null===(o=null===(o=null==o?void 0:o.cordova)||void 0===o?void 0:o.InAppBrowser)||void 0===o?void 0:o.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const a=await this._initialize(e);await a.initialized(),a.resetRedirect(),ro.clear(),await this._originValidation(e);var o=Zo(e,n,r);n=e,r=o,await nc()._set(rc(n),r);o=await Yo(await Qo(e,o,t));return async function(a,o,c){const l=Ho()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(oi(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}o.addPassiveListener(r),document.addEventListener("resume",i,!1),Yi()&&document.addEventListener("visibilitychange",s,!1),u=()=>{o.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,a,o)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=Ho()["BuildInfo"];const n={};Zi()?n.iosBundleId=t.packageName:Yi()?n.androidPackageName=t.packageName:ai(e,"operation-not-supported-in-this-environment"),await yo(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=Ho(),s=setTimeout(async()=>{await ec(r),i.onEvent(ac())},500),a=async e=>{clearTimeout(s);var t=await ec(r);let n=null;t&&null!=e&&e.url&&(n=tc(t,e.url)),i.onEvent(n||ac())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a);const o=t,c=`${n.packageName.toLowerCase()}://`;Ho().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}};function ac(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:oi("no-auth-event")}}var oc;function cc(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function lc(e=h()){return!("file:"!==cc()&&"ionic:"!==cc()&&"capacitor:"!==cc()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function uc(e=h()){return g()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=h()]=[e],/Edge\/\d+/.test(e))}function hc(){try{const t=self.localStorage;var e=wa();if(t)return t.setItem(e,"1"),t.removeItem(e),!uc()||v()}catch(e){return dc()&&v()}return!1}function dc(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function pc(){return("http:"===cc()||"https:"===cc()||d()||lc())&&!(p()||l())&&hc()&&!dc()}function fc(){return lc()&&"undefined"!=typeof document}const gc={LOCAL:"local",NONE:"none",SESSION:"session"},mc=hi,vc="persistence";async function yc(e){await e._initializationPromise;const t=_c();var n=Ki(vc,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function _c(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const wc=hi;class bc{constructor(){this.browserResolver=gi(qo),this.cordovaResolver=gi(sc),this.underlyingResolver=null,this._redirectPersistence=ya,this._completeRedirectFn=po,this._overrideRedirectResult=ao}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return fc()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return wc(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!fc()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Ic(e){return e.unwrap()}function Tc(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===(null===t||void 0===t?void 0:t.code)){const o=t;o.resolver=new Sc(e,(n=t,i=ae(e),hi((a=n).customData.operationType,i,"argument-error"),hi(null===(r=a.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),ua._fromError(i,a)))}else if(s){var a=Ec(t);const c=t;a&&(c.credential=a,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Ec(e){var t=(e instanceof R?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof R)&&"temporaryProof"in t&&"phoneNumber"in t)return Ga.credentialFromResult(e);const n=t.providerId;if(!n||n===Xr.PASSWORD)return null;let r;switch(n){case Xr.GOOGLE:r=Es;break;case Xr.FACEBOOK:r=Ts;break;case Xr.GITHUB:r=ks;break;case Xr.TWITTER:r=As;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:c}=t;return s||a||i||o?o?n.startsWith("saml.")?Cs._create(n,o):gs._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:i,accessToken:s}):new Is(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof R?r.credentialFromError(e):r.credentialFromResult(e)}function kc(t,e){return e.catch(e=>{throw e instanceof R&&Tc(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Ec(e),additionalUserInfo:ca(e),user:Ac.getOrCreate(n)}})}async function Cc(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>kc(t,n.confirm(e))}}class Sc{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 kc(Ic(this.auth),this.resolver.resolveSignIn(e))}}class Ac{constructor(e){var t;this._delegate=e,this.multiFactor=(t=ae(e),da.has(t)||da.set(t,ha._fromUser(t)),da.get(t))}static getOrCreate(e){return Ac.USER_MAP.has(e)||Ac.USER_MAP.set(e,new Ac(e)),Ac.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 kc(this.auth,Bs(this._delegate,e))}async linkWithPhoneNumber(e,t){return Cc(this.auth,async function(e,t,n){const r=ae(e);await Fs(!1,r,"phone");var i=await Wa(r.auth,t,ae(n));return new za(i,e=>Bs(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return kc(this.auth,async function(e,t,n){var r=ae(e);li(r.auth,t,ws);var i=Ha(r.auth,n);const s=new to(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,bc))}async linkWithRedirect(e){return await yc(is(this.auth)),ho(this._delegate,e,bc)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return kc(this.auth,js(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Cc(this.auth,async function(e,t,n){const r=ae(e);var i=await Wa(r.auth,t,ae(n));return new za(i,e=>js(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return kc(this.auth,async function(e,t,n){var r=ae(e);li(r.auth,t,ws);var i=Ha(r.auth,n);const s=new to(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,bc))}async reauthenticateWithRedirect(e){return await yc(is(this.auth)),uo(this._delegate,e,bc)}sendEmailVerification(e){return Xs(this._delegate,e)}async unlink(e){return await Ms(this._delegate,e),this}updateEmail(e){return ta(ae(this._delegate),e,null)}updatePassword(e){return ta(ae(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await Ls(ae(e),t)}(this._delegate,e)}updateProfile(e){return ea(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return Zs(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}}Ac.USER_MAP=new WeakMap;const Nc=hi;class Rc{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Nc(n,"invalid-api-key",{appName:e.name}),Nc(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?bc:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=_c();if(!n)return[];var r=Ki(vc,e,t);switch(n.getItem(r)){case gc.NONE:return[ji];case gc.LOCAL:return[Pa,ya];case gc.SESSION:return[ya];default:return[]}}(e,t);"undefined"==typeof self||n.includes(Pa)||n.push(Pa);if("undefined"!=typeof window)for(const r of[ma,ya])n.includes(r)||n.push(r);n.includes(ji)||n.push(ji);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(ti),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Ac.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){as(this._delegate,e,t)}applyActionCode(e){return Hs(this._delegate,e)}checkActionCode(e){return Qs(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await us(ae(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return kc(this._delegate,async function(e,t,n){const r=is(e);var i=await Ns(r,{returnSecureToken:!0,email:t,password:n}),i=await Rs._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(i.user),i}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return Js(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=ys.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Nc(pc(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=bc,await is(e)._initializationPromise,await po(e,t,!1));return n?kc(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){is(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=xc(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=xc(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return Ys(this._delegate,e,t)}sendPasswordResetEmail(e,t){return Gs(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,mc(Object.values(gc).includes(n),t,"invalid-persistence-type"),p()?mc(n!==gc.SESSION,t,"unsupported-persistence-type"):l()?mc(n===gc.NONE,t,"unsupported-persistence-type"):dc()?mc(n===gc.NONE||n===gc.LOCAL&&v(),t,"unsupported-persistence-type"):mc(n===gc.NONE||hc(),t,"unsupported-persistence-type");let r;switch(e){case gc.SESSION:r=ya;break;case gc.LOCAL:var i=await gi(Pa)._isAvailable();r=i?Pa:ma;break;case gc.NONE:r=ji;break;default:return ai("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return kc(this._delegate,async function(e){const t=is(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Rs({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await Ns(t,{returnSecureToken:!0}),n=await Rs._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return kc(this._delegate,Vs(this._delegate,e))}signInWithCustomToken(e){return kc(this._delegate,Ks(this._delegate,e))}signInWithEmailAndPassword(e,t){return kc(this._delegate,(n=this._delegate,e=e,t=t,Vs(ae(n),_s.credential(e,t))));var n}signInWithEmailLink(e,t){return kc(this._delegate,async function(e,t,n){var r=ae(e),i=_s.credentialWithLink(t,n||mi());return hi(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),Vs(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Cc(this._delegate,async function(e,t,n){const r=is(e);var i=await Wa(r,t,ae(n));return new za(i,e=>Vs(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Nc(pc(),this._delegate,"operation-not-supported-in-this-environment"),kc(this._delegate,async function(e,t,n){var r=is(e);li(e,t,ws);var i=Ha(r,n);const s=new to(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,bc))}async signInWithRedirect(e){return Nc(pc(),this._delegate,"operation-not-supported-in-this-environment"),await yc(this._delegate),lo(this._delegate,e,bc)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await Qs(ae(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function xc(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&Ac.getOrCreate(e)),error:t,complete:n}}Rc.Persistence=gc;class Dc{constructor(){this.providerId="phone",this._delegate=new Ga(Ic(wt.auth()))}static credential(e,t){return Ga.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Dc.PHONE_SIGN_IN_METHOD=Ga.PHONE_SIGN_IN_METHOD,Dc.PROVIDER_ID=Ga.PROVIDER_ID;const Pc=hi;class Oc{constructor(e,t,n=wt.app()){var r;Pc(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new $a(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(oc=wt).INTERNAL.registerComponent(new oe("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new Rc(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:Zr.EMAIL_SIGNIN,PASSWORD_RESET:Zr.PASSWORD_RESET,RECOVER_EMAIL:Zr.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:Zr.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:Zr.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:Zr.VERIFY_EMAIL}},EmailAuthProvider:_s,FacebookAuthProvider:Ts,GithubAuthProvider:ks,GoogleAuthProvider:Es,OAuthProvider:Is,SAMLAuthProvider:Ss,PhoneAuthProvider:Dc,PhoneMultiFactorGenerator:Bo,RecaptchaVerifier:Oc,TwitterAuthProvider:As,Auth:Rc,AuthCredential:ls,Error:R}).setInstantiationMode("LAZY").setMultipleInstances(!1)),oc.registerVersion("@firebase/auth-compat","0.2.23");const Mc="@firebase/database";let Lc="";function Fc(e){Lc=e}class Uc{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),O(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:P(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class qc{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return L(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var Vc,Bc,jc,Kc,$c,zc,Wc=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new Uc(t)}}catch(e){}return new qc};function Gc(e){var t=function(t){const n=[];let r=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);var i,s;55296<=e&&e<=56319&&(i=e-55296,a++,f(a<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(a)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new z;return n.update(t),t=n.digest(),r.encodeByteArray(t)}const Hc=Wc("localStorage"),Qc=Wc("sessionStorage"),Yc=new me("@firebase/database"),Jc=function(){let e=1;return function(){return e++}}(),Xc=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=Xc.apply(null,n):t+="object"==typeof n?O(n):n,t+=" "}return t};let Zc=null,el=!0;function tl(t){return function(...e){cl(t,...e)}}function nl(...e){var t="FIREBASE INTERNAL ERROR: "+Xc(...e);Yc.error(t)}function rl(e,t){return e===t?0:e<t?-1:1}function il(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+O(t))}function sl(e){if("object"!=typeof e||null===e)return O(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=O(t[i]),n+=":",n+=sl(e[t[i]]);return n+="}",n}function al(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const ol=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(Yc.logLevel=k.VERBOSE,Zc=Yc.log.bind(Yc),t&&Qc.set("logging_enabled",!0)):"function"==typeof e?Zc=e:(Zc=null,Qc.remove("logging_enabled"))},cl=function(...e){var t;!0===el&&(el=!1,null===Zc&&!0===Qc.get("logging_enabled")&&ol(!0)),Zc&&(t=Xc.apply(null,e),Zc(t))},ll=function(...e){var t=`FIREBASE FATAL ERROR: ${Xc(...e)}`;throw Yc.error(t),new Error(t)},ul=function(...e){var t="FIREBASE WARNING: "+Xc(...e);Yc.warn(t)},hl=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&ul("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},dl=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},pl="[MIN_NAME]",fl="[MAX_NAME]",gl=function(e,t){if(e===t)return 0;if(e===pl||t===fl)return-1;if(t===pl||e===fl)return 1;var n=Il(e),r=Il(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function ml(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function vl(e){f(!dl(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const a=[];for(s=52;s;--s)a.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse();const o=a.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(o.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function yl(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}const _l=new RegExp("^-?(0*)\\d{1,10}$"),wl=-2147483648,bl=2147483647,Il=function(e){if(_l.test(e)){var t=Number(e);if(t>=wl&&t<=bl)return t}return null},Tl=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw ul("Exception was thrown by user callback.",e),t},Math.floor(0))}};class El{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(e=>this.appCheck=e)}getToken(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){ul(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class kl{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(cl("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',ul(e)}}class Cl{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Cl.OWNER="owner";const Sl=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Al="websocket",Nl="long_polling";class Rl{constructor(e,t,n,r,i=!1,s="",a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Hc.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()&&Hc.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 xl(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===Al)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Nl)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return ml(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class Dl{constructor(){this.counters_={}}incrementCounter(e,t=1){L(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return c(void 0,this.counters_)}}const Pl={},Ol={};function Ml(e){var t=e.toString();return Pl[t]||(Pl[t]=new Dl),Pl[t]}class Ll{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&Tl(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Fl{constructor(e,t,n,r,i,s,a){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=tl(e),this.stats_=Ml(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),xl(t,Nl,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Ll(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new Ul((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Sl.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Fl.forceAllow_=!0}static forceDisallow(){Fl.forceDisallow_=!0}static isAvailable(){return!!Fl.forceAllow_||!(Fl.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=O(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=i(t),n=al(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=O(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Ul{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=Jc(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=Ul.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){cl("frame writing exception"),e.stack&&cl(e.stack),cl(e)}}}static createIFrame_(){const 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||cl("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{cl("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let ql=null;"undefined"!=typeof MozWebSocket?ql=MozWebSocket:"undefined"!=typeof WebSocket&&(ql=WebSocket);class Vl{constructor(e,t,n,r,i,s,a){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=tl(this.connId),this.stats_=Ml(t),this.connURL=Vl.connectionURL_(t,s,a,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={v:"5"};return"undefined"!=typeof location&&location.hostname&&Sl.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),xl(e,Al,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Hc.set("previous_websocket_failure",!0);try{m(),this.mySock=new ql(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Vl.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==ql&&!Vl.forceDisallow_}static previouslyFailed(){return Hc.isInMemoryStorage||!0===Hc.get("previous_websocket_failure")}markConnectionHealthy(){Hc.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=P(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=O(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=al(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}Vl.responsesRequiredToBeHealthy=2,Vl.healthyTimeout=3e4;class Bl{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Fl,Vl]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){var t=Vl&&Vl.isAvailable();let n=t&&!Vl.previouslyFailed();if(e.webSocketOnly&&(t||ul("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[Vl];else{const r=this.transports_=[];for(const i of Bl.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i);Bl.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}}Bl.globalTransportInitialized_=!1;class jl{constructor(e,t,n,r,i,s,a,o,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=o,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=tl("c:"+this.id+":"),this.transportManager_=new Bl(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=yl(()=>{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(r)))}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=il("t",e),n=il("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=il("t",e),n=il("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=il("t",e);if("d"in e){var n=e.d;if("h"===t)this.onHandshake_(n);else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?nl("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):nl("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&ul("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),yl(()=>{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):yl(()=>{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()&&(Hc.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 Kl{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class $l{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class zl extends $l{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||o()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new zl}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class Wl{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function Gl(){return new Wl("")}function Hl(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function Ql(e){return e.pieces_.length-e.pieceNum_}function Yl(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new Wl(e.pieces_,t)}function Jl(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function Xl(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function Zl(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new Wl(t,0)}function eu(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof Wl)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new Wl(n,0)}function tu(e){return e.pieceNum_>=e.pieces_.length}function nu(e,t){var n=Hl(e),r=Hl(t);if(null===n)return t;if(n===r)return nu(Yl(e),Yl(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function ru(e,t){var n=Xl(e,0),r=Xl(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=gl(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function iu(e,t){if(Ql(e)!==Ql(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function su(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(Ql(e)>Ql(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class au{constructor(e,t){this.errorPrefix_=t,this.parts_=Xl(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=ee(this.parts_[n]);ou(this)}}function ou(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+cu(e))}function cu(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class lu extends $l{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)}static getInstance(){return new lu}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class uu extends Kl{constructor(e,t,n,r,i,s,a,o){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=a,this.authOverride_=o,this.id=uu.nextPersistentConnectionId_++,this.log_=tl("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&&!m())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");lu.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&zl.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(O(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new A;var t={p:e._path.toString(),q:e._queryObject};this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++;t=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var a={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,a),this.connected_&&this.sendListen_(a)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),a=i._queryIdentifier;this.log_("Listen on "+s+" for "+a);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;uu.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(a))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,a),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&L(e,"w")){const i=F(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),ul("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} to your security rules for better performance.`))}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=M(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_){const r=this.authToken_;var e=function(e){const t=M(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+O(e));var t=e.r;const n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):nl("Unrecognized action received from server: "+O(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){f(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(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 e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+uu.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,u())};this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var o=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(o),this.appCheckTokenProvider_.getToken(o)]);t?cl("getToken() completed but was canceled"):(cl("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new jl(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{ul(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&ul(e),a())}}}interrupt(e){cl("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){cl("Resuming connection for reason: "+e),delete this.interruptReasons_[e],U(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 e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>sl(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new Wl(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){cl("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){cl("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(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+Lc.replace(/\./g,"-")]=1,o()?e["framework.cordova"]=1:p()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=zl.getInstance().currentlyOnline();return U(this.interruptReasons_)&&e}}uu.nextPersistentConnectionId_=0,uu.nextConnectionId_=0;class hu{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new hu(e,t)}}class du{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new hu(pl,e),r=new hu(pl,t);return 0!==this.compare(n,r)}minPost(){return hu.MIN}}let pu;class fu extends du{static get __EMPTY_NODE(){return pu}static set __EMPTY_NODE(e){pu=e}compare(e,t){return gl(e.name,t.name)}isDefinedOn(e){throw u("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return hu.MIN}maxPost(){return new hu(fl,pu)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new hu(e,pu)}toString(){return".key"}}const gu=new fu;class mu{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class vu{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:vu.RED,this.left=null!=r?r:yu.EMPTY_NODE,this.right=null!=i?i:yu.EMPTY_NODE}copy(e,t,n,r,i){return new vu(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return yu.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return yu.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,vu.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,vu.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)}}vu.RED=!0,vu.BLACK=!1;class yu{constructor(e,t=yu.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new yu(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,vu.BLACK,null,null))}remove(e){return new yu(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,vu.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new mu(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new mu(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new mu(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new mu(this.root_,null,this.comparator_,!0,e)}}function _u(e,t){return gl(e.name,t.name)}function wu(e,t){return gl(e,t)}yu.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new vu(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let bu;function Iu(e){return"number"==typeof e?"number:"+vl(e):"string:"+e}function Tu(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&L(t,".sv"),"Priority must be a string or number.")):f(e===bu||e.isEmpty(),"priority of unexpected type."),f(e===bu||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let Eu;class ku{constructor(e,t=ku.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Tu(this.priorityNode_)}static set __childrenNodeConstructor(e){Eu=e}static get __childrenNodeConstructor(){return Eu}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new ku(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:ku.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return tu(e)?this:".priority"===Hl(e)?this.priorityNode_:ku.__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:ku.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=Hl(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===Ql(e),".priority must be the last token in a path"),this.updateImmediateChild(n,ku.__childrenNodeConstructor.EMPTY_NODE.updateChild(Yl(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:"+Iu(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?vl(this.value_):this.value_,this.lazyHash_=Gc(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===ku.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof ku.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=ku.VALUE_TYPE_ORDER.indexOf(t),i=ku.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}ku.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Cu,Su;const Au=new class extends du{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?gl(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return hu.MIN}maxPost(){return new hu(fl,new ku("[PRIORITY-POST]",Su))}makePost(e,t){var n=Cu(e);return new hu(t,new ku("[PRIORITY-POST]",n))}toString(){return".priority"}},Nu=Math.log(2);class Ru{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Nu,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function xu(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new vu(i,r.node,vu.BLACK,null,null);var s=parseInt(n/2,10)+e,a=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new vu(i,r.node,vu.BLACK,a,n)};var n=function(e){let s=null,a=null,o=c.length;function t(e,t){var n=o-e,r=o;o-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{a=e;s=e}}(new vu(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,vu.BLACK):(t(r,vu.BLACK),t(r,vu.RED))}return a}(new Ru(c.length));return new yu(t||e,n)}let Du;const Pu={};class Ou{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return f((Pu,Au),"ChildrenNode.ts has not been loaded"),Du=Du||new Ou({".priority":Pu},{".priority":Au}),Du}get(e){var t=F(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof yu?t:null}hasIndex(e){return L(this.indexSet_,e.toString())}addIndex(e,t){f(e!==gu,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(hu.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let a;a=r?xu(n,e.getCompare()):Pu;var o=e.toString();const c=Object.assign({},this.indexSet_);c[o]=e;const l=Object.assign({},this.indexes_);return l[o]=a,new Ou(l,c)}addToIndexes(a,o){var e=q(this.indexes_,(t,e)=>{const n=F(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Pu){if(n.isDefinedOn(a.node)){const i=[],s=o.getIterator(hu.Wrap);let e=s.getNext();for(;e;)e.name!==a.name&&i.push(e),e=s.getNext();return i.push(a),xu(i,n.getCompare())}return Pu}{var r=o.get(a.name);let e=t;return r&&(e=e.remove(new hu(a.name,r))),e.insert(a,a.node)}});return new Ou(e,this.indexSet_)}removeFromIndexes(n,r){var e=q(this.indexes_,e=>{if(e===Pu)return e;var t=r.get(n.name);return t?e.remove(new hu(n.name,t)):e});return new Ou(e,this.indexSet_)}}let Mu;class Lu{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Tu(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Mu=Mu||new Lu(new yu(wu),null,Ou.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Mu}updatePriority(e){return this.children_.isEmpty()?this:new Lu(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?Mu:t}getChild(e){var t=Hl(e);return null===t?this:this.getImmediateChild(t).getChild(Yl(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new hu(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Mu:this.priorityNode_;return new Lu(e,i,t)}}updateChild(e,t){var n=Hl(e);if(null===n)return t;f(".priority"!==Hl(e)||1===Ql(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(Yl(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,a=!0;if(this.forEachChild(Au,(e,t)=>{r[e]=t.val(n),i++,a&&Lu.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):a=!1}),!n&&a&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+Iu(this.getPriority().val())+":"),this.forEachChild(Au,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":Gc(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new hu(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new hu(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new hu(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,hu.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,hu.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Uu?-1:0}withIndex(e){if(e===gu||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new Lu(this.children_,this.priorityNode_,t)}isIndexed(e){return e===gu||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(Au),i=n.getIterator(Au);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===gu?null:this.indexMap_.get(e.toString())}}Lu.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Fu extends Lu{constructor(){super(new yu(wu),Lu.EMPTY_NODE,Ou.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return Lu.EMPTY_NODE}isEmpty(){return!1}}const Uu=new Fu;Object.defineProperties(hu,{MIN:{value:new hu(pl,Lu.EMPTY_NODE)},MAX:{value:new hu(fl,Uu)}}),fu.__EMPTY_NODE=Lu.EMPTY_NODE,ku.__childrenNodeConstructor=Lu,Vc=Uu,bu=Vc,Bc=Uu,Su=Bc;const qu=!0;function Vu(i,e=null){if(null===i)return Lu.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new ku(t,Vu(e))}if(i instanceof Array||!qu){let r=Lu.EMPTY_NODE;return ml(i,(e,t)=>{if(L(i,e)&&"."!==e.substring(0,1)){const n=Vu(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(Vu(e))}{const s=[];let r=!1;if(ml(i,(e,t)=>{if("."!==e.substring(0,1)){const n=Vu(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new hu(e,n)))}}),0===s.length)return Lu.EMPTY_NODE;var n=xu(s,_u,e=>e.name,wu);if(r){t=xu(s,Au.getCompare());return new Lu(n,Vu(e),new Ou({".priority":t},{".priority":Au}))}return new Lu(n,Vu(e),Ou.Default)}}Cu=Vu;class Bu extends du{constructor(e){super(),this.indexPath_=e,f(!tu(e)&&".priority"!==Hl(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){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?gl(e.name,t.name):r}makePost(e,t){var n=Vu(e),n=Lu.EMPTY_NODE.updateChild(this.indexPath_,n);return new hu(t,n)}maxPost(){var e=Lu.EMPTY_NODE.updateChild(this.indexPath_,Uu);return new hu(fl,e)}toString(){return Xl(this.indexPath_,0).join("/")}}function ju(e){if(e===""+bl)return Wu;var t=Il(e);if(null!=t)return""+(t+1);const n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e.charAt(i);if(n.length<Hu)return n.push(Wu),n.join("");let r=n.length-1;for(;0<=r&&n[r]===Gu;)r--;return-1===r?fl:(t=n[r],t=zu.charAt(zu.indexOf(t)+1),n[r]=t,n.slice(0,r+1).join(""))}function Ku(e){if(e===""+wl)return pl;var t=Il(e);if(null!=t)return""+(t-1);const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e.charAt(r);return n[n.length-1]===Wu?1===n.length?""+bl:(delete n[n.length-1],n.join("")):(n[n.length-1]=zu.charAt(zu.indexOf(n[n.length-1])-1),n.join("")+Gu.repeat(Hu-n.length))}const $u=new class extends du{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?gl(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return hu.MIN}maxPost(){return hu.MAX}makePost(e,t){var n=Vu(e);return new hu(t,n)}toString(){return".value"}},zu="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Wu="-",Gu="z",Hu=786,Qu=function(){let s=0;const a=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=zu.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===a[n];n--)a[n]=0;a[n]++}else for(n=0;n<12;n++)a[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=zu.charAt(a[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}}();function Yu(e){return{type:"value",snapshotNode:e}}function Ju(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function Xu(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function Zu(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class eh{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(r).equals(n.getChild(r))&&a.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(Xu(t,a)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(Ju(t,n)):s.trackChildChange(Zu(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(Au,(e,t)=>{n.hasChild(e)||i.trackChildChange(Xu(e,t))}),n.isLeafNode()||n.forEachChild(Au,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(Zu(e,t,n))}else i.trackChildChange(Ju(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?Lu.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class th{constructor(e){this.indexedFilter_=new eh(e.getIndex()),this.index_=e.getIndex(),this.startPost_=th.getStartPost_(e),this.endPost_=th.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0}updateChild(e,t,n,r,i,s){return this.matches(new hu(t,n))||(n=Lu.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?Lu.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(Lu.EMPTY_NODE);const i=this;return t.forEachChild(Au,(e,t)=>{i.matches(new hu(e,t))||(r=r.updateImmediateChild(e,Lu.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class nh{constructor(e){this.rangedFilter_=new th(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new hu(t,n))||(n=Lu.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,a,t){let o;if(a.isLeafNode()||a.isEmpty())o=Lu.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<a.numChildren()&&a.isIndexed(this.index_)){o=Lu.EMPTY_NODE.withIndex(this.index_);let t;t=this.reverse_?a.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):a.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;t.hasNext()&&n<this.limit_;){var r=t.getNext();let e;if(e=this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),r)<=0:this.index_.compare(r,this.rangedFilter_.getEndPost())<=0,!e)break;o=o.updateImmediateChild(r.name,r.node),n++}}else{o=a.withIndex(this.index_),o=o.updatePriority(Lu.EMPTY_NODE);let e,t,n,r;if(this.reverse_){r=o.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),t=this.rangedFilter_.getStartPost();const l=this.index_.getCompare();n=(e,t)=>l(t,e)}else r=o.getIterator(this.index_),e=this.rangedFilter_.getStartPost(),t=this.rangedFilter_.getEndPost(),n=this.index_.getCompare();let i=0,s=!1;for(;r.hasNext();){var c=r.getNext();!s&&n(e,c)<=0&&(s=!0),s&&i<this.limit_&&n(c,t)<=0?i++:o=o.updateImmediateChild(c.name,Lu.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,o,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const a=e;f(a.numChildren()===this.limit_,"");var o=new hu(t,n),c=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),l=this.rangedFilter_.matches(o);if(a.hasChild(t)){var u=a.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||a.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,o);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(Zu(t,n,u)),a.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(Xu(t,u));const p=a.updateImmediateChild(t,Lu.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(Ju(e.name,e.node)),p.updateImmediateChild(e.name,e.node)):p}}return!n.isEmpty()&&l&&0<=s(c,o)?(null!=i&&(i.trackChildChange(Xu(c.name,c.node)),i.trackChildChange(Ju(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(c.name,Lu.EMPTY_NODE)):e}}class rh{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_=Au}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:pl}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:fl}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===Au}copy(){const e=new rh;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function ih(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function sh(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function ah(e,t){const n=e.copy();return n.index_=t,n}function oh(e){const t={};if(e.isDefault())return t;let n;return n=e.index_===Au?"$priority":e.index_===$u?"$value":e.index_===gu?"$key":(f(e.index_ instanceof Bu,"Unrecognized index type!"),e.index_.toString()),t.orderBy=O(n),e.startSet_&&(t.startAt=O(e.indexStartValue_),e.startNameSet_&&(t.startAt+=","+O(e.indexStartName_))),e.endSet_&&(t.endAt=O(e.indexEndValue_),e.endNameSet_&&(t.endAt+=","+O(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function ch(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_)),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_)),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==Au&&(n.i=t.index_.toString()),n}class lh extends Kl{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=tl("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const a=lh.getListenId_(e,r),o={};this.listens_[a]=o;var n=oh(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),F(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=lh.getListenId_(e,t);delete this.listens_[n]}get(e){var t=oh(e._queryParams);const r=e._path.toString(),i=new A;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},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);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+j(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(a&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=P(r.responseText)}catch(e){ul("Failed to parse JSON response for "+n+": "+r.responseText)}a(null,e)}else 401!==r.status&&404!==r.status&&ul("Got unsuccessful REST response for "+n+" Status: "+r.status),a(r.status);a=null}},r.open("GET",n,!0),r.send()})}}class uh{constructor(){this.rootNode_=Lu.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function hh(){return{value:null,children:new Map}}function dh(e,t,n){var r;tu(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=Hl(t),e.children.has(r)||e.children.set(r,hh()),dh(e.children.get(r),t=Yl(t),n))}function ph(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{ph(t,new Wl(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class fh{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&ml(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class gh{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new fh(e);var n=1e4+2e4*Math.random();yl(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;ml(e,(e,t)=>{0<t&&L(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),yl(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function mh(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function vh(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function yh(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(KC=jc=jc||{})[KC.OVERWRITE=0]="OVERWRITE",KC[KC.MERGE=1]="MERGE",KC[KC.ACK_USER_WRITE=2]="ACK_USER_WRITE",KC[KC.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class _h{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=jc.ACK_USER_WRITE,this.source=mh()}operationForChild(e){if(tu(this.path)){if(null!=this.affectedTree.value)return f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new Wl(e));return new _h(Gl(),t,this.revert)}return f(Hl(this.path)===e,"operationForChild called for unrelated child."),new _h(Yl(this.path),this.affectedTree,this.revert)}}class wh{constructor(e,t){this.source=e,this.path=t,this.type=jc.LISTEN_COMPLETE}operationForChild(e){return tu(this.path)?new wh(this.source,Gl()):new wh(this.source,Yl(this.path))}}class bh{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=jc.OVERWRITE}operationForChild(e){return tu(this.path)?new bh(this.source,Gl(),this.snap.getImmediateChild(e)):new bh(this.source,Yl(this.path),this.snap)}}class Ih{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=jc.MERGE}operationForChild(e){if(tu(this.path)){const t=this.children.subtree(new Wl(e));return t.isEmpty()?null:t.value?new bh(this.source,Gl(),t.value):new Ih(this.source,Gl(),t)}return f(Hl(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Ih(this.source,Yl(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Th{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(tu(e))return this.isFullyInitialized()&&!this.filtered_;var t=Hl(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Eh{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function kh(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),Ch(n,i,"child_removed",e,r,t),Ch(n,i,"child_added",e,r,t),Ch(n,i,"child_moved",s,r,t),Ch(n,i,"child_changed",e,r,t),Ch(n,i,"value",e,r,t),i}function Ch(s,a,t,e,o,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw u("Should only compare child_ events.");var r=new hu(t.childName,t.snapshotNode),i=new hu(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;o.forEach(e=>{e.respondsTo(t.type)&&a.push(e.createEvent(n,s.query_))})})}function Sh(e,t){return{eventCache:e,serverCache:t}}function Ah(e,t,n,r){return Sh(new Th(t,n,r),e.serverCache)}function Nh(e,t,n,r){return Sh(e.eventCache,new Th(t,n,r))}function Rh(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function xh(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Dh;class Ph{constructor(e,t=(Dh=Dh||new yu(rl),Dh)){this.value=e,this.children=t}static fromObject(e){let n=new Ph(null);return ml(e,(e,t)=>{n=n.set(new Wl(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:Gl(),value:this.value};if(tu(e))return null;{var n=Hl(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(Yl(e),t);return null==r?null:{path:eu(new Wl(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(tu(e))return this;{var t=Hl(e);const n=this.children.get(t);return null!==n?n.subtree(Yl(e)):new Ph(null)}}set(e,t){if(tu(e))return new Ph(t,this.children);{var n=Hl(e);const i=this.children.get(n)||new Ph(null);var r=i.set(Yl(e),t),r=this.children.insert(n,r);return new Ph(this.value,r)}}remove(t){if(tu(t))return this.children.isEmpty()?new Ph(null):new Ph(null,this.children);{var n=Hl(t);const r=this.children.get(n);if(r){const i=r.remove(Yl(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new Ph(null):new Ph(this.value,e)}return this}}get(e){if(tu(e))return this.value;{var t=Hl(e);const n=this.children.get(t);return n?n.get(Yl(e)):null}}setTree(t,n){if(tu(t))return n;{var r=Hl(t);const i=this.children.get(r)||new Ph(null),s=i.setTree(Yl(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new Ph(this.value,e)}}fold(e){return this.fold_(Gl(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(eu(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,Gl(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(tu(e))return null;{r=Hl(e);const i=this.children.get(r);return i?i.findOnPath_(Yl(e),eu(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,Gl(),t)}foreachOnPath_(e,t,n){if(tu(e))return this;{this.value&&n(t,this.value);var r=Hl(e);const i=this.children.get(r);return i?i.foreachOnPath_(Yl(e),eu(t,r),n):new Ph(null)}}foreach(e){this.foreach_(Gl(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(eu(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class Oh{constructor(e){this.writeTree_=e}static empty(){return new Oh(new Ph(null))}}function Mh(t,n,r){if(tu(n))return new Oh(new Ph(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=nu(s,n);return e=e.updateChild(i,r),new Oh(t.writeTree_.set(s,e))}s=new Ph(r),s=t.writeTree_.setTree(n,s);return new Oh(s)}function Lh(e,n,t){let r=e;return ml(t,(e,t)=>{r=Mh(r,eu(n,e),t)}),r}function Fh(e,t){if(tu(t))return Oh.empty();var n=e.writeTree_.setTree(t,new Ph(null));return new Oh(n)}function Uh(e,t){return null!=qh(e,t)}function qh(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(nu(n.path,t)):null}function Vh(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(Au,(e,t)=>{n.push(new hu(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new hu(e,t.value))}),n}function Bh(e,t){if(tu(t))return e;var n=qh(e,t);return null!=n?new Oh(new Ph(n)):new Oh(e.writeTree_.subtree(t))}function jh(e){return e.writeTree_.isEmpty()}function Kh(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(eu(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(eu(i,".priority"),n):s}}}(Gl(),e.writeTree_,t)}function $h(e,t){return nd(t,e)}function zh(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,a=!1,o=t.allWrites.length-1;for(;s&&0<=o;){var c=t.allWrites[o];c.visible&&(o>=r&&function(e,t){{if(e.snap)return su(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&su(eu(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:su(i.path,c.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=Gh(e.allWrites,Wh,Gl()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=Fh(t.visibleWrites,i.path):ml(i.children,e=>{t.visibleWrites=Fh(t.visibleWrites,eu(i.path,e))}),!0)}function Wh(e){return e.visible}function Gh(e,t,n){let r=Oh.empty();for(let s=0;s<e.length;++s){const a=e[s];if(t(a)){var i=a.path;let e;if(a.snap)su(n,i)?(e=nu(n,i),r=Mh(r,e,a.snap)):su(i,n)&&(e=nu(i,n),r=Mh(r,Gl(),a.snap.getChild(e)));else{if(!a.children)throw u("WriteRecord should have .snap or .children");if(su(n,i))e=nu(n,i),r=Lh(r,e,a.children);else if(su(i,n))if(e=nu(i,n),tu(e))r=Lh(r,Gl(),a.children);else{const o=F(a.children,Hl(e));o&&(i=o.getChild(Yl(e)),r=Mh(r,Gl(),i))}}}}return r}function Hh(e,t,n,r,i){if(r||i){var s=Bh(e.visibleWrites,t);if(!i&&jh(s))return n;if(i||null!=n||Uh(s,Gl()))return Kh(Gh(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(su(e.path,t)||su(t,e.path))},t),n||Lu.EMPTY_NODE);return null}s=qh(e.visibleWrites,t);if(null!=s)return s;s=Bh(e.visibleWrites,t);return jh(s)?n:null!=n||Uh(s,Gl())?Kh(s,n||Lu.EMPTY_NODE):null}function Qh(e,t,n,r){return Hh(e.writeTree,e.treePath,t,n,r)}function Yh(e,t){return function(e,t,n){let r=Lu.EMPTY_NODE;const i=qh(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(Au,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=Bh(e.visibleWrites,t);return n.forEachChild(Au,(e,t)=>{var n=Kh(Bh(s,new Wl(e)),t);r=r.updateImmediateChild(e,n)}),Vh(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return Vh(Bh(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function Jh(e,t,n,r){return function(e,t,n,r,i){f(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=eu(t,n);return Uh(e.visibleWrites,s)?null:jh(s=Bh(e.visibleWrites,s))?i.getChild(n):Kh(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function Xh(e,t){return n=e.writeTree,t=eu(e.treePath,t),qh(n.visibleWrites,t);var n}function Zh(e,t,n,r,i,s){return function(e,t,n,r,i,s,a){let o;var c=Bh(e.visibleWrites,t),l=qh(c,Gl());if(null!=l)o=l;else{if(null==n)return[];o=Kh(c,n)}if(o=o.withIndex(a),o.isEmpty()||o.isLeafNode())return[];{const u=[],h=a.getCompare(),d=s?o.getReverseIteratorFrom(r,a):o.getIteratorFrom(r,a);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function ed(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=eu(e,t=t),null!=(s=qh(r.visibleWrites,i))?s:n.isCompleteForChild(t)?Kh(Bh(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function td(e,t){return nd(eu(e.treePath,t),e.writeTree)}function nd(e,t){return{treePath:e,writeTree:t}}class rd{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,Zu(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,Xu(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,Ju(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw u("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,Zu(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const id=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class sd{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new Th(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return ed(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:xh(this.viewCache_),r=Zh(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function ad(e,t,n,r,i){const s=new rd;let a,o;if(n.type===jc.OVERWRITE){var c=n;a=c.source.fromUser?ld(e,t,c.path,c.snap,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered()&&!tu(c.path),cd(e,t,c.path,c.snap,r,i,o,s))}else if(n.type===jc.MERGE){c=n;a=c.source.fromUser?function(r,i,s,e,a,o,c){let l=i;return e.foreach((e,t)=>{var n=eu(s,e);ud(i,Hl(n))&&(l=ld(r,l,n,t,a,o,c))}),e.foreach((e,t)=>{var n=eu(s,e);ud(i,Hl(n))||(l=ld(r,l,n,t,a,o,c))}),l}(e,t,c.path,c.children,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered(),dd(e,t,c.path,c.children,r,i,o,s))}else if(n.type===jc.ACK_USER_WRITE){var l=n;a=l.revert?function(n,r,i,s,e,a){let o;{if(null!=Xh(s,i))return r;{var c=new sd(s,r,e);const u=r.eventCache.getNode();let t;if(tu(i)||".priority"===Hl(i)){let e;e=r.serverCache.isFullyInitialized()?Qh(s,xh(r)):(l=r.serverCache.getNode(),f(l instanceof Lu,"serverChildren would be complete if leaf node"),Yh(s,l)),e=e,t=n.filter.updateFullNode(u,e,a)}else{var l=Hl(i);let e=ed(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,Yl(i),c,a):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,Lu.EMPTY_NODE,Yl(i),c,a):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(o=Qh(s,xh(r)),o.isLeafNode()&&(t=n.filter.updateFullNode(t,o,a)))}return o=r.serverCache.isFullyInitialized()||null!=Xh(s,Gl()),Ah(r,t,o,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,a,o){if(null!=Xh(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(tu(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return cd(e,t,i,l.getNode().getChild(i),s,a,c,o);if(tu(i)){let n=new Ph(null);return l.getNode().forEachChild(gu,(e,t)=>{n=n.set(new Wl(e),t)}),dd(e,t,i,n,s,a,c,o)}return t}{let r=new Ph(null);return n.foreach((e,t)=>{var n=eu(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),dd(e,t,i,r,s,a,c,o)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==jc.LISTEN_COMPLETE)throw u("Unknown operation type: "+n.type);a=function(e,t,n,r,i){const s=t.serverCache,a=Nh(t,s.getNode(),s.isFullyInitialized()||tu(n),s.isFiltered());return od(e,a,n,r,id,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=Rh(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(Yu(Rh(t)))}}(t,a,l),{viewCache:a,changes:l}}function od(r,i,s,a,o,c){const l=i.eventCache;if(null!=Xh(a,s))return i;{let t,n;if(tu(s)){var e;f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=Yh(a,(e=xh(i))instanceof Lu?e:Lu.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=Qh(a,xh(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=Hl(s);if(".priority"===u){f(1===Ql(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=Jh(a,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=Yl(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=Jh(a,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):ed(a,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,o,c):l.getNode()}}return Ah(i,t,l.isFullyInitialized()||tu(s),r.filter.filtersNodes())}}function cd(e,t,n,r,i,s,a,o){const c=t.serverCache;let l;const u=a?e.filter:e.filter.getIndexedFilter();if(tu(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=Hl(n);if(!c.isCompleteForPath(n)&&1<Ql(n))return t;var p=Yl(n);const f=c.getNode().getImmediateChild(d);h=f.updateChild(p,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,p,id,null)}p=Nh(t,l,c.isFullyInitialized()||tu(n),u.filtersNodes());return od(e,p,n,i,new sd(i,p,s),o)}function ld(t,n,r,i,e,s,a){const o=n.eventCache;let c,l;const u=new sd(e,n,s);if(tu(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,a),c=Ah(n,l,!0,t.filter.filtersNodes());else{var h=Hl(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=Ah(n,l,o.isFullyInitialized(),o.isFiltered());else{var d=Yl(r);const p=o.getNode().getImmediateChild(h);let e;if(tu(d))e=i;else{const f=u.getCompleteChild(h);e=null!=f?".priority"===Jl(d)&&f.getChild(Zl(d)).isEmpty()?f:f.updateChild(d,i):Lu.EMPTY_NODE}c=p.equals(e)?n:Ah(n,t.filter.updateChild(o.getNode(),h,e,d,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return c}function ud(e,t){return e.eventCache.isCompleteForChild(t)}function hd(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function dd(r,i,e,t,s,a,o,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=tu(e)?t:new Ph(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=hd(0,i.serverCache.getNode().getImmediateChild(e),t),l=cd(r,l,new Wl(e),n,s,a,o,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;u.hasChild(e)||n||(n=hd(0,i.serverCache.getNode().getImmediateChild(e),t),l=cd(r,l,new Wl(e),n,s,a,o,c))}),l}class pd{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new eh(n.getIndex()),i=(e=n).loadsAllData()?new eh(e.getIndex()):new(e.hasLimit()?nh:th)(e);this.processor_={filter:i};const s=t.serverCache,a=t.eventCache;var o=r.updateFullNode(Lu.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(Lu.EMPTY_NODE,a.getNode(),null),o=new Th(o,s.isFullyInitialized(),r.filtersNodes()),c=new Th(c,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=Sh(c,o),this.eventGenerator_=new Eh(this.query_)}get query(){return this.query_}}function fd(e){return 0===e.eventRegistrations_.length}function gd(n,r,i){const s=[];if(i){f(null==r,"A cancel should cancel all event registrations.");const a=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,a);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const o=n.eventRegistrations_[t];if(o.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(o)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function md(e,t,n,r){t.type===jc.MERGE&&null!==t.source.queryId&&(f(xh(e.viewCache_),"We should always have a full cache before handling merges"),f(Rh(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=ad(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,f(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),f(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,vd(e,s.changes,s.viewCache.eventCache.getNode(),null)}function vd(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return kh(e.eventGenerator_,t,n,i)}let yd;class _d{constructor(){this.views=new Map}}function wd(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return f(null!=e,"SyncTree gave us an op for an invalid query."),md(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(md(s,n,r,i));return e}}function bd(e,n,r,i,s){var a=n._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Qh(r,s?i:null),t=!1;t=!!e||(e=i instanceof Lu?Yh(r,i):Lu.EMPTY_NODE,!1);a=Sh(new Th(e,t,!1),new Th(i,s,!1));return new pd(n,a)}}function Id(e,t,n,r,i,s){var a=bd(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,a),a.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(Au,(e,t)=>{r.push(Ju(e,t))})}return n.isFullyInitialized()&&r.push(Yu(n.getNode())),vd(e,r,n.getNode(),t)}(a,n)}function Td(e,t,n,r){var i=t._queryIdentifier;const s=[];let a=[];var o=Ad(e);if("default"===i)for(var[c,l]of e.views.entries())a=a.concat(gd(l,n,r)),fd(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(a=a.concat(gd(u,n,r)),fd(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return o&&!Ad(e)&&s.push((f(yd,"Reference.ts has not been loaded"),new yd(t._repo,t._path))),{removed:s,events:a}}function Ed(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function kd(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=xh(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!tu(t)&&!n.getImmediateChild(Hl(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function Cd(e,t){const n=t._queryParams;if(n.loadsAllData())return Nd(e);var r=t._queryIdentifier;return e.views.get(r)}function Sd(e,t){return null!=Cd(e,t)}function Ad(e){return null!=Nd(e)}function Nd(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Rd;let xd=1;class Dd{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Ph(null),this.pendingWriteTree_={visibleWrites:Oh.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Pd(e,t,n,r,i){var s,a,o,c;return s=e.pendingWriteTree_,a=t,o=n,c=r,r=i,f(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:a,snap:o,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=Mh(s.visibleWrites,a,o)),s.lastWriteId=c,i?jd(e,new bh(mh(),t,n)):[]}function Od(e,t,n,r){var i,s,a;i=e.pendingWriteTree_,s=t,a=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:a,writeId:r,visible:!0}),i.visibleWrites=Lh(i.visibleWrites,s,a),i.lastWriteId=r;var o=Ph.fromObject(n);return jd(e,new Ih(mh(),t,o))}function Md(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(zh(e.pendingWriteTree_,t)){let t=new Ph(null);return null!=r.snap?t=t.set(Gl(),!0):ml(r.children,e=>{t=t.set(new Wl(e),!0)}),jd(e,new _h(r.path,t,n))}return[]}function Ld(e,t,n){return jd(e,new bh(vh(),t,n))}function Fd(n,e,t,r,i=!1){var s=e._path,a=n.syncPointTree_.get(s);let o=[];if(a&&("default"===e._queryIdentifier||Sd(a,e))){var c=Td(a,e,t,r);0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(s));const d=c.removed;if(o=c.events,!i){a=-1!==d.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(s,(e,t)=>Ad(t));if(a&&!c){const p=n.syncPointTree_.subtree(s);if(!p.isEmpty()){var l=p.fold((e,t,r)=>{if(t&&Ad(t))return[Nd(t)];{let n=[];return t&&(n=Ed(t)),ml(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<l.length;++e){var u=l[e],h=u.query,u=$d(n,u);n.listenProvider_.startListening(Yd(h),zd(n,h),u.hashFn,u.onComplete)}}}!c&&0<d.length&&!r&&(a?n.listenProvider_.stopListening(Yd(e),null):d.forEach(e=>{var t=n.queryToTagMap.get(Wd(e));n.listenProvider_.stopListening(Yd(e),t)}))}!function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=Wd(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,d)}return o}function Ud(e,t,n,r){var i=Gd(e,r);if(null==i)return[];var s=Hd(i),a=s.path,i=s.queryId,s=nu(a,t);return Qd(e,a,new bh(yh(i),s,n))}function qd(e,t,n,r=!1){const i=t._path;let s=null,a=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=nu(e,i);s=s||kd(t,n),a=a||Ad(t)});let o=e.syncPointTree_.get(i);o?(a=a||Ad(o),s=s||kd(o,Gl())):(o=new _d,e.syncPointTree_=e.syncPointTree_.set(i,o));let c;if(null!=s)c=!0;else{c=!1,s=Lu.EMPTY_NODE;const p=e.syncPointTree_.subtree(i);p.foreachChild((e,t)=>{var n=kd(t,Gl());n&&(s=s.updateImmediateChild(e,n))})}var l,u=Sd(o,t);u||t._queryParams.loadsAllData()||(h=Wd(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),l=xd++,e.queryToTagMap.set(h,l),e.tagToQueryMap.set(l,h));var h=$h(e.pendingWriteTree_,i);let d=Id(o,t,n,h,s,c);return u||a||r||(u=Cd(o,t),d=d.concat(function(t,e,n){const r=e._path,i=zd(t,e),s=$d(t,n),a=t.listenProvider_.startListening(Yd(e),i,s.hashFn,s.onComplete),o=t.syncPointTree_.subtree(r);if(i)f(!Ad(o.value),"If we're adding a query, it shouldn't be shadowed");else{var c=o.fold((e,t,r)=>{if(!tu(e)&&t&&Ad(t))return[Nd(t).query];{let n=[];return t&&(n=n.concat(Ed(t).map(e=>e.query))),ml(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(Yd(l),zd(t,l))}}return a}(e,t,u))),d}function Vd(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=kd(t,nu(e,r));if(n)return n});return Hh(n,r,i,t,!0)}function Bd(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=nu(e,r);i=i||kd(t,n)});let n=e.syncPointTree_.get(r);n?i=i||kd(n,Gl()):(n=new _d,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const a=s?new Th(i,!0,!1):null;var o=$h(e.pendingWriteTree_,t._path);return Rh(bd(n,t,o,s?a.getNode():Lu.EMPTY_NODE,s).viewCache_)}function jd(e,t){return function t(n,r,i,s){{if(tu(n.path))return Kd(n,r,i,s);{const a=r.get(Gl());null==i&&null!=a&&(i=kd(a,Gl()));let e=[];const o=Hl(n.path),c=n.operationForChild(o),l=r.children.get(o);if(l&&c){const u=i?i.getImmediateChild(o):null,h=td(s,o);e=e.concat(t(c,l,u,h))}return a&&(e=e.concat(wd(a,n,s,i))),e}}}(t,e.syncPointTree_,null,$h(e.pendingWriteTree_,Gl()))}function Kd(s,e,a,o){var t=e.get(Gl());null==a&&null!=t&&(a=kd(t,Gl()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=a?a.getImmediateChild(e):null,r=td(o,e),i=s.operationForChild(e);i&&(c=c.concat(Kd(i,t,n,r)))}),t&&(c=c.concat(wd(t,s,o,a))),c}function $d(i,t){const s=t.query,a=zd(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||Lu.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return a?function(e,t,n){if(s=Gd(e,n)){var r=Hd(s),i=r.path,s=r.queryId,r=nu(i,t);return Qd(e,i,new wh(yh(s),r))}return[]}(i,s._path,a):(t=i,n=s._path,jd(t,new wh(vh(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return Fd(i,s,null,r)}}}function zd(e,t){var n=Wd(t);return e.queryToTagMap.get(n)}function Wd(e){return e._path.toString()+"$"+e._queryIdentifier}function Gd(e,t){return e.tagToQueryMap.get(t)}function Hd(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new Wl(e.substr(0,t))}}function Qd(e,t,n){var r=e.syncPointTree_.get(t);return f(r,"Missing sync point for query tag that we're tracking"),wd(r,n,$h(e.pendingWriteTree_,t),null)}function Yd(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(Rd,"Reference.ts has not been loaded"),new Rd(e._repo,e._path)):e}class Jd{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new Jd(t)}node(){return this.node_}}class Xd{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=eu(this.path_,e);return new Xd(this.syncTree_,t)}node(){return Vd(this.syncTree_,this.path_)}}function Zd(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function ep(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?tp(e[".sv"],t,n):"object"==typeof e[".sv"]?np(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const tp=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},np=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&f(!1,"Unexpected increment value: "+r);const i=t.node();if(f(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var a=s.getValue();return"number"!=typeof a?r:a+r},rp=function(e,t,n,r){return sp(t,new Xd(n,e),r)},ip=function(e,t,n){return sp(e,new Jd(t),n)};function sp(e,r,i){var t=e.getPriority().val(),n=ep(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const a=e;t=ep(a.getValue(),r,i);return t!==a.getValue()||n!==a.getPriority().val()?new ku(t,Vu(n)):e}{const o=e;return s=o,n!==o.getPriority().val()&&(s=s.updatePriority(new ku(n))),o.forEachChild(Au,(e,t)=>{var n=sp(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class ap{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function op(e,t){let n=t instanceof Wl?t:new Wl(t),r=e,i=Hl(n);for(;null!==i;){var s=F(r.node.children,i)||{children:{},childCount:0};r=new ap(i,r,s),n=Yl(n),i=Hl(n)}return r}function cp(e){return e.node.value}function lp(e,t){e.node.value=t,pp(e)}function up(e){return 0<e.node.childCount}function hp(n,r){ml(n.node.children,(e,t)=>{r(new ap(e,n,t))})}function dp(e){return new Wl(null===e.parent?e.name:dp(e.parent)+"/"+e.name)}function pp(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===cp(e)&&!up(e)}(e=e),i=L(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,pp(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,pp(t)))}function fp(e,t,n,r){r&&void 0===t||Sp(Y(e,"value"),t,n)}function gp(e,t,r,n){if(!n||void 0!==t){const i=Y(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];ml(t,(e,t)=>{const n=new Wl(e);if(Sp(i,t,eu(r,n)),".priority"===Jl(n)&&!Cp(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=Xl(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!Tp(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(ru);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&su(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function mp(e,t,n){if(!n||void 0!==t){if(dl(t))throw new Error(Y(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Cp(t))throw new Error(Y(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function vp(e,t,n,r){if(!(r&&void 0===n||Tp(n)))throw new Error(Y(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function yp(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Ap(e,t,n,r)}function _p(e,t){if(".info"===Hl(t))throw new Error(e+" failed = Can't modify data under /.info/")}const wp=/[\[\].#$\/\u0000-\u001F\u007F]/,bp=/[\[\].#$\u0000-\u001F\u007F]/,Ip=10485760,Tp=function(e){return"string"==typeof e&&0!==e.length&&!wp.test(e)},Ep=function(e){return"string"==typeof e&&0!==e.length&&!bp.test(e)},kp=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Ep(e)},Cp=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!dl(e)||e&&"object"==typeof e&&L(e,".sv")},Sp=function(a,e,t){const o=t instanceof Wl?new au(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+cu(o));if("function"==typeof e)throw new Error(a+"contains a function "+cu(o)+" with contents = "+e.toString());if(dl(e))throw new Error(a+"contains "+e.toString()+" "+cu(o));if("string"==typeof e&&e.length>Ip/3&&ee(e)>Ip)throw new Error(a+"contains a string greater than "+Ip+" utf8 bytes "+cu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(ml(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!Tp(e)))throw new Error(a+" contains an invalid key ("+e+") "+cu(o)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=o,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=ee(e),ou(n),Sp(a,t,o),t=o,r=t.parts_.pop(),t.byteLength_-=ee(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+cu(o)+" in addition to actual children.")}},Ap=function(e,t,n,r){if(!(r&&void 0===n||Ep(n)))throw new Error(Y(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Np=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Tp(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!kp(n))throw new Error(Y(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Rp{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function xp(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||iu(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function Dp(e,t,n){xp(e,n),Op(e,e=>iu(e,t))}function Pp(e,t,n){xp(e,n),Op(e,e=>su(e,t)||su(t,e))}function Op(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),Zc&&cl("event: "+r.toString()),Tl(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const Mp="repo_interrupt",Lp=25;class Fp{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Rp,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=hh(),this.transactionQueueTree_=new ap,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Up(a,e,t){if(a.stats_=Ml(a.repoInfo_),a.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())a.server_=new lh(a.repoInfo_,(e,t,n,r)=>{Bp(a,e,t,n,r)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>jp(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{O(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new uu(a.repoInfo_,e,(e,t,n,r)=>{Bp(a,e,t,n,r)},e=>{jp(a,e)},e=>{var n;n=a,ml(e,(e,t)=>{Kp(n,e,t)})},a.authTokenProvider_,a.appCheckProvider_,t),a.server_=a.persistentConnection_}var n;a.authTokenProvider_.addTokenChangeListener(e=>{a.server_.refreshAuthToken(e)}),a.appCheckProvider_.addTokenChangeListener(e=>{a.server_.refreshAppCheckToken(e.token)}),a.statsReporter_=(e=a.repoInfo_,t=()=>new gh(a.stats_,a.server_),n=e.toString(),Ol[n]||(Ol[n]=t()),Ol[n]),a.infoData_=new uh,a.infoSyncTree_=new Dd({startListening:(e,t,n,r)=>{let i=[];const s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=Ld(a.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),Kp(a,"connected",!1),a.serverSyncTree_=new Dd({startListening:(r,e,t,i)=>(a.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);Pp(a.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function qp(e){const t=e.infoData_.getNode(new Wl(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function Vp(e){return Zd({timestamp:qp(e)})}function Bp(e,t,n,r,i){e.dataUpdateCount++;var s,a,o=new Wl(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=q(n,e=>Vu(e)),function(e,t,n,r){if(o=Gd(e,r)){var i=Hd(o),s=i.path,a=i.queryId,o=nu(s,t),i=Ph.fromObject(n);return Qd(e,s,new Ih(yh(a),o,i))}return[]}(e.serverSyncTree_,o,s,i)):(s=Vu(n),Ud(e.serverSyncTree_,o,s,i)):r?(a=q(n,e=>Vu(e)),t=e.serverSyncTree_,i=o,r=a,a=Ph.fromObject(r),jd(t,new Ih(vh(),i,a))):(a=Vu(n),Ld(e.serverSyncTree_,o,a));let l=o;0<c.length&&(l=ef(e,o)),Pp(e.eventQueue_,l,c)}function jp(e,t){Kp(e,"connected",t),!1===t&&function(r){Yp(r,"onDisconnectEvents");const i=Vp(r),s=hh();ph(r.onDisconnect_,Gl(),(e,t)=>{var n=rp(e,t,r.serverSyncTree_,i);dh(s,e,n)});let a=[];ph(s,Gl(),(e,t)=>{a=a.concat(Ld(r.serverSyncTree_,e,t));var n=sf(r,e);ef(r,n)}),r.onDisconnect_=hh(),Pp(r.eventQueue_,Gl(),a)}(e)}function Kp(e,t,n){var r=new Wl("/.info/"+t),i=Vu(n);e.infoData_.updateSnapshot(r,i);i=Ld(e.infoSyncTree_,r,i);Pp(e.eventQueue_,r,i)}function $p(e){return e.nextWriteId_++}function zp(r,i,e,t,s){Yp(r,"set",{path:i.toString(),value:e,priority:t});var n=Vp(r);const a=Vu(e,t);var o=Vd(r.serverSyncTree_,i),n=ip(a,o,n);const c=$p(r);n=Pd(r.serverSyncTree_,i,n,c,!0);xp(r.eventQueue_,n),r.server_.put(i.toString(),a.val(!0),(e,t)=>{var n="ok"===e;n||ul("set at "+i+" failed: "+e);n=Md(r.serverSyncTree_,c,!n);Pp(r.eventQueue_,i,n),Jp(0,s,e,t)});n=sf(r,i);ef(r,n),Pp(r.eventQueue_,n,[])}function Wp(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(tu(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(Au,(e,t)=>{dh(n,new Wl(e),t)}),e(n,t)}}if(0<n.children.size){var r=Hl(t);return t=Yl(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),Jp(0,i,e,t)})}function Gp(n,r,e,i){const s=Vu(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&dh(n.onDisconnect_,r,s),Jp(0,i,e,t)})}function Hp(e,t,n){let r;r=".info"===Hl(t._path)?Fd(e.infoSyncTree_,t,n):Fd(e.serverSyncTree_,t,n),Dp(e.eventQueue_,t._path,r)}function Qp(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Mp)}function Yp(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),cl(n,...t)}function Jp(e,r,i,s){r&&Tl(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function Xp(e,t,n){return Vd(e.serverSyncTree_,t,n)||Lu.EMPTY_NODE}function Zp(t,e=t.transactionQueueTree_){if(e||rf(t,e),cp(e)){const n=nf(t,e);f(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,a){const e=a.map(e=>e.currentWriteId),t=Xp(i,s,e);let n=t;var r=t.hash();for(let u=0;u<a.length;u++){const h=a[u];f(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var o=nu(s,h.path);n=n.updateChild(o,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{Yp(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<a.length;e++)a[e].status=2,n=n.concat(Md(i.serverSyncTree_,a[e].currentWriteId)),a[e].onComplete&&r.push(()=>a[e].onComplete(null,!0,a[e].currentOutputSnapshotResolved)),a[e].unwatcher();rf(i,op(i.transactionQueueTree_,s)),Zp(i,i.transactionQueueTree_),Pp(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)Tl(r[t])}else{if("datastale"===t)for(let e=0;e<a.length;e++)3===a[e].status?a[e].status=4:a[e].status=0;else{ul("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<a.length;e++)a[e].status=4,a[e].abortReason=t}ef(i,s)}},r)}(t,dp(e),n)}else up(e)&&hp(e,e=>{Zp(t,e)})}function ef(e,t){var n=tf(e,t),r=dp(n);return function(i,s,a){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var o=nu(a,h.path);let e=!1,t;if(f(null!==o,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(Md(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=Lp)e=!0,t="maxretry",n=n.concat(Md(i.serverSyncTree_,h.currentWriteId,!0));else{const d=Xp(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){Sp("transaction failed: Data returned ",c,h.path);let e=Vu(c);"object"==typeof c&&null!=c&&L(c,".priority")||(e=e.updatePriority(d.getPriority()));o=h.currentWriteId,c=Vp(i),c=ip(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=$p(i),u.splice(u.indexOf(o),1),n=n.concat(Pd(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(Md(i.serverSyncTree_,o,!0))}else e=!0,t="nodata",n=n.concat(Md(i.serverSyncTree_,h.currentWriteId,!0))}Pp(i.eventQueue_,a,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}rf(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)Tl(l[e]);Zp(i,i.transactionQueueTree_)}}(e,nf(e,n),r),r}function tf(e,t){let n,r=e.transactionQueueTree_;for(n=Hl(t);null!==n&&void 0===cp(r);)r=op(r,n),t=Yl(t),n=Hl(t);return r}function nf(e,t){const n=[];return function t(n,e,r){const i=cp(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);hp(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function rf(t,n){const r=cp(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,lp(n,0<r.length?r:void 0)}hp(n,e=>{rf(t,e)})}function sf(t,e){var n=dp(tf(t,e)),r=op(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{af(t,e)}),af(t,r),function t(e,n,r,i){r&&!i&&n(e),hp(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{af(t,e)}),n}function af(i,s){const a=cp(s);if(a){const o=[];let e=[],t=-1;for(let n=0;n<a.length;n++)3===a[n].status||(1===a[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),t=n,a[n].status=3,a[n].abortReason="set"):(f(0===a[n].status,"Unexpected transaction status in abort"),a[n].unwatcher(),e=e.concat(Md(i.serverSyncTree_,a[n].currentWriteId,!0)),a[n].onComplete&&o.push(a[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?lp(s,void 0):a.length=t+1,Pp(i.eventQueue_,dp(s),e);for(let r=0;r<o.length;r++)Tl(o[r])}}const of=function(e,t){var n=cf(e),r=n.namespace;"firebase.com"===n.domain&&ll(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||ll("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||hl();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Rl(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new Wl(n.pathString)}},cf=function(r){let i="",s="",a="",o="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(o=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,p=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):ul(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const f=i.slice(0,e);"localhost"===f.toLowerCase()?s="localhost":f.split(".").length<=2?s=f:(d=i.indexOf("."),a=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=a),"ns"in p&&(c=p.ns)}return{host:i,port:h,domain:s,subdomain:a,secure:l,scheme:u,pathString:o,namespace:c}};class lf{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+O(this.snapshot.exportVal())}}class uf{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class hf{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class df{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new A;return Wp(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){_p("OnDisconnect.remove",this._path);const e=new A;return Gp(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){_p("OnDisconnect.set",this._path),fp("OnDisconnect.set",e,this._path,!1);const t=new A;return Gp(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){_p("OnDisconnect.setWithPriority",this._path),fp("OnDisconnect.setWithPriority",e,this._path,!1),mp("OnDisconnect.setWithPriority",t,!1);const n=new A;return function(n,r,e,t,i){const s=Vu(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&dh(n.onDisconnect_,r,s),Jp(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){_p("OnDisconnect.update",this._path),gp("OnDisconnect.update",e,this._path,!1);const t=new A;return function(r,i,n,s){if(U(n))return cl("onDisconnect().update() called with empty data. Don't do anything."),Jp(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&ml(n,(e,t)=>{var n=Vu(t);dh(r.onDisconnect_,eu(i,e),n)}),Jp(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class pf{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return tu(this._path)?null:Jl(this._path)}get ref(){return new vf(this._repo,this._path)}get _queryIdentifier(){var e=ch(this._queryParams),e=sl(e);return"{}"===e?"default":e}get _queryObject(){return ch(this._queryParams)}isEqual(e){if(!((e=ae(e))instanceof pf))return!1;var t=this._repo===e._repo,n=iu(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function ff(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function gf(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===gu){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==pl)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==fl)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===Au){if(null!=t&&!Cp(t)||null!=n&&!Cp(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(f(e.getIndex()instanceof Bu||e.getIndex()===$u,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function mf(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 vf extends pf{constructor(e,t){super(e,t,new rh,!1)}get parent(){var e=Zl(this._path);return null===e?null:new vf(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class yf{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new Wl(e),n=bf(this.ref,e);return new yf(this._node.getChild(t),n,Au)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new yf(t,bf(this.ref,e),Au)))}hasChild(e){var t=new Wl(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 _f(e,t){return(e=ae(e))._checkNotDeleted("ref"),void 0!==t?bf(e._root,t):e._root}function wf(e,t){(e=ae(e))._checkNotDeleted("refFromURL");const n=of(t,e._repo.repoInfo_.nodeAdmin);Np("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||ll("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),_f(e,n.path.toString())}function bf(e,t){return(null===Hl((e=ae(e))._path)?yp:Ap)("child","path",t,!1),new vf(e._repo,eu(e._path,t))}function If(e,t){e=ae(e),_p("set",e._path),fp("set",t,e._path,!1);const n=new A;return zp(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Tf(e,t){gp("update",t,e._path,!1);const n=new A;return function(i,s,e,a){Yp(i,"update",{path:s.toString(),value:e});let n=!0;const r=Vp(i),o={};if(ml(e,(e,t)=>{n=!1,o[e]=rp(eu(s,e),Vu(t),i.serverSyncTree_,r)}),n)cl("update() called with empty data. Don't do anything."),Jp(0,a,"ok",void 0);else{const c=$p(i);var t=Od(i.serverSyncTree_,s,o,c);xp(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||ul("update at "+s+" failed: "+e);var r=Md(i.serverSyncTree_,c,!n),n=0<r.length?ef(i,s):s;Pp(i.eventQueue_,n,r),Jp(0,a,e,t)}),ml(e,e=>{var t=sf(i,eu(s,e));ef(i,t)}),Pp(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function Ef(t){t=ae(t);var i,s,a,e=new hf(()=>{}),e=new kf(e);return i=t._repo,s=t,a=e,(null!=(e=Bd(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=Vu(e).withIndex(s._queryParams.getIndex());qd(i.serverSyncTree_,s,a,!0);let r;return r=s._queryParams.loadsAllData()?Ld(i.serverSyncTree_,s._path,n):(t=zd(i.serverSyncTree_,s),Ud(i.serverSyncTree_,s._path,n,t)),Pp(i.eventQueue_,s._path,r),Fd(i.serverSyncTree_,s,a,null,!0),n},e=>(Yp(i,"get for query "+O(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new yf(e,new vf(t._repo,t._path),t._queryParams.getIndex()))}class kf{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new lf("value",this,new yf(e.snapshotNode,new vf(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new uf(this,e,t):null}matches(e){return e instanceof kf&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Cf{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new uf(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=bf(new vf(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new lf(e.type,this,new yf(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Cf&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function Sf(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var a=(e,t)=>{Hp(n._repo,n,o),c(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new hf(t,s||void 0);const o="value"===e?new kf(a):new Cf(e,a);return function(e,t,n){let r;r=".info"===Hl(t._path)?qd(e.infoSyncTree_,t,n):qd(e.serverSyncTree_,t,n),Dp(e.eventQueue_,t._path,r)}(n._repo,n,o),()=>Hp(n._repo,n,o)}function Af(e,t,n,r){return Sf(e,"value",t,n,r)}function Nf(e,t,n,r){return Sf(e,"child_added",t,n,r)}function Rf(e,t,n,r){return Sf(e,"child_changed",t,n,r)}function xf(e,t,n,r){return Sf(e,"child_moved",t,n,r)}function Df(e,t,n,r){return Sf(e,"child_removed",t,n,r)}function Pf(e,t,n){let r=null;var i=n?new hf(n):null;"value"===t?r=new kf(i):t&&(r=new Cf(t,i)),Hp(e._repo,e,r)}class Of{}class Mf extends Of{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){fp("endAt",this._value,e._path,!0);var t=sh(e._queryParams,this._value,this._key);if(mf(t),gf(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new pf(e._repo,e._path,t,e._orderByCalled)}}class Lf extends Of{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){fp("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r,i;return i=e.index_===gu?sh(e,t="string"==typeof t?Ku(t):t,n):(r=null==n?pl:Ku(n),sh(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(mf(t),gf(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new pf(e._repo,e._path,t,e._orderByCalled)}}class Ff extends Of{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){fp("startAt",this._value,e._path,!0);var t=ih(e._queryParams,this._value,this._key);if(mf(t),gf(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new pf(e._repo,e._path,t,e._orderByCalled)}}class Uf extends Of{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){fp("startAfter",this._value,e._path,!1);var t=function(t,n,r){let i;if(t.index_===gu)"string"==typeof n&&(n=ju(n)),i=ih(t,n,r);else{let e;e=null==r?fl:ju(r),i=ih(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(mf(t),gf(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new pf(e._repo,e._path,t,e._orderByCalled)}}class qf extends Of{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new pf(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class Vf extends Of{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new pf(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class Bf extends Of{constructor(e){super(),this._path=e}_apply(e){ff(e,"orderByChild");var t=new Wl(this._path);if(tu(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new Bu(t),t=ah(e._queryParams,t);return gf(t),new pf(e._repo,e._path,t,!0)}}class jf extends Of{_apply(e){ff(e,"orderByKey");var t=ah(e._queryParams,gu);return gf(t),new pf(e._repo,e._path,t,!0)}}class Kf extends Of{_apply(e){ff(e,"orderByPriority");var t=ah(e._queryParams,Au);return gf(t),new pf(e._repo,e._path,t,!0)}}class $f extends Of{_apply(e){ff(e,"orderByValue");var t=ah(e._queryParams,$u);return gf(t),new pf(e._repo,e._path,t,!0)}}class zf extends Of{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(fp("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 Mf(this._value,this._key)._apply(new Ff(this._value,this._key)._apply(e))}}function Wf(e,...t){let n=ae(e);for(const r of t)n=r._apply(n);return n}Kc=vf,f(!yd,"__referenceConstructor has already been defined"),yd=Kc,$c=vf,f(!Rd,"__referenceConstructor has already been defined"),Rd=$c;const Gf="FIREBASE_DATABASE_EMULATOR_HOST",Hf={};let Qf=!1;function Yf(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||ll("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),cl("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let a=of(s,i),o=a.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[Gf]),l?(c=!0,s=`http://${l}?ns=${o.namespace}`,a=of(s,i),o=a.repoInfo):c=!a.repoInfo.secure;var u=i&&c?new Cl(Cl.OWNER):new kl(e.name,e.options,t);Np("Invalid Firebase Database URL",a),tu(a.path)||ll("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=Hf[t.name];i||(i={},Hf[t.name]=i);var s=i[e.toURLString()];s&&ll("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new Fp(e,Qf,n,r),i[e.toURLString()]=s}(o,e,u,new El(e.name,n));return new Jf(u,e)}class Jf{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Up(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new vf(this._repo,Gl())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=Hf[t];n&&n[e.key]===e||ll(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Qp(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&ll("Cannot call "+e+" on a deleted database.")}}function Xf(){Bl.IS_TRANSPORT_INITIALIZED&&ul("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Zf(){Xf(),Fl.forceDisallow()}function eg(){Xf(),Vl.forceDisallow(),Fl.forceAllow()}function tg(e,t,n,r={}){(e=ae(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&ll("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&ll('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 Cl(Cl.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:N(r.mockUserToken,e.app.options.projectId),a=new Cl(i)),r=s,e=t,t=n,n=a,r.repoInfo_=new Rl(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams),n&&(r.authTokenProvider_=n)}function ng(e){(e=ae(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Mp)}function rg(e,t){ol(e,t)}const ig={".sv":"timestamp"};class sg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function ag(i,e,t){if(i=ae(i),_p("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new A;var r=Af(i,()=>{});return function(t,n,e,r,i,s){Yp(t,"transaction on "+n);const a={path:n,update:e,onComplete:r,status:null,order:Jc(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},o=Xp(t,n,void 0);a.currentInputSnapshot=o;var c=a.update(o.val());if(void 0===c)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Sp("transaction failed: Data returned ",c,a.path),a.status=0;var l=op(t.transactionQueueTree_,n);const u=cp(l)||[];u.push(a),lp(l,u);let e;if("object"==typeof c&&null!==c&&L(c,".priority"))e=F(c,".priority"),f(Cp(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=Vd(t.serverSyncTree_,n)||Lu.EMPTY_NODE;e=h.getPriority().val()}l=Vp(t),c=Vu(c,e),l=ip(c,o,l);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=l,a.currentWriteId=$p(t);l=Pd(t.serverSyncTree_,n,l,a.currentWriteId,a.applyLocally);Pp(t.eventQueue_,n,l),Zp(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new yf(n,new vf(i._repo,i._path),Au),s.resolve(new sg(t,r)))},r,n),s.promise}uu.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},uu.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Fc(Ye),We(new oe("database",(e,{instanceIdentifier:t})=>{return Yf(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),et(Mc,"0.13.9",zc),et(Mc,"0.13.9","esm2017");function og(e){var t="FIREBASE WARNING: "+e;cg.warn(t)}const cg=new me("@firebase/database-compat");class lg{constructor(e){this._delegate=e}cancel(t){Q("OnDisconnect.cancel",0,1,arguments.length),J("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Q("OnDisconnect.remove",0,1,arguments.length),J("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Q("OnDisconnect.set",1,2,arguments.length),J("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Q("OnDisconnect.setWithPriority",2,3,arguments.length),J("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Q("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,og("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.")}J("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class ug{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Q("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class hg{constructor(e,t){this._database=e,this._delegate=t}val(){return Q("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Q("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Q("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Q("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Q("DataSnapshot.child",0,1,arguments.length),e=String(e),Ap("DataSnapshot.child","path",e,!1),new hg(this._database,this._delegate.child(e))}hasChild(e){return Q("DataSnapshot.hasChild",1,1,arguments.length),Ap("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Q("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Q("DataSnapshot.forEach",1,1,arguments.length),J("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new hg(this._database,e)))}hasChildren(){return Q("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Q("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Q("DataSnapshot.ref",0,0,arguments.length),new pg(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class dg{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Q("Query.on",2,4,arguments.length),J("Query.on","callback",n,!1);const s=dg.getCancelAndContextArgs_("Query.on",t,r);var a=(e,t)=>{n.call(s.context,new hg(this.database,e),t)};a.userCallback=n,a.context=s.context;var o=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return Af(this._delegate,a,o),n;case"child_added":return Nf(this._delegate,a,o),n;case"child_removed":return Df(this._delegate,a,o),n;case"child_changed":return Rf(this._delegate,a,o),n;case"child_moved":return xf(this._delegate,a,o),n;default:throw new Error(Y("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Q("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(Y(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),J("Query.off","callback",t,!0),X("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,Pf(this._delegate,e,r)):Pf(this._delegate,e)}get(){return Ef(this._delegate).then(e=>new hg(this.database,e))}once(e,r,t,n){Q("Query.once",1,4,arguments.length),J("Query.once","callback",r,!0);const i=dg.getCancelAndContextArgs_("Query.once",t,n),s=new A;var a=(e,t)=>{var n=new hg(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};a.userCallback=r,a.context=i.context;var o=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":Af(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":Nf(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Df(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":Rf(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":xf(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(Y("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 Q("Query.limitToFirst",1,1,arguments.length),new dg(this.database,Wf(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new qf(e)}(e)))}limitToLast(e){return Q("Query.limitToLast",1,1,arguments.length),new dg(this.database,Wf(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Vf(e)}(e)))}orderByChild(e){return Q("Query.orderByChild",1,1,arguments.length),new dg(this.database,Wf(this._delegate,function(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 Ap("orderByChild","path",e,!1),new Bf(e)}(e)))}orderByKey(){return Q("Query.orderByKey",0,0,arguments.length),new dg(this.database,Wf(this._delegate,new jf))}orderByPriority(){return Q("Query.orderByPriority",0,0,arguments.length),new dg(this.database,Wf(this._delegate,new Kf))}orderByValue(){return Q("Query.orderByValue",0,0,arguments.length),new dg(this.database,Wf(this._delegate,new $f))}startAt(e=null,t){return Q("Query.startAt",0,2,arguments.length),new dg(this.database,Wf(this._delegate,([e=null,t]=[e,t],vp("startAt","key",t,!0),new Ff(e,t))))}startAfter(e=null,t){return Q("Query.startAfter",0,2,arguments.length),new dg(this.database,Wf(this._delegate,(e=e,t=t,vp("startAfter","key",t,!0),new Uf(e,t))))}endAt(e=null,t){return Q("Query.endAt",0,2,arguments.length),new dg(this.database,Wf(this._delegate,(e=e,t=t,vp("endAt","key",t,!0),new Mf(e,t))))}endBefore(e=null,t){return Q("Query.endBefore",0,2,arguments.length),new dg(this.database,Wf(this._delegate,(e=e,t=t,vp("endBefore","key",t,!0),new Lf(e,t))))}equalTo(e,t){return Q("Query.equalTo",1,2,arguments.length),new dg(this.database,Wf(this._delegate,(e=e,t=t,vp("equalTo","key",t,!0),new zf(e,t))))}toString(){return Q("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Q("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Q("Query.isEqual",1,1,arguments.length),e instanceof dg)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,J(e,"cancel",r.cancel,!0),r.context=n,X(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(Y(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new pg(this.database,new vf(this._delegate._repo,this._delegate._path))}}class pg extends dg{constructor(e,t){super(e,new pf(t._repo,t._path,new rh,!1)),this.database=e,this._delegate=t}getKey(){return Q("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Q("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new pg(this.database,bf(this._delegate,e))}getParent(){Q("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new pg(this.database,e):null}getRoot(){return Q("Reference.root",0,0,arguments.length),new pg(this.database,this._delegate.root)}set(e,t){Q("Reference.set",1,2,arguments.length),J("Reference.set","onComplete",t,!0);const n=If(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Q("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,og("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.")}_p("Reference.update",this._delegate._path),J("Reference.update","onComplete",n,!0);const e=Tf(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Q("Reference.setWithPriority",2,3,arguments.length),J("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(_p("setWithPriority",e._path),fp("setWithPriority",t,e._path,!1),mp("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new A;return zp(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Q("Reference.remove",0,1,arguments.length),J("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,_p("remove",n._path),If(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Q("Reference.transaction",1,3,arguments.length),J("Reference.transaction","transactionUpdate",e,!1),J("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(Y(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=ag(this._delegate,e,{applyLocally:n}).then(e=>new ug(e.committed,new hg(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Q("Reference.setPriority",1,2,arguments.length),J("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=ae(e),_p("setPriority",e._path),mp("setPriority",t,!1);const n=new A;return zp(e._repo,eu(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Q("Reference.push",0,2,arguments.length),J("Reference.push","onComplete",t,!0);const n=function(e,t){e=ae(e),_p("push",e._path),fp("push",t,e._path,!0);var n=qp(e._repo),n=Qu(n);const r=bf(e,n),i=bf(e,n);let s;return s=null!=t?If(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new pg(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new pg(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return _p("Reference.onDisconnect",this._delegate._path),new lg(new df(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class fg{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Zf,forceLongPolling:eg}}useEmulator(e,t,n={}){tg(this._delegate,e,t,n)}ref(e){if(Q("database.ref",0,1,arguments.length),e instanceof pg){var t=wf(this._delegate,e.toString());return new pg(this,t)}t=_f(this._delegate,e);return new pg(this,t)}refFromURL(e){Q("database.refFromURL",1,1,arguments.length);var t=wf(this._delegate,e);return new pg(this,t)}goOffline(){var e;Q("database.goOffline",0,0,arguments.length),(e=ae(e=this._delegate))._checkNotDeleted("goOffline"),Qp(e._repo)}goOnline(){return Q("database.goOnline",0,0,arguments.length),ng(this._delegate)}}fg.ServerValue={TIMESTAMP:ig,increment:e=>({".sv":{increment:e}})};var gg,mg=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){Fc(n);const a=new le("auth-internal",new ue("database-standalone"));return a.setComponent(new oe("auth-internal",()=>r,"PRIVATE")),{instance:new fg(Yf(e,a,void 0,t,s),e),namespace:i}}});const vg=fg.ServerValue;(gg=wt).INTERNAL.registerComponent(new oe("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new fg(r,n)},"PUBLIC").setServiceProps({Reference:pg,Query:dg,Database:fg,DataSnapshot:hg,enableLogging:rg,INTERNAL:mg,ServerValue:vg}).setMultipleInstances(!0)),gg.registerVersion("@firebase/database-compat","0.2.9");var yt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},yg={},_g=yt||self;function wg(){}function bg(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 Ig(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Tg="closure_uid_"+(1e9*Math.random()>>>0),Eg=0;function kg(e,t,n){return e.call.apply(e.bind,arguments)}function Cg(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function Sg(e,t,n){return(Sg=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?kg:Cg).apply(null,arguments)}function Ag(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function Ng(e,s){function t(){}t.prototype=s.prototype,e.X=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Wb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function Rg(){this.s=this.s,this.o=this.o}var xg={};Rg.prototype.s=!1,Rg.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,Tg)&&t[Tg]||(t[Tg]=++Eg),delete xg[e])},Rg.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Dg=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function Pg(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function Og(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(bg(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function Mg(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}Mg.prototype.h=function(){this.defaultPrevented=!0};var Lg=function(){if(!_g.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{_g.addEventListener("test",wg,t),_g.removeEventListener("test",wg,t)}catch(e){}return e}();function Fg(e){return/^[\s\xa0]*$/.test(e)}var Ug=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function qg(e,t){return e<t?-1:t<e?1:0}function Vg(){var e=_g.navigator;return(e=e&&e.userAgent)?e:""}function Bg(e){return-1!=Vg().indexOf(e)}function jg(e){return jg[" "](e),e}jg[" "]=wg;var Kg,$g=Bg("Opera"),zg=Bg("Trident")||Bg("MSIE"),Wg=Bg("Edge"),Gg=Wg||zg,Hg=Bg("Gecko")&&!(-1!=Vg().toLowerCase().indexOf("webkit")&&!Bg("Edge"))&&!(Bg("Trident")||Bg("MSIE"))&&!Bg("Edge"),Qg=-1!=Vg().toLowerCase().indexOf("webkit")&&!Bg("Edge");function Yg(){var e=_g.document;return e?e.documentMode:void 0}e:{var Jg="",Xg=(Xg=Vg(),Hg?/rv:([^\);]+)(\)|;)/.exec(Xg):Wg?/Edge\/([\d\.]+)/.exec(Xg):zg?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Xg):Qg?/WebKit\/(\S+)/.exec(Xg):$g?/(?:Version)[ \/]?(\S+)/.exec(Xg):void 0);if(Xg&&(Jg=Xg?Xg[1]:""),zg){Xg=Yg();if(null!=Xg&&Xg>parseFloat(Jg)){Kg=String(Xg);break e}}Kg=Jg}var Zg={};function em(){return e=function(){let e=0;var t=Ug(String(Kg)).split("."),n=Ug("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a<r;a++)for(var i=t[a]||"",s=n[a]||"";i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],(0!=i[0].length||0!=s[0].length)&&(e=qg(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||qg(0==i[2].length,0==s[2].length)||qg(i[2],s[2]),i=i[3],s=s[3],0==e););return 0<=e},t=Zg,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var tm=_g.document&&zg&&(Yg()||parseInt(Kg,10))||void 0;function nm(e,t){if(Mg.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 n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(Hg){e:{try{jg(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.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:rm[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&nm.X.h.call(this)}}Ng(nm,Mg);var rm={2:"touch",3:"pen",4:"mouse"};nm.prototype.h=function(){nm.X.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var im="closure_listenable_"+(1e6*Math.random()|0),sm=0;function am(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++sm,this.ba=this.ea=!1}function om(e){e.ba=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function cm(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function lm(e){const t={};for(const n in e)t[n]=e[n];return t}const um="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function hm(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<um.length;e++)n=um[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function dm(e){this.src=e,this.g={},this.h=0}function pm(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Dg(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(om(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function fm(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.ba&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}dm.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=fm(e,t,r,i);return-1<a?(t=e[a],n||(t.ea=!1)):((t=new am(t,this.src,s,!!r,i)).ea=n,e.push(t)),t};var gm="closure_lm_"+(1e6*Math.random()|0),mm={};function vm(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Em(r);return t&&t[im]?t.O(n,r,Ig(i)?!!i.capture:!!i,s):ym(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)vm(e,t[s],n,r,i);return null}return n=Em(n),e&&e[im]?e.N(t,n,Ig(r)?!!r.capture:!!r,i):ym(e,t,n,!1,r,i)}function ym(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=Ig(i)?!!i.capture:!!i,o=Im(e);if(o||(e[gm]=o=new dm(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=bm;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!Lg?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(wm(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function _m(e){var t,n,r;"number"!=typeof e&&e&&!e.ba&&((t=e.src)&&t[im]?pm(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(wm(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Im(t))?(pm(n,e),0==n.h&&(n.src=null,t[gm]=null)):om(e)))}function wm(e){return e in mm?mm[e]:mm[e]="on"+e}function bm(e,t){var n,r;return e=!!e.ba||(t=new nm(t,this),n=e.listener,r=e.ha||e.src,e.ea&&_m(e),n.call(r,t))}function Im(e){return(e=e[gm])instanceof dm?e:null}var Tm="__closure_events_fn_"+(1e9*Math.random()>>>0);function Em(t){return"function"==typeof t?t:(t[Tm]||(t[Tm]=function(e){return t.handleEvent(e)}),t[Tm])}function km(){Rg.call(this),this.i=new dm(this),(this.P=this).I=null}function Cm(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new Mg(t,e):t instanceof Mg?t.target=t.target||e:(a=t,hm(t=new Mg(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Sm(s,r,!0,t)&&a;if(a=Sm(s=t.g=e,r,!0,t)&&a,a=Sm(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Sm(s=t.g=n[i],r,!1,t)&&a}function Sm(e,t,n,r){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,c=t[s];c&&!c.ba&&c.capture==n&&(a=c.listener,o=c.ha||c.src,c.ea&&pm(e.i,c),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}Ng(km,Rg),km.prototype[im]=!0,km.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=Ig(i)?!!i.capture:!!i,r=Em(r),t&&t[im]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=fm(a=t.g[n],r,i,s))&&(om(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Im(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?fm(n,r,i,s):t)?n[t]:null)&&_m(r))}(this,e,t,n,r)},km.prototype.M=function(){if(km.X.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)om(n[r]);delete t.g[e],t.h--}}this.I=null},km.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},km.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Am=_g.JSON.stringify;var Nm,Rm=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 xm,e=>e.reset());class xm{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}}function Dm(e,t){var n;Nm||(n=_g.Promise.resolve(void 0),Nm=function(){n.then(Mm)}),Pm||(Nm(),Pm=!0),Om.add(e,t)}var Pm=!1,Om=new class{constructor(){this.h=this.g=null}add(e,t){const n=Rm.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Mm(){for(var e;e=function(){var e=Om;let 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){!function(e){_g.setTimeout(()=>{throw e},0)}(e)}var t=Rm;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Pm=!1}function Lm(e,t){km.call(this),this.h=e||1,this.g=t||_g,this.j=Sg(this.lb,this),this.l=Date.now()}function Fm(e){e.ca=!1,e.R&&(e.g.clearTimeout(e.R),e.R=null)}function Um(e,t,n){if("function"==typeof e)n&&(e=Sg(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Sg(e.handleEvent,e)}return 2147483647<Number(t)?-1:_g.setTimeout(e,t||0)}Ng(Lm,km),(bt=Lm.prototype).ca=!1,bt.R=null,bt.lb=function(){var e;this.ca&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.R=this.g.setTimeout(this.j,this.h-e):(this.R&&(this.g.clearTimeout(this.R),this.R=null),Cm(this,"tick"),this.ca&&(Fm(this),this.start())))},bt.start=function(){this.ca=!0,this.R||(this.R=this.g.setTimeout(this.j,this.h),this.l=Date.now())},bt.M=function(){Lm.X.M.call(this),Fm(this),delete this.g};class qm extends Rg{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Um(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(_g.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Vm(e){Rg.call(this),this.h=e,this.g={}}Ng(Vm,Rg);var Bm=[];function jm(e,t,n,r){Array.isArray(n)||(n&&(Bm[0]=n.toString()),n=Bm);for(var i=0;i<n.length;i++){var s=vm(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function Km(e){cm(e.g,function(e,t){this.g.hasOwnProperty(t)&&_m(e)},e),e.g={}}function $m(){this.g=!0}function zm(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[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 Am(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Vm.prototype.M=function(){Vm.X.M.call(this),Km(this)},Vm.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},$m.prototype.Aa=function(){this.g=!1},$m.prototype.info=function(){};var Wm={},Gm=null;function Hm(){return Gm=Gm||new km}function Qm(e){Mg.call(this,Wm.Pa,e)}function Ym(){var e=Hm();Cm(e,new Qm(e))}function Jm(e,t){Mg.call(this,Wm.STAT_EVENT,e),this.stat=t}function Xm(e){var t=Hm();Cm(t,new Jm(t,e))}function Zm(e,t){Mg.call(this,Wm.Qa,e),this.size=t}function ev(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return _g.setTimeout(function(){e()},t)}Wm.Pa="serverreachability",Ng(Qm,Mg),Wm.STAT_EVENT="statevent",Ng(Jm,Mg),Wm.Qa="timingevent",Ng(Zm,Mg);It={NO_ERROR:0,mb:1,zb:2,yb:3,tb:4,xb:5,Ab:6,Ma:7,TIMEOUT:8,Db:9},Wc={rb:"complete",Nb:"success",Na:"error",Ma:"abort",Fb:"ready",Gb:"readystatechange",TIMEOUT:"timeout",Bb:"incrementaldata",Eb:"progress",ub:"downloadprogress",Vb:"uploadprogress"};function tv(){}function nv(e){return e.h||(e.h=e.i())}function rv(){}tv.prototype.h=null;yt={OPEN:"a",qb:"b",Na:"c",Cb:"d"};function iv(){Mg.call(this,"d")}function sv(){Mg.call(this,"c")}function av(){}function ov(e,t,n,r){this.l=e,this.j=t,this.m=n,this.U=r||1,this.S=new Vm(this),this.O=uv,this.T=new Lm(e=Gg?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.V=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.Y=-1,this.I=!1,this.N=0,this.L=null,this.$=this.J=this.Z=this.P=!1,this.h=new cv}function cv(){this.i=null,this.g="",this.h=!1}Ng(iv,Mg),Ng(sv,Mg),Ng(av,tv),av.prototype.g=function(){return new XMLHttpRequest},av.prototype.i=function(){return{}};var lv=new av,uv=45e3,hv={},dv={};function pv(e,t,n){e.K=1,e.v=xv(Cv(t)),e.s=n,e.P=!0,fv(e,null)}function fv(e,t){e.F=Date.now(),vv(e),e.A=Cv(e.v);var a,o,c,l,u,h,n=e.A,r=e.U;Array.isArray(r)||(r=[String(r)]),$v(n.i,"t",r),e.C=0,n=e.l.H,e.h=new cv,e.g=Ky(e.l,n?t:null,!e.s),0<e.N&&(e.L=new qm(Sg(e.La,e,e.g),e.N)),jm(e.S,e.g,"readystatechange",e.ib),t=e.H?lm(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.da(e.A,e.u,e.s,t)):(e.u="GET",e.g.da(e.A,e.u,null,t)),Ym(),a=e.j,o=e.u,c=e.A,l=e.m,u=e.U,h=e.s,a.info(function(){if(a.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+o+"\n"+c+"\n"+e})}function gv(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Da)}function mv(e,t,n){let r=!0,i;for(;!e.I&&e.C<n.length;){if(i=(a=n,c=o=void 0,o=(s=e).C,-1==(c=a.indexOf("\n",o))?dv:(o=Number(a.substring(o,c)),isNaN(o)?hv:(c+=1)+o>a.length?dv:(a=a.substr(c,o),s.C=c+o,a))),i==dv){4==t&&(e.o=4,Xm(14),r=!1),zm(e.j,e.m,null,"[Incomplete Response]");break}if(i==hv){e.o=4,Xm(15),zm(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}zm(e.j,e.m,i,null),Iv(e,i)}var s,a,o,c;gv(e)&&i!=dv&&i!=hv&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,Xm(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.$&&(e.$=!0,(t=e.l).g==e&&t.$&&!t.K&&(t.j.info("Great, no buffering proxy detected. Bytes received: "+n.length),My(t),t.K=!0,Xm(11))):(zm(e.j,e.m,n,"[Invalid Chunked Response]"),bv(e),wv(e))}function vv(e){e.V=Date.now()+e.O,yv(e,e.O)}function yv(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=ev(Sg(e.gb,e),t)}function _v(e){e.B&&(_g.clearTimeout(e.B),e.B=null)}function wv(e){0==e.l.G||e.I||Uy(e.l,e)}function bv(e){_v(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,Fm(e.T),Km(e.S),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Iv(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||Jv(n.h,e)))if(!e.J&&Jv(n.h,e)&&3==n.G){try{var r=n.Fa.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Fy(n),Sy(n)}Oy(n),Xm(18)}}else n.Ba=i[1],0<n.Ba-n.T&&i[2]<37500&&n.L&&0==n.A&&!n.v&&(n.v=ev(Sg(n.cb,n),6e3));if(Yv(n.h)<=1&&n.ja){try{n.ja()}catch(e){}n.ja=void 0}}else Vy(n,11)}else if(!e.J&&n.g!=e||Fy(n),!Fg(t))for(i=n.Fa.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.T=s[0],s=s[1],2==n.G)if("c"==s[0]){n.I=s[1],n.ka=s[2];var a=s[3];null!=a&&(n.ma=a,n.j.info("VER="+n.ma));var o=s[4];null!=o&&(n.Ca=o,n.j.info("SVER="+n.Ca));var c,l,u=s[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,n.J=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const f=e.g;if(f){const g=f.g?f.g.getResponseHeader("X-Client-Wire-Protocol"):null;g&&((c=r.h).g||-1==g.indexOf("spdy")&&-1==g.indexOf("quic")&&-1==g.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(Xv(c,c.h),c.h=null))),!r.D||(l=f.g?f.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.za=l,Rv(r.F,r.D,l))}n.G=3,n.l&&n.l.xa(),n.$&&(n.P=Date.now()-e.F,n.j.info("Handshake RTT: "+n.P+"ms"));var h,d,p=e;(r=n).sa=jy(r,r.H?r.ka:null,r.V),p.J?(Zv(r.h,p),h=p,(d=r.J)&&h.setTimeout(d),h.B&&(_v(h),vv(h)),r.g=p):Py(r),0<n.i.length&&Ny(n)}else"stop"!=s[0]&&"close"!=s[0]||Vy(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?Vy(n,7):Cy(n):"noop"!=s[0]&&n.l&&n.l.wa(s),n.A=0)}Ym()}catch(e){}}function Tv(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(bg(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.oa&&"function"==typeof e.oa)return e.oa();if(!e.W||"function"!=typeof e.W){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(bg(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.W&&"function"==typeof e.W)return e.W();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(bg(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(bt=ov.prototype).setTimeout=function(e){this.O=e},bt.ib=function(e){e=e.target;const t=this.L;t&&3==wy(e)?t.l():this.La(e)},bt.La=function(e){try{if(e==this.g)e:{var t=wy(this.g),n=this.g.Ea();this.g.aa();if(!(t<3)&&(3!=t||Gg||this.g&&(this.h.h||this.g.fa()||by(this.g)))){this.I||4!=t||7==n||Ym(),_v(this);var r=this.g.aa();this.Y=r;t:if(gv(this)){var i=by(this.g);e="";var s=i.length,a=4==wy(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){bv(this),wv(this);var o="";break t}this.h.i=new _g.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:a&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.fa();if(this.i=200==r,h=this.j,d=this.u,p=this.A,f=this.m,g=this.U,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+f+") [ attempt "+g+"]: "+d+"\n"+p+"\n"+m+" "+v}),this.i){if(this.Z&&!this.J){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!Fg(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,Xm(12),bv(this),wv(this);break e}zm(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Iv(this,r)}this.P?(mv(this,t,o),Gg&&this.i&&3==t&&(jm(this.S,this.T,"tick",this.hb),this.T.start())):(zm(this.j,this.m,o,null),Iv(this,o)),4==t&&bv(this),this.i&&!this.I&&(4==t?Uy(this.l,this):(this.i=!1,vv(this)))}else 400==r&&0<o.indexOf("Unknown SID")?(this.o=3,Xm(12)):(this.o=0,Xm(13)),bv(this),wv(this)}}}catch(e){}var h,d,p,f,g,m,v},bt.hb=function(){var e,t;this.g&&(e=wy(this.g),t=this.g.fa(),this.C<t.length&&(_v(this),mv(this,e,t),this.i&&4!=e&&vv(this)))},bt.cancel=function(){this.I=!0,bv(this)},bt.gb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.V?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.K&&(Ym(),Xm(17)),bv(this),this.o=2,wv(this)):yv(this,this.V-n)};var Ev=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function kv(e,t){var n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof kv?(this.h=void 0!==t?t:e.h,Sv(this,e.j),this.s=e.s,this.g=e.g,Av(this,e.m),this.l=e.l,t=e.i,(n=new Vv).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Nv(this,n),this.o=e.o):e&&(n=String(e).match(Ev))?(this.h=!!t,Sv(this,n[1]||"",!0),this.s=Dv(n[2]||""),this.g=Dv(n[3]||"",!0),Av(this,n[4]),this.l=Dv(n[5]||"",!0),Nv(this,n[6]||"",!0),this.o=Dv(n[7]||"")):(this.h=!!t,this.i=new Vv(null,this.h))}function Cv(e){return new kv(e)}function Sv(e,t,n){e.j=n?Dv(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Av(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Nv(e,t,n){var r,i;t instanceof Vv?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(Bv(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(jv(this,t),$v(this,n,e))},r)),r.j=i):(n||(t=Pv(t,Uv)),e.i=new Vv(t,e.h))}function Rv(e,t,n){e.i.set(t,n)}function xv(e){return Rv(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Dv(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Pv(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Ov),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Ov(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}kv.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Pv(t,Mv,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Pv(t,Mv,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Pv(n,"/"==n.charAt(0)?Fv:Lv,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Pv(n,qv)),e.join("")};var Mv=/[#\/\?@]/g,Lv=/[#\?:]/g,Fv=/[#\?]/g,Uv=/[#\?@]/g,qv=/#/g;function Vv(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Bv(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function jv(e,t){Bv(e),t=zv(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Kv(e,t){return Bv(e),t=zv(e,t),e.g.has(t)}function $v(e,t,n){jv(e,t),0<n.length&&(e.i=null,e.g.set(zv(e,t),Pg(n)),e.h+=n.length)}function zv(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(bt=Vv.prototype).add=function(e,t){Bv(this),this.i=null,e=zv(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},bt.forEach=function(n,r){Bv(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},bt.oa=function(){Bv(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},bt.W=function(t){Bv(this);let n=[];if("string"==typeof t)Kv(this,t)&&(n=n.concat(this.g.get(zv(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},bt.set=function(e,t){return Bv(this),this.i=null,Kv(this,e=zv(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},bt.get=function(e,t){return e&&0<(e=this.W(e)).length?String(e[0]):t},bt.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.W(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")};var Wv=class{constructor(e,t){this.h=e,this.g=t}};function Gv(e){this.l=e||10,e=_g.PerformanceNavigationTiming?0<(e=_g.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(_g.g&&_g.g.Ga&&_g.g.Ga()&&_g.g.Ga().$b),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var Hv;function Qv(e){return e.h||e.g&&e.g.size>=e.j}function Yv(e){return e.h?1:e.g?e.g.size:0}function Jv(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Xv(e,t){e.g?e.g.add(t):e.h=t}function Zv(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function ey(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Pg(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function ty(){}function ny(){this.g=new ty}function ry(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function iy(e){this.l=e.ac||null,this.j=e.jb||!1}function sy(e,t){km.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=ay,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Gv.prototype.cancel=function(){if(this.i=ey(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},ty.prototype.stringify=function(e){return _g.JSON.stringify(e,void 0)},ty.prototype.parse=function(e){return _g.JSON.parse(e,void 0)},Ng(iy,tv),iy.prototype.g=function(){return new sy(this.l,this.j)},iy.prototype.i=(Hv={},function(){return Hv}),Ng(sy,km);var ay=0;function oy(e){e.j.read().then(e.Ta.bind(e)).catch(e.ga.bind(e))}function cy(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ly(e)}function ly(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(bt=sy.prototype).open=function(e,t){if(this.readyState!=ay)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ly(this)},bt.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||_g).fetch(new Request(this.B,t)).then(this.Wa.bind(this),this.ga.bind(this))},bt.abort=function(){this.response=this.responseText="",this.v=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,cy(this)),this.readyState=ay},bt.Wa=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,ly(this)),this.g&&(this.readyState=3,ly(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ua.bind(this),this.ga.bind(this));else if(void 0!==_g.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;oy(this)}else e.text().then(this.Va.bind(this),this.ga.bind(this))},bt.Ta=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?cy:ly)(this),3==this.readyState&&oy(this))},bt.Va=function(e){this.g&&(this.response=this.responseText=e,cy(this))},bt.Ua=function(e){this.g&&(this.response=e,cy(this))},bt.ga=function(){this.g&&cy(this)},bt.setRequestHeader=function(e,t){this.v.append(e,t)},bt.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},bt.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(sy.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var uy=_g.JSON.parse;function hy(e){km.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=dy,this.K=this.L=!1}Ng(hy,km);var dy="",py=/^https?$/i,fy=["POST","PUT"];function gy(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,my(e),yy(e)}function my(e){e.D||(e.D=!0,Cm(e,"complete"),Cm(e,"error"))}function vy(e){if(e.h&&void 0!==yg&&(!e.C[1]||4!=wy(e)||2!=e.aa()))if(e.v&&4==wy(e))Um(e.Ha,0,e);else if(Cm(e,"readystatechange"),4==wy(e)){e.h=!1;try{var t,n,r,i,s=e.aa();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var a=!0;break e;default:a=!1}if((t=a)||((n=0===s)&&(!(i=String(e.H).match(Ev)[1]||null)&&_g.self&&_g.self.location&&(i=(r=_g.self.location.protocol).substr(0,r.length-1)),n=!py.test(i?i.toLowerCase():"")),t=n),t)Cm(e,"complete"),Cm(e,"success");else{e.m=6;try{var o=2<wy(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.aa()+"]",my(e)}}finally{yy(e)}}}function yy(e,t){if(e.g){_y(e);const n=e.g,r=e.C[0]?wg:null;e.g=null,e.C=null,t||Cm(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function _y(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(_g.clearTimeout(e.A),e.A=null)}function wy(e){return e.g?e.g.readyState:0}function by(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case dy:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Iy(e){let n="";return cm(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Ty(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Iy(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Rv(e,t,n))}function Ey(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function ky(e){this.Ca=0,this.i=[],this.j=new $m,this.ka=this.sa=this.F=this.V=this.g=this.za=this.D=this.ia=this.o=this.S=this.s=null,this.ab=this.U=0,this.Za=Ey("failFast",!1,e),this.L=this.v=this.u=this.m=this.l=null,this.Y=!0,this.pa=this.Ba=this.T=-1,this.Z=this.A=this.C=0,this.Xa=Ey("baseRetryDelayMs",5e3,e),this.bb=Ey("retryDelaySeedMs",1e4,e),this.$a=Ey("forwardChannelMaxRetries",2,e),this.ta=Ey("forwardChannelRequestTimeoutMs",2e4,e),this.ra=e&&e.xmlHttpFactory||void 0,this.Da=e&&e.Zb||!1,this.J=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.I="",this.h=new Gv(e&&e.concurrentRequestLimit),this.Fa=new ny,this.O=e&&e.fastHandshake||!1,this.N=e&&e.encodeInitMessageHeaders||!1,this.O&&this.N&&(this.N=!1),this.Ya=e&&e.Xb||!1,e&&e.Aa&&this.j.Aa(),e&&e.forceLongPolling&&(this.Y=!1),this.$=!this.O&&this.Y&&e&&e.detectBufferingProxy||!1,this.ja=void 0,this.P=0,this.K=!1,this.la=this.B=null}function Cy(e){var t,n;Ay(e),3==e.G&&(t=e.U++,Rv(n=Cv(e.F),"SID",e.I),Rv(n,"RID",t),Rv(n,"TYPE","terminate"),xy(e,n),(t=new ov(e,e.j,t,void 0)).K=2,t.v=xv(Cv(n)),n=!1,!(n=_g.navigator&&_g.navigator.sendBeacon?_g.navigator.sendBeacon(t.v.toString(),""):n)&&_g.Image&&((new Image).src=t.v,n=!0),n||(t.g=Ky(t.l,null),t.g.da(t.v)),t.F=Date.now(),vv(t)),By(e)}function Sy(e){e.g&&(My(e),e.g.cancel(),e.g=null)}function Ay(e){Sy(e),e.u&&(_g.clearTimeout(e.u),e.u=null),Fy(e),e.h.cancel(),e.m&&("number"==typeof e.m&&_g.clearTimeout(e.m),e.m=null)}function Ny(e){Qv(e.h)||e.m||(e.m=!0,Dm(e.Ja,e),e.C=0)}function Ry(e,t){var n=t?t.m:e.U++,r=Cv(e.F);Rv(r,"SID",e.I),Rv(r,"RID",n),Rv(r,"AID",e.T),xy(e,r),e.o&&e.s&&Ty(r,e.o,e.s),n=new ov(e,e.j,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.i=t.D.concat(e.i)),t=Dy(e,n,1e3),n.setTimeout(Math.round(.5*e.ta)+Math.round(.5*e.ta*Math.random())),Xv(e.h,n),pv(n,r,t)}function xy(e,n){e.ia&&cm(e.ia,function(e,t){Rv(n,t,e)}),e.l&&Tv({},function(e,t){Rv(n,t,e)})}function Dy(e,t,r){r=Math.min(e.i.length,r);var i=e.l?Sg(e.l.Ra,e.l,e):null;e:{var s=e.i;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].h,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].h,o=s[t].g;if((a-=n)<0)n=Math.max(0,s[t].h-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Tv(e,function(e,t){let n=e;Ig(e)&&(n=Am(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,c,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=c.join("&");break e}}}return e=e.i.splice(0,r),t.D=e,i}function Py(e){e.g||e.u||(e.Z=1,Dm(e.Ia,e),e.A=0)}function Oy(e){return!(e.g||e.u||3<=e.A)&&(e.Z++,e.u=ev(Sg(e.Ia,e),qy(e,e.A)),e.A++,1)}function My(e){null!=e.B&&(_g.clearTimeout(e.B),e.B=null)}function Ly(e){e.g=new ov(e,e.j,"rpc",e.Z),null===e.o&&(e.g.H=e.s),e.g.N=0;var t=Cv(e.sa);Rv(t,"RID","rpc"),Rv(t,"SID",e.I),Rv(t,"CI",e.L?"0":"1"),Rv(t,"AID",e.T),Rv(t,"TYPE","xmlhttp"),xy(e,t),e.o&&e.s&&Ty(t,e.o,e.s),e.J&&e.g.setTimeout(e.J);var n=e.g;e=e.ka,n.K=1,n.v=xv(Cv(t)),n.s=null,n.P=!0,fv(n,e)}function Fy(e){null!=e.v&&(_g.clearTimeout(e.v),e.v=null)}function Uy(e,t){var n,r,i,s=null;if(e.g==t){Fy(e),My(e),e.g=null;var a=2}else{if(!Jv(e.h,t))return;s=t.D,Zv(e.h,t),a=1}if(0!=e.G)if(e.pa=t.Y,t.i)1==a?(s=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,Cm(a=Hm(),new Zm(a,s)),Ny(e)):Py(e);else if(3==(n=t.o)||0==n&&0<e.pa||(1!=a||(i=t,Yv((r=e).h)>=r.h.j-(r.m?1:0)||(r.m?(r.i=i.D.concat(r.i),0):1==r.G||2==r.G||r.C>=(r.Za?0:r.$a)||(r.m=ev(Sg(r.Ja,r,i),qy(r,r.C)),r.C++,0))))&&(2!=a||!Oy(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),n){case 1:Vy(e,5);break;case 4:Vy(e,10);break;case 3:Vy(e,6);break;default:Vy(e,2)}}function qy(e,t){let n=e.Xa+Math.floor(Math.random()*e.bb);return e.l||(n*=2),n*t}function Vy(e,t){var n,r;e.j.info("Error code "+t),2==t?(n=null,e.l&&(n=null),r=Sg(e.kb,e),n||(n=new kv("//www.google.com/images/cleardot.gif"),_g.location&&"http"==_g.location.protocol||Sv(n,"https"),xv(n)),function(e,t){var n=new $m;if(_g.Image){const r=new Image;r.onload=Ag(ry,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Ag(ry,n,r,"TestLoadImage: error",!1,t),r.onabort=Ag(ry,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Ag(ry,n,r,"TestLoadImage: timeout",!1,t),_g.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):Xm(2),e.G=0,e.l&&e.l.va(t),By(e),Ay(e)}function By(e){var t;e.G=0,e.la=[],e.l&&(0==(t=ey(e.h)).length&&0==e.i.length||(Og(e.la,t),Og(e.la,e.i),e.h.i.length=0,Pg(e.i),e.i.length=0),e.l.ua())}function jy(e,t,n){var r,i,s=n instanceof kv?Cv(n):new kv(n,void 0);return""!=s.g?(t&&(s.g=t+"."+s.g),Av(s,s.m)):(s=(r=_g.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new kv(null,void 0),s&&Sv(i,s),t&&(i.g=t),r&&Av(i,r),n&&(i.l=n),s=i),n=e.D,t=e.za,n&&t&&Rv(s,n,t),Rv(s,"VER",e.ma),xy(e,s),s}function Ky(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Da&&!e.ra?new hy(new iy({jb:!0})):new hy(e.ra)).Ka(e.H),t}function $y(){}function zy(){if(zg&&!(10<=Number(tm)))throw Error("Environmental error: no available transport.")}function Wy(e,t){km.call(this),this.g=new ky(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.s=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.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.S=e,(e=t&&t.Yb)&&!Fg(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Fg(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Qy(this)}function Gy(e){iv.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;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 Hy(){sv.call(this),this.status=1}function Qy(e){this.g=e}(bt=hy.prototype).Ka=function(e){this.L=e},bt.da=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||lv).g(),this.C=this.u?nv(this.u):nv(lv),this.g.onreadystatechange=Sg(this.Ha,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void gy(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const c of r.keys())n.set(c,r.get(c))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=_g.FormData&&e instanceof _g.FormData,0<=Dg(fy,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{_y(this),0<this.B&&((this.K=(o=this.g,zg&&em()&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=Sg(this.qa,this)):this.A=Um(this.qa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){gy(this,e)}var o},bt.qa=function(){void 0!==yg&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Cm(this,"timeout"),this.abort(8))},bt.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Cm(this,"complete"),Cm(this,"abort"),yy(this))},bt.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),yy(this,!0)),hy.X.M.call(this)},bt.Ha=function(){this.s||(this.F||this.v||this.l?vy(this):this.fb())},bt.fb=function(){vy(this)},bt.aa=function(){try{return 2<wy(this)?this.g.status:-1}catch(e){return-1}},bt.fa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},bt.Sa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),uy(t)}},bt.Ea=function(){return this.m},bt.Oa=function(){return"string"==typeof this.j?this.j:String(this.j)},(bt=ky.prototype).ma=8,bt.G=1,bt.Ja=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;const s=new ov(this,this.j,t,void 0);let e=this.s;if(this.S&&(e?(e=lm(e),hm(e,this.S)):e=this.S),null!==this.o||this.N||(s.H=e,e=null),this.O)e:{for(var n=0,r=0;r<this.i.length;r++){var i=this.i[r];if("__data__"in i.g&&"string"==typeof(i=i.g.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.i.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Dy(this,s,n),Rv(r=Cv(this.F),"RID",t),Rv(r,"CVER",22),this.D&&Rv(r,"X-HTTP-Session-Id",this.D),xy(this,r),e&&(this.N?n="headers="+encodeURIComponent(String(Iy(e)))+"&"+n:this.o&&Ty(r,this.o,e)),Xv(this.h,s),this.Ya&&Rv(r,"TYPE","init"),this.O?(Rv(r,"$req",n),Rv(r,"SID","null"),s.Z=!0,pv(s,r,null)):pv(s,r,n),this.G=2}}else 3==this.G&&(t?Ry(this,t):0==this.i.length||Qv(this.h)||Ry(this))},bt.Ia=function(){var e;this.u=null,Ly(this),this.$&&!(this.K||null==this.g||this.P<=0)&&(e=2*this.P,this.j.info("BP detection timer enabled: "+e),this.B=ev(Sg(this.eb,this),e))},bt.eb=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.L=!1,this.K=!0,Xm(10),Sy(this),Ly(this))},bt.cb=function(){null!=this.v&&(this.v=null,Sy(this),Oy(this),Xm(19))},bt.kb=function(e){e?(this.j.info("Successfully pinged google.com"),Xm(2)):(this.j.info("Failed to ping google.com"),Xm(1))},(bt=$y.prototype).xa=function(){},bt.wa=function(){},bt.va=function(){},bt.ua=function(){},bt.Ra=function(){},zy.prototype.g=function(e,t){return new Wy(e,t)},Ng(Wy,km),Wy.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;Xm(0),e.V=t,e.ia=n||{},e.L=e.Y,e.F=jy(e,null,e.V),Ny(e)},Wy.prototype.close=function(){Cy(this.g)},Wy.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Am(e),e=t),n.i.push(new Wv(n.ab++,e)),3==n.G&&Ny(n)},Wy.prototype.M=function(){this.g.l=null,delete this.j,Cy(this.g),delete this.g,Wy.X.M.call(this)},Ng(Gy,iv),Ng(Hy,sv),Ng(Qy,$y),Qy.prototype.xa=function(){Cm(this.g,"a")},Qy.prototype.wa=function(e){Cm(this.g,new Gy(e))},Qy.prototype.va=function(e){Cm(this.g,new Hy)},Qy.prototype.ua=function(){Cm(this.g,"b")},zy.prototype.createWebChannel=zy.prototype.g,Wy.prototype.send=Wy.prototype.u,Wy.prototype.open=Wy.prototype.m,It.NO_ERROR=0,It.TIMEOUT=8,It.HTTP_ERROR=6,Wc.COMPLETE="complete",(rv.EventType=yt).OPEN="a",yt.CLOSE="b",yt.ERROR="c",yt.MESSAGE="d",km.prototype.listen=km.prototype.N,hy.prototype.listenOnce=hy.prototype.O,hy.prototype.getLastError=hy.prototype.Oa,hy.prototype.getLastErrorCode=hy.prototype.Ea,hy.prototype.getStatus=hy.prototype.aa,hy.prototype.getResponseJson=hy.prototype.Sa,hy.prototype.getResponseText=hy.prototype.fa,hy.prototype.send=hy.prototype.da,hy.prototype.setWithCredentials=hy.prototype.Ka;var Yy,Jy=Hm,Xy=It,Zy=Wc,e_=Wm,t_=10,n_=11,r_=iy,i_=rv,s_=hy;const a_="@firebase/firestore";class o_{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}}o_.UNAUTHENTICATED=new o_(null),o_.GOOGLE_CREDENTIALS=new o_("google-credentials-uid"),o_.FIRST_PARTY=new o_("first-party-uid"),o_.MOCK_USER=new o_("mock-user");let c_="9.12.1";const l_=new me("@firebase/firestore");function u_(){return l_.logLevel}function h_(e,...t){var n;l_.logLevel<=k.DEBUG&&(n=t.map(f_),l_.debug(`Firestore (${c_}): ${e}`,...n))}function d_(e,...t){var n;l_.logLevel<=k.ERROR&&(n=t.map(f_),l_.error(`Firestore (${c_}): ${e}`,...n))}function p_(e,...t){var n;l_.logLevel<=k.WARN&&(n=t.map(f_),l_.warn(`Firestore (${c_}): ${e}`,...n))}function f_(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function g_(e="Unexpected state"){var t=`FIRESTORE (${c_}) INTERNAL ASSERTION FAILED: `+e;throw d_(t),new Error(t)}function m_(e){e||g_()}const v_={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 y_ extends R{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class w_{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class b_{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(o_.UNAUTHENTICATED))}shutdown(){}}class I_{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 T_{constructor(e){this.t=e,this.currentUser=o_.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new __;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new __,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{h_("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,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):(h_("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new __))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(h_("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(m_("string"==typeof e.accessToken),new w_(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return m_(null===e||"string"==typeof e),new o_(e)}}class E_{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r,this.type="FirstParty",this.user=o_.FIRST_PARTY,this.p=new Map}I(){return this.g?this.g():(m_(!("object"!=typeof this.h||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}get headers(){this.p.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}class k_{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r}getToken(){return Promise.resolve(new E_(this.h,this.l,this.m,this.g))}start(e,t){e.enqueueRetryable(()=>t(o_.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class C_{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 S_{constructor(e){this.T=e,this.forceRefresh=!1,this.appCheck=null,this.A=null}start(t,n){const r=e=>{null!=e.error&&h_("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.A;return this.A=e.token,h_("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{h_("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.T.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.T.getImmediate({optional:!0}))?i(e):h_("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(m_("string"==typeof e.token),this.A=e.token,new C_(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class A_{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function N_(e,t){return e<t?-1:t<e?1:0}function R_(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function x_(e){return e+"\0"}class D_{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new y_(v_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new y_(v_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new y_(v_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new y_(v_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return D_.fromMillis(Date.now())}static fromDate(e){return D_.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new D_(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?N_(this.nanoseconds,e.nanoseconds):N_(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class P_{constructor(e){this.timestamp=e}static fromTimestamp(e){return new P_(e)}static min(){return new P_(new D_(0,0))}static max(){return new P_(new D_(253402300799,999999999))}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}}class O_{constructor(e,t,n){void 0===t?t=0:t>e.length&&g_(),void 0===n?n=e.length-t:n>e.length-t&&g_(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===O_.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof O_?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,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class M_ extends O_{construct(e,t,n){return new M_(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new y_(v_.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new M_(t)}static emptyPath(){return new M_([])}}const L_=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class F_ extends O_{construct(e,t,n){return new F_(e,t,n)}static isValidIdentifier(e){return L_.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!F_.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new F_(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new y_(v_.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new y_(v_.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new y_(v_.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new y_(v_.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new F_(t)}static emptyPath(){return new F_([])}}class U_{constructor(e){this.path=e}static fromPath(e){return new U_(M_.fromString(e))}static fromName(e){return new U_(M_.fromString(e).popFirst(5))}static empty(){return new U_(M_.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===M_.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return M_.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new U_(new M_(e.slice()))}}class q_{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function V_(e){return e.fields.find(e=>2===e.kind)}function B_(e){return e.fields.filter(e=>2!==e.kind)}q_.UNKNOWN_ID=-1;class j_{constructor(e,t){this.fieldPath=e,this.kind=t}}class K_{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new K_(0,W_.min())}}function $_(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=P_.fromTimestamp(1e9===r?new D_(n+1,0):new D_(n,r));return new W_(r,U_.empty(),t)}function z_(e){return new W_(e.readTime,e.key,-1)}class W_{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new W_(P_.min(),U_.empty(),-1)}static max(){return new W_(P_.max(),U_.empty(),-1)}}function G_(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=U_.comparator(e.documentKey,t.documentKey),0!==n?n:N_(e.largestBatchId,t.largestBatchId))}const H_="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Q_{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Y_(e){if(e.code!==v_.FAILED_PRECONDITION||e.message!==H_)throw e;h_("LocalStore","Unexpectedly lost primary lease")}class J_{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(r,i){return this.callbackAttached&&g_(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new J_((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof J_?t:J_.resolve(t)}catch(e){return J_.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):J_.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):J_.reject(t)}static resolve(n){return new J_((e,t)=>{e(n)})}static reject(n){return new J_((e,t)=>{t(n)})}static waitFor(e){return new J_((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=J_.resolve(!1);for(const n of e)t=t.next(e=>e?J_.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,c){return new J_((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;c(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new J_((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class X_{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.P=new __,this.transaction.oncomplete=()=>{this.P.resolve()},this.transaction.onabort=()=>{e.error?this.P.reject(new tw(n,e.error)):this.P.resolve()},this.transaction.onerror=e=>{var t=aw(e.target.error);this.P.reject(new tw(n,t))}}static open(e,t,n,r){try{return new X_(t,e.transaction(r,n))}catch(e){throw new tw(t,e)}}get v(){return this.P.promise}abort(e){e&&this.P.reject(e),this.aborted||(h_("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}V(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new rw(t)}}class Z_{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===Z_.D(h())&&d_("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.")}static delete(e){return h_("SimpleDb","Removing database:",e),iw(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!v())return!1;if(Z_.N())return!0;const e=h(),t=Z_.D(e),n=0<t&&t<10,r=Z_.k(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static N(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.O)}static M(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static k(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async F(s){return this.db||(h_("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new tw(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?r(new y_(v_.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?r(new y_(v_.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)):r(new tw(s,t))},i.onupgradeneeded=e=>{h_("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.$(t,i.transaction,e.oldVersion,this.version).next(()=>{h_("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.B&&(this.db.onversionchange=e=>this.B(e)),this.db}L(t){this.B=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.F(e);const t=X_.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.V(),e)).catch(e=>(t.abort(e),J_.reject(e))).toPromise();return s.catch(()=>{}),await t.v,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(h_("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class ew{constructor(e){this.U=e,this.q=!1,this.K=null}get isDone(){return this.q}get G(){return this.K}set cursor(e){this.U=e}done(){this.q=!0}j(e){this.K=e}delete(){return iw(this.U.delete())}}class tw extends y_{constructor(e,t){super(v_.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function nw(e){return"IndexedDbTransactionError"===e.name}class rw{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(h_("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(h_("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),iw(n)}add(e){return h_("SimpleDb","ADD",this.store.name,e,e),iw(this.store.add(e))}get(t){return iw(this.store.get(t)).next(e=>(h_("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return h_("SimpleDb","DELETE",this.store.name,e),iw(this.store.delete(e))}count(){return h_("SimpleDb","COUNT",this.store.name),iw(this.store.count())}W(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.H(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new J_((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}J(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new J_((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Y(e,t){h_("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.X=!1;var r=this.cursor(n);return this.H(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.H(r,t)}tt(i){const e=this.cursor({});return new J_((n,r)=>{e.onerror=e=>{var t=aw(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}H(e,s){const a=[];return new J_((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new ew(t),r=s(t.primaryKey,t.value,n);if(r instanceof J_){const e=r.catch(e=>(n.done(),J_.reject(e)));a.push(e)}n.isDone?i():null===n.G?t.continue():t.continue(n.G)}else i()}}).next(()=>J_.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function iw(e){return new J_((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=aw(e.target.error);r(t)}})}let sw=!1;function aw(e){const t=Z_.D(h());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new y_("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 sw||(sw=!0,setTimeout(()=>{throw e},0)),e}}return e}class ow{constructor(e,t){this.asyncQueue=e,this.et=t,this.task=null}start(){this.nt(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}nt(e){h_("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{h_("IndexBackiller",`Documents written: ${await this.et.st()}`)}catch(e){nw(e)?h_("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await Y_(e)}await this.nt(6e4)})}}class cw{constructor(e,t){this.localStore=e,this.persistence=t}async st(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.it(e,t))}it(e,t){const n=new Set;let r=t,i=!0;return J_.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(h_("IndexBackiller",`Processing collection: ${t}`),this.rt(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}rt(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.ot(n,e)).next(e=>(h_("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}ot(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=z_(t);0<G_(n,r)&&(r=n)}),new W_(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class lw{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ut(e),this.ct=e=>t.writeSequenceNumber(e))}ut(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ct&&this.ct(e),e}}function uw(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function hw(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function dw(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}lw.at=-1;class pw{constructor(e,t){this.comparator=e,this.root=t||gw.EMPTY}insert(e,t){return new pw(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,gw.BLACK,null,null))}remove(e){return new pw(this.comparator,this.root.remove(e,this.comparator).copy(null,null,gw.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.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(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new fw(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new fw(this.root,e,this.comparator,!1)}getReverseIterator(){return new fw(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new fw(this.root,e,this.comparator,!0)}}class fw{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(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(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class gw{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:gw.RED,this.left=null!=r?r:gw.EMPTY,this.right=null!=i?i:gw.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new gw(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return gw.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return gw.EMPTY;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.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,gw.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,gw.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 g_();if(this.right.isRed())throw g_();var e=this.left.check();if(e!==this.right.check())throw g_();return e+(this.isRed()?0:1)}}gw.EMPTY=null,gw.RED=!0,gw.BLACK=!1,gw.EMPTY=new class{constructor(){this.size=0}get key(){throw g_()}get value(){throw g_()}get color(){throw g_()}get left(){throw g_()}get right(){throw g_()}copy(e,t,n,r,i){return this}insert(e,t,n){return new gw(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 mw{constructor(e){this.comparator=e,this.data=new pw(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(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new vw(this.data.getIterator())}getIteratorFrom(e){return new vw(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 mw))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new mw(this.comparator);return t.data=e,t}}class vw{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function yw(e){return e.hasNext()?e.getNext():void 0}class _w{constructor(e){(this.fields=e).sort(F_.comparator)}static empty(){return new _w([])}unionWith(e){let t=new mw(F_.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new _w(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return R_(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class ww{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new ww(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new ww(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(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return N_(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ww.EMPTY_BYTE_STRING=new ww("");const bw=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Iw(t){if(m_(!!t),"string"!=typeof t)return{seconds:Tw(t.seconds),nanos:Tw(t.nanos)};{let e=0;var n=bw.exec(t);m_(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Tw(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ew(e){return"string"==typeof e?ww.fromBase64String(e):ww.fromUint8Array(e)}function kw(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Cw(e){var t=Iw(e.mapValue.fields.__local_write_time__.timestampValue);return new D_(t.seconds,t.nanos)}class Sw{constructor(e,t,n,r,i,s,a,o){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.useFetchStreams=o}}class Aw{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Aw("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Aw&&e.projectId===this.projectId&&e.database===this.database}}function Nw(e){return null==e}function Rw(e){return 0===e&&1/e==-1/0}function xw(e){return"number"==typeof e&&Number.isInteger(e)&&!Rw(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}const Dw={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Pw={nullValue:"NULL_VALUE"};function Ow(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?kw(e)?4:Gw(e)?9007199254740991:10:g_()}function Mw(r,i){if(r===i)return!0;var e,t,n=Ow(r);if(n!==Ow(i))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return Cw(r).isEqual(Cw(i));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=Iw(r.timestampValue),n=Iw(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,Ew(r.bytesValue).isEqual(Ew(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,Tw((t=r).geoPointValue.latitude)===Tw(e.geoPointValue.latitude)&&Tw(t.geoPointValue.longitude)===Tw(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Tw(e.integerValue)===Tw(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Tw(e.doubleValue),r=Tw(t.doubleValue);return n===r?Rw(n)===Rw(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return R_(r.arrayValue.values||[],i.arrayValue.values||[],Mw);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(uw(t)!==uw(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!Mw(t[e],n[e])))return!1;return!0}(r);default:return g_()}}function Lw(e,t){return void 0!==(e.values||[]).find(e=>Mw(e,t))}function Fw(e,t){if(e===t)return 0;var n,r,i,s,a=Ow(e),o=Ow(t);if(a!==o)return N_(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return N_(e.booleanValue,t.booleanValue);case 2:return r=t,i=Tw(e.integerValue||e.doubleValue),s=Tw(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Uw(e.timestampValue,t.timestampValue);case 4:return Uw(Cw(e),Cw(t));case 5:return N_(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ew(e),r=Ew(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=N_(n[i],r[i]);if(0!==t)return t}return N_(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=N_(Tw(n.latitude),Tw(r.latitude)))?s:N_(Tw(n.longitude),Tw(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Fw(n[i],r[i]);if(t)return t}return N_(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Dw.mapValue&&t===Dw.mapValue)return 0;if(e===Dw.mapValue)return 1;if(t===Dw.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=N_(r[o],s[o]);if(0!==t)return t;var a=Fw(n[r[o]],i[s[o]]);if(0!==a)return a}return N_(r.length,s.length)}(e.mapValue,t.mapValue);default:throw g_()}}function Uw(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return N_(e,t);var n=Iw(e),r=Iw(t),i=N_(n.seconds,r.seconds);return 0!==i?i:N_(n.nanos,r.nanos)}function qw(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?function(e){const t=Iw(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?Ew(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,U_.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):g_();var t}(e)}function Vw(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Bw(e){return e&&"integerValue"in e}function jw(e){return!!e&&"arrayValue"in e}function Kw(e){return e&&"nullValue"in e}function $w(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function zw(e){return e&&"mapValue"in e}function Ww(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){const n={mapValue:{fields:{}}};return hw(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Ww(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Ww(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Gw(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Hw(e,t){var n=Fw(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Qw(e,t){var n=Fw(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Yw{constructor(e){this.value=e}static empty(){return new Yw({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!zw(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ww(t)}setAll(e){let n=F_.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Ww(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());zw(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Mw(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];zw(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){hw(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Yw(Ww(this.value))}}class Jw{constructor(e,t,n,r,i,s){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=i,this.documentState=s}static newInvalidDocument(e){return new Jw(e,0,P_.min(),P_.min(),Yw.empty(),0)}static newFoundDocument(e,t,n){return new Jw(e,1,t,P_.min(),n,0)}static newNoDocument(e,t){return new Jw(e,2,t,P_.min(),Yw.empty(),0)}static newUnknownDocument(e,t){return new Jw(e,3,t,P_.min(),Yw.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Yw.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Yw.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 Jw&&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 Jw(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Xw{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ht=null}}function Zw(e,t=null,n=[],r=[],i=null,s=null,a=null){return new Xw(e,t,n,r,i,s,a)}function eb(e){const t=e;if(null===t.ht){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>{return(t=e).field.canonicalString()+t.op.toString()+qw(t.value);var t}).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),Nw(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>qw(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>qw(e)).join(",")),t.ht=e}return t.ht}function tb(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let a=0;a<e.orderBy.length;a++)if(n=e.orderBy[a],r=t.orderBy[a],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,i,s;if(e.filters.length!==t.filters.length)return!1;for(let o=0;o<e.filters.length;o++)if(i=e.filters[o],s=t.filters[o],i.op!==s.op||!i.field.isEqual(s.field)||!Mw(i.value,s.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!yb(e.startAt,t.startAt)&&yb(e.endAt,t.endAt)}function nb(e){return U_.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function rb(e,t){return e.filters.filter(e=>e instanceof ab&&e.field.isEqual(t))}function ib(t,n,r){let i=Pw,s=!0;for(const r of rb(t,n)){let e=Pw,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Pw:"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?Vw(Aw.empty(),U_.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:g_();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Pw}Hw({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Hw({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function sb(t,n,r){let i=Dw,s=!0;for(const r of rb(t,n)){let e=Dw,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.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?Vw(Aw.empty(),U_.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Dw:g_(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Dw}0<Qw({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Qw({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class ab extends class{}{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.lt(e,t,n):new ob(e,t,n):"array-contains"===t?new hb(e,n):"in"===t?new db(e,n):"not-in"===t?new pb(e,n):"array-contains-any"===t?new fb(e,n):new ab(e,t,n)}static lt(e,t,n){return new("in"===t?cb:lb)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.ft(Fw(t,this.value)):null!==t&&Ow(this.value)===Ow(t)&&this.ft(Fw(t,this.value))}ft(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 g_()}}dt(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class ob extends ab{constructor(e,t,n){super(e,t,n),this.key=U_.fromName(n.referenceValue)}matches(e){var t=U_.comparator(e.key,this.key);return this.ft(t)}}class cb extends ab{constructor(e,t){super(e,"in",t),this.keys=ub(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class lb extends ab{constructor(e,t){super(e,"not-in",t),this.keys=ub(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function ub(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>U_.fromName(e.referenceValue))}class hb extends ab{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return jw(t)&&Lw(t.arrayValue,this.value)}}class db extends ab{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Lw(this.value.arrayValue,t)}}class pb extends ab{constructor(e,t){super(e,"not-in",t)}matches(e){if(Lw(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Lw(this.value.arrayValue,t)}}class fb extends ab{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!jw(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Lw(this.value.arrayValue,e))}}class gb{constructor(e,t){this.position=e,this.inclusive=t}}class mb{constructor(e,t="asc"){this.field=e,this.dir=t}}function vb(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?U_.comparator(U_.fromName(a.referenceValue),n.key):Fw(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function yb(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 n=0;n<e.position.length;n++)if(!Mw(e.position[n],t.position[n]))return!1;return!0}class _b{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this._t=null,this.wt=null,this.startAt,this.endAt}}function wb(e,t,n,r,i,s,a,o){return new _b(e,t,n,r,i,s,a,o)}function bb(e){return new _b(e)}function Ib(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 Tb(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Eb(e){for(const t of e.filters)if(t.dt())return t.field;return null}function kb(e){return null!==e.collectionGroup}function Cb(t){const n=t;if(null===n._t){n._t=[];const t=Eb(n),e=Tb(n);if(null!==t&&null===e)t.isKeyField()||n._t.push(new mb(t)),n._t.push(new mb(F_.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n._t.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n._t.push(new mb(F_.keyField(),t))}}}return n._t}function Sb(e){const t=e;if(!t.wt)if("F"===t.limitType)t.wt=Zw(t.path,t.collectionGroup,Cb(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of Cb(t)){const t="desc"===i.dir?"asc":"desc";e.push(new mb(i.field,t))}var n=t.endAt?new gb(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new gb(t.startAt.position,t.startAt.inclusive):null;t.wt=Zw(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.wt}function Ab(e,t,n){return new _b(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Nb(e,t){return tb(Sb(e),Sb(t))&&e.limitType===t.limitType}function Rb(e){return`${eb(Sb(e))}|lt:${e.limitType}`}function xb(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>{return`${(t=e).field.canonicalString()} ${t.op} ${qw(t.value)}`;var t}).join(", ")}]`),Nw(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>qw(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>qw(e)).join(",")),`Target(${t})`}(Sb(e))}; limitType=${e.limitType})`}function Db(n,e){return e.isFoundDocument()&&(i=n,a=(s=e).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):U_.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(i=e,(!(e=n).startAt||(t=e.startAt,r=vb(t,Cb(e),i),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=vb(t,Cb(e),i),t.inclusive?0<=r:0<r)));var t,r,i,s,a}function Pb(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ob(i){return(e,t)=>{let n=!1;for(const r of Cb(i)){const i=function(e,i,t){var n=e.field.isKeyField()?U_.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?Fw(n,r):g_()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return g_()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}function Mb(e,t){if(e.gt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Rw(t)?"-0":t}}function Lb(e){return{integerValue:""+e}}function Fb(e,t){return xw(t)?Lb(t):Mb(e,t)}class Ub{constructor(){this._=void 0}}function qb(e,t){return e instanceof zb?Bw(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class Vb extends Ub{}class Bb extends Ub{constructor(e){super(),this.elements=e}}function jb(e,t){const n=Gb(t);for(const t of e.elements)n.some(e=>Mw(e,t))||n.push(t);return{arrayValue:{values:n}}}class Kb extends Ub{constructor(e){super(),this.elements=e}}function $b(e,t){let n=Gb(t);for(const t of e.elements)n=n.filter(e=>!Mw(e,t));return{arrayValue:{values:n}}}class zb extends Ub{constructor(e,t){super(),this.It=e,this.yt=t}}function Wb(e){return Tw(e.integerValue||e.doubleValue)}function Gb(e){return jw(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Hb{constructor(e,t){this.field=e,this.transform=t}}class Qb{constructor(e,t){this.version=e,this.transformResults=t}}class Yb{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Yb}static exists(e){return new Yb(void 0,e)}static updateTime(e){return new Yb(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 Jb(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Xb{}function Zb(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new cI(e.key,Yb.none()):new rI(e.key,e.data,Yb.none());{const i=e.data,s=Yw.empty();let t=new mw(F_.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new iI(e.key,s,new _w(t.toArray()),Yb.none())}}function eI(e,t,n){e instanceof rI?function(e,t,n){const r=e.value.clone(),i=aI(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof iI?function(e,t,n){if(!Jb(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=aI(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(sI(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function tI(e,t,n,r){return e instanceof rI?function(e,t,n,r){if(!Jb(e.precondition,t))return n;const i=e.value.clone(),s=oI(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof iI?function(e,t,n,r){if(!Jb(e.precondition,t))return n;const i=oI(e.fieldTransforms,r,t),s=t.data;return s.setAll(sI(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,Jb(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function nI(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&R_(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof Bb&&t instanceof Bb||e instanceof Kb&&t instanceof Kb?R_(e.elements,t.elements,Mw):e instanceof zb&&t instanceof zb?Mw(e.yt,t.yt):e instanceof Vb&&t instanceof Vb)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class rI extends Xb{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class iI extends Xb{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function sI(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function aI(e,t,n){const r=new Map;m_(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,c=a,l=n[u],o instanceof Bb?jb(o,c):o instanceof Kb?$b(o,c):l))}var o,c,l;return r}function oI(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,a=t,c=o=void 0,i instanceof Vb?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:a.seconds,nanos:a.nanoseconds}}}};return s&&(e.fields.__previous_value__=s),{mapValue:e}}():i instanceof Bb?jb(i,s):i instanceof Kb?$b(i,s):(o=qb(i=i,s),c=Wb(o)+Wb(i.yt),Bw(o)&&Bw(i.yt)?Lb(c):Mb(i.It,c))))}var i,s,a,o,c;return r}class cI extends Xb{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class lI extends Xb{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class uI{constructor(e){this.count=e}}function hI(e){switch(e){default:return g_(),0;case v_.CANCELLED:case v_.UNKNOWN:case v_.DEADLINE_EXCEEDED:case v_.RESOURCE_EXHAUSTED:case v_.INTERNAL:case v_.UNAVAILABLE:case v_.UNAUTHENTICATED:return;case v_.INVALID_ARGUMENT:case v_.NOT_FOUND:case v_.ALREADY_EXISTS:case v_.PERMISSION_DENIED:case v_.FAILED_PRECONDITION:case v_.ABORTED:case v_.OUT_OF_RANGE:case v_.UNIMPLEMENTED:case v_.DATA_LOSS:return 1}}function dI(e){if(void 0===e)return d_("GRPC error has no .code"),v_.UNKNOWN;switch(e){case Yy.OK:return v_.OK;case Yy.CANCELLED:return v_.CANCELLED;case Yy.UNKNOWN:return v_.UNKNOWN;case Yy.DEADLINE_EXCEEDED:return v_.DEADLINE_EXCEEDED;case Yy.RESOURCE_EXHAUSTED:return v_.RESOURCE_EXHAUSTED;case Yy.INTERNAL:return v_.INTERNAL;case Yy.UNAVAILABLE:return v_.UNAVAILABLE;case Yy.UNAUTHENTICATED:return v_.UNAUTHENTICATED;case Yy.INVALID_ARGUMENT:return v_.INVALID_ARGUMENT;case Yy.NOT_FOUND:return v_.NOT_FOUND;case Yy.ALREADY_EXISTS:return v_.ALREADY_EXISTS;case Yy.PERMISSION_DENIED:return v_.PERMISSION_DENIED;case Yy.FAILED_PRECONDITION:return v_.FAILED_PRECONDITION;case Yy.ABORTED:return v_.ABORTED;case Yy.OUT_OF_RANGE:return v_.OUT_OF_RANGE;case Yy.UNIMPLEMENTED:return v_.UNIMPLEMENTED;case Yy.DATA_LOSS:return v_.DATA_LOSS;default:return g_()}}(It=Yy=Yy||{})[It.OK=0]="OK",It[It.CANCELLED=1]="CANCELLED",It[It.UNKNOWN=2]="UNKNOWN",It[It.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",It[It.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",It[It.NOT_FOUND=5]="NOT_FOUND",It[It.ALREADY_EXISTS=6]="ALREADY_EXISTS",It[It.PERMISSION_DENIED=7]="PERMISSION_DENIED",It[It.UNAUTHENTICATED=16]="UNAUTHENTICATED",It[It.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",It[It.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",It[It.ABORTED=10]="ABORTED",It[It.OUT_OF_RANGE=11]="OUT_OF_RANGE",It[It.UNIMPLEMENTED=12]="UNIMPLEMENTED",It[It.INTERNAL=13]="INTERNAL",It[It.UNAVAILABLE=14]="UNAVAILABLE",It[It.DATA_LOSS=15]="DATA_LOSS";class pI{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){hw(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return dw(this.inner)}size(){return this.innerSize}}const fI=new pw(U_.comparator);const gI=new pw(U_.comparator);function mI(...e){let t=gI;for(const n of e)t=t.insert(n.key,n);return t}function vI(e){let n=gI;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function yI(){return new pI(e=>e.toString(),(e,t)=>e.isEqual(t))}const _I=new pw(U_.comparator),wI=new mw(U_.comparator);function bI(...e){let t=wI;for(const n of e)t=t.add(n);return t}const II=new mw(N_);class TI{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,EI.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new TI(P_.min(),r,II,fI,bI())}}class EI{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new EI(n,t,bI(),bI(),bI())}}class kI{constructor(e,t,n,r){this.Tt=e,this.removedTargetIds=t,this.key=n,this.Et=r}}class CI{constructor(e,t){this.targetId=e,this.At=t}}class SI{constructor(e,t,n=ww.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class AI{constructor(){this.Rt=0,this.bt=xI(),this.Pt=ww.EMPTY_BYTE_STRING,this.vt=!1,this.Vt=!0}get current(){return this.vt}get resumeToken(){return this.Pt}get St(){return 0!==this.Rt}get Dt(){return this.Vt}Ct(e){0<e.approximateByteSize()&&(this.Vt=!0,this.Pt=e)}xt(){let n=bI(),r=bI(),i=bI();return this.bt.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:g_()}}),new EI(this.Pt,this.vt,n,r,i)}Nt(){this.Vt=!1,this.bt=xI()}kt(e,t){this.Vt=!0,this.bt=this.bt.insert(e,t)}Ot(e){this.Vt=!0,this.bt=this.bt.remove(e)}Mt(){this.Rt+=1}Ft(){--this.Rt}$t(){this.Vt=!0,this.vt=!0}}class NI{constructor(e){this.Bt=e,this.Lt=new Map,this.Ut=fI,this.qt=RI(),this.Kt=new mw(N_)}Gt(e){for(const t of e.Tt)e.Et&&e.Et.isFoundDocument()?this.Qt(t,e.Et):this.jt(t,e.key,e.Et);for(const n of e.removedTargetIds)this.jt(n,e.key,e.Et)}Wt(n){this.forEachTarget(n,e=>{const t=this.zt(e);switch(n.state){case 0:this.Ht(e)&&t.Ct(n.resumeToken);break;case 1:t.Ft(),t.St||t.Nt(),t.Ct(n.resumeToken);break;case 2:t.Ft(),t.St||this.removeTarget(e);break;case 3:this.Ht(e)&&(t.$t(),t.Ct(n.resumeToken));break;case 4:this.Ht(e)&&(this.Jt(e),t.Ct(n.resumeToken));break;default:g_()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Lt.forEach((e,t)=>{this.Ht(t)&&n(t)})}Yt(e){const t=e.targetId,n=e.At.count,r=this.Xt(t);if(r){const e=r.target;if(nb(e))if(0===n){const n=new U_(e.path);this.jt(t,n,Jw.newNoDocument(n,P_.min()))}else m_(1===n);else this.Zt(t)!==n&&(this.Jt(t),this.Kt=this.Kt.add(t))}}te(r){const i=new Map;this.Lt.forEach((e,t)=>{var n=this.Xt(t);if(n){if(e.current&&nb(n.target)){const i=new U_(n.target.path);null!==this.Ut.get(i)||this.ee(t,i)||this.jt(t,i,Jw.newNoDocument(i,r))}e.Dt&&(i.set(t,e.xt()),e.Nt())}});let s=bI();this.qt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Xt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.Ut.forEach((e,t)=>t.setReadTime(r));var e=new TI(r,i,this.Kt,this.Ut,s);return this.Ut=fI,this.qt=RI(),this.Kt=new mw(N_),e}Qt(e,t){var n;this.Ht(e)&&(n=this.ee(e,t.key)?2:0,this.zt(e).kt(t.key,n),this.Ut=this.Ut.insert(t.key,t),this.qt=this.qt.insert(t.key,this.ne(t.key).add(e)))}jt(e,t,n){if(this.Ht(e)){const r=this.zt(e);this.ee(e,t)?r.kt(t,1):r.Ot(t),this.qt=this.qt.insert(t,this.ne(t).delete(e)),n&&(this.Ut=this.Ut.insert(t,n))}}removeTarget(e){this.Lt.delete(e)}Zt(e){var t=this.zt(e).xt();return this.Bt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Mt(e){this.zt(e).Mt()}zt(e){let t=this.Lt.get(e);return t||(t=new AI,this.Lt.set(e,t)),t}ne(e){let t=this.qt.get(e);return t||(t=new mw(N_),this.qt=this.qt.insert(e,t)),t}Ht(e){var t=null!==this.Xt(e);return t||h_("WatchChangeAggregator","Detected inactive target",e),t}Xt(e){var t=this.Lt.get(e);return t&&t.St?null:this.Bt.se(e)}Jt(t){this.Lt.set(t,new AI),this.Bt.getRemoteKeysForTarget(t).forEach(e=>{this.jt(t,e,null)})}ee(e,t){return this.Bt.getRemoteKeysForTarget(e).has(t)}}function RI(){return new pw(U_.comparator)}function xI(){return new pw(U_.comparator)}const DI={asc:"ASCENDING",desc:"DESCENDING"},PI={"<":"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"};class OI{constructor(e,t){this.databaseId=e,this.gt=t}}function MI(e,t){return e.gt?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function LI(e,t){return e.gt?t.toBase64():t.toUint8Array()}function FI(e){return m_(!!e),P_.fromTimestamp((t=Iw(e),new D_(t.seconds,t.nanos)));var t}function UI(e,t){return e=e,new M_(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function qI(e){var t=M_.fromString(e);return m_(rT(t)),t}function VI(e,t){return UI(e.databaseId,t.path)}function BI(e,t){const n=qI(t);if(n.get(1)!==e.databaseId.projectId)throw new y_(v_.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new y_(v_.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new U_(zI(n))}function jI(e,t){return UI(e.databaseId,t)}function KI(e){var t=qI(e);return 4===t.length?M_.emptyPath():zI(t)}function $I(e){return new M_(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function zI(e){return m_(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function WI(e,t,n){return{name:VI(e,t),fields:n.value.mapValue.fields}}function GI(e,t,n){const r=BI(e,t.name),i=FI(t.updateTime),s=new Yw({mapValue:{fields:t.fields}}),a=Jw.newFoundDocument(r,i,s);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function HI(e,t){let n;if(t instanceof rI)n={update:WI(e,t.key,t.value)};else if(t instanceof cI)n={delete:VI(e,t.key)};else if(t instanceof iI)n={update:WI(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof lI))return g_();n={verify:VI(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof Vb)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof Bb)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Kb)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof zb)return{fieldPath:e.field.canonicalString(),increment:t.yt};throw g_()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,MI(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:g_()),n;var r}function QI(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?Yb.updateTime(FI(i.updateTime)):void 0!==i.exists?Yb.exists(i.exists):Yb.none():Yb.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)m_("REQUEST_TIME"===t.setToServerValue),n=new Vb;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new Bb(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new Kb(e)}else"increment"in t?n=new zb(e,t.increment):g_();var r=F_.fromServerFormat(t.fieldPath);return new Hb(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=BI(t,n.update.name),a=new Yw({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new _w(e.map(e=>F_.fromServerFormat(e)))}();return new iI(s,a,t,e,r)}return new rI(s,a,e,r)}if(n.delete){const r=BI(t,n.delete);return new cI(r,e)}if(n.verify){const r=BI(t,n.verify);return new lI(r,e)}return g_()}function YI(e,t){return{documents:[jI(e,t.path)]}}function JI(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=jI(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=jI(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if($w(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NAN"}};if(Kw(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NULL"}}}else if("!="===e.op){if($w(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NOT_NAN"}};if(Kw(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ZI(e.field),op:(t=e.op,PI[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:ZI(e.field),direction:(e=e.dir,DI[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.gt||Nw(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(i=t.startAt).inclusive,values:i.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function XI(e){let t=KI(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){m_(1===r);const f=n.from[0];f.allDescendants?i=f.collectionId:t=t.child(f.collectionId)}let s=[];n.where&&(s=function t(e){return e?void 0!==e.unaryFilter?[nT(e)]:void 0!==e.fieldFilter?[tT(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):g_():[]}(n.where));let a=[];n.orderBy&&(a=n.orderBy.map(e=>function(e){return new mb(eT(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var c,l,u,h;n.limit&&(o=(e=n.limit,Nw(c="object"==typeof e?e.value:e)?null:c));let d=null;n.startAt&&(d=(l=n.startAt,h=!!l.before,u=l.values||[],new gb(u,h)));let p=null;return n.endAt&&(p=(l=n.endAt,u=!l.before,h=l.values||[],new gb(h,u))),wb(t,i,a,s,o,"F",d,p)}function ZI(e){return{fieldPath:e.canonicalString()}}function eT(e){return F_.fromServerFormat(e.fieldPath)}function tT(e){return ab.create(eT(e.fieldFilter.field),function(){switch(e.fieldFilter.op){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 g_()}}(),e.fieldFilter.value)}function nT(e){switch(e.unaryFilter.op){case"IS_NAN":var t=eT(e.unaryFilter.field);return ab.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=eT(e.unaryFilter.field);return ab.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=eT(e.unaryFilter.field);return ab.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=eT(e.unaryFilter.field);return ab.create(n,"!=",{nullValue:"NULL_VALUE"});default:return g_()}}function rT(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function iT(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=sT(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return sT(t)}function sT(e){return e+""}function aT(t){const n=t.length;if(m_(2<=n),2===n)return m_(""===t.charAt(0)&&""===t.charAt(1)),M_.emptyPath();const r=n-2,i=[];let s="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>r)&&g_(),t.charAt(n+1)){case"":const r=t.substring(a,n);let e;0===s.length?e=r:(s+=r,e=s,s=""),i.push(e);break;case"":s+=t.substring(a,n),s+="\0";break;case"":s+=t.substring(a,n+1);break;default:g_()}a=n+2}return new M_(i)}const oT=["userId","batchId"];function cT(e,t){return[e,iT(t)]}function lT(e,t,n){return[e,iT(t),n]}const uT={},hT=["prefixPath","collectionGroup","readTime","documentId"],dT=["prefixPath","collectionGroup","documentId"],pT=["collectionGroup","readTime","prefixPath","documentId"],fT=["canonicalId","targetId"],gT=["targetId","path"],mT=["path","targetId"],vT=["collectionId","parent"],yT=["indexId","uid"],_T=["uid","sequenceNumber"],wT=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],bT=["indexId","uid","orderedDocumentKey"],IT=["userId","collectionPath","documentId"],TT=["userId","collectionPath","largestBatchId"],ET=["userId","collectionGroup","largestBatchId"],kT=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],CT=[...kT,"documentOverlays"],ST=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],AT=ST,NT=[...AT,"indexConfiguration","indexState","indexEntries"];class RT extends Q_{constructor(e,t){super(),this.ie=e,this.currentSequenceNumber=t}}function xT(e,t){var n=e;return Z_.M(n.ie,t)}class DT{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&eI(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=tI(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=tI(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=yI();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=Zb(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(P_.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),bI())}isEqual(e){return this.batchId===e.batchId&&R_(this.mutations,e.mutations,(e,t)=>nI(e,t))&&R_(this.baseMutations,e.baseMutations,(e,t)=>nI(e,t))}}class PT{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){m_(e.mutations.length===n.length);let r=_I;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new PT(e,t,n,r)}}class OT{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{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class MT{constructor(e,t,n,r,i=P_.min(),s=P_.min(),a=ww.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a}withSequenceNumber(e){return new MT(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new MT(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new MT(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class LT{constructor(e){this.re=e}}function FT(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:UT(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:VI(i=e.re,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:MI(i,e.version.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:qT(t.version)};else{if(!t.isUnknownDocument())return g_();r.unknownDocument={path:n.path.toArray(),version:qT(t.version)}}var i;return r}function UT(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function qT(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function VT(e){var t=new D_(e.seconds,e.nanoseconds);return P_.fromTimestamp(t)}function BT(t,e){const n=(e.baseMutations||[]).map(e=>QI(t.re,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>QI(t.re,e)),i=D_.fromMillis(e.localWriteTimeMs);return new DT(e.batchId,i,n,r)}function jT(e){var t,n=VT(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?VT(e.lastLimboFreeSnapshotVersion):P_.min();let i;return i=void 0!==e.query.documents?(m_(1===(t=e.query).documents.length),Sb(bb(KI(t.documents[0])))):Sb(XI(e.query)),new MT(i,e.targetId,0,e.lastListenSequenceNumber,n,r,ww.fromBase64String(e.resumeToken))}function KT(e,t){var n=qT(t.snapshotVersion),r=qT(t.lastLimboFreeSnapshotVersion),i=(nb(t.target)?YI:JI)(e.re,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:eb(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function $T(e){var t=XI({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Ab(t,t.limit,"L"):t}function zT(e,t){return new OT(t.largestBatchId,QI(e.re,t.overlayMutation))}function WT(e,t){var n=t.path.lastSegment();return[e,iT(t.path.popLast()),n]}function GT(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:qT(r.readTime),documentKey:iT(r.documentKey.path),largestBatchId:r.largestBatchId}}class HT{getBundleMetadata(e,t){return QT(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:VT(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return QT(e).put({bundleId:(n=t).id,createTime:qT(FI(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return YT(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:$T(t.bundledQuery),readTime:VT(t.readTime)};var t})}saveNamedQuery(e,t){return YT(e).put({name:(t=t).name,readTime:qT(FI(t.readTime)),bundledQuery:t.bundledQuery})}}function QT(e){return xT(e,"bundles")}function YT(e){return xT(e,"namedQueries")}class JT{constructor(e,t){this.It=e,this.userId=t}static oe(e,t){var n=t.uid||"";return new JT(e,n)}getOverlay(e,t){return XT(e).get(WT(this.userId,t)).next(e=>e?zT(this.It,e):null)}getOverlays(e,t){const n=yI();return J_.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new OT(i,t);s.push(this.ue(r,n))}),J_.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(iT(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(XT(n).Y("collectionPathOverlayIndex",t))}),J_.waitFor(i)}getOverlaysForCollection(e,t,n){const r=yI(),i=iT(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return XT(e).W("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=zT(this.It,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=yI();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return XT(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=zT(this.It,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}ue(e,t){return XT(e).put(function(e,t,n){var[,r,i]=WT(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:HI(e.re,n.mutation)}}(this.It,this.userId,t))}}function XT(e){return xT(e,"documentOverlays")}class ZT{constructor(){}ce(e,t){this.ae(e,t),t.he()}ae(e,t){var n,r;"nullValue"in e?this.le(t,5):"booleanValue"in e?(this.le(t,10),t.fe(e.booleanValue?1:0)):"integerValue"in e?(this.le(t,15),t.fe(Tw(e.integerValue))):"doubleValue"in e?(n=Tw(e.doubleValue),isNaN(n)?this.le(t,13):(this.le(t,15),Rw(n)?t.fe(0):t.fe(n))):"timestampValue"in e?(r=e.timestampValue,this.le(t,20),"string"==typeof r?t.de(r):(t.de(`${r.seconds||""}`),t.fe(r.nanos||0))):"stringValue"in e?(this._e(e.stringValue,t),this.we(t)):"bytesValue"in e?(this.le(t,30),t.me(Ew(e.bytesValue)),this.we(t)):"referenceValue"in e?this.ge(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.le(t,45),t.fe(r.latitude||0),t.fe(r.longitude||0)):"mapValue"in e?Gw(e)?this.le(t,Number.MAX_SAFE_INTEGER):(this.ye(e.mapValue,t),this.we(t)):"arrayValue"in e?(this.pe(e.arrayValue,t),this.we(t)):g_()}_e(e,t){this.le(t,25),this.Ie(e,t)}Ie(e,t){t.de(e)}ye(e,t){var n=e.fields||{};this.le(t,55);for(const e of Object.keys(n))this._e(e,t),this.ae(n[e],t)}pe(e,t){var n=e.values||[];this.le(t,50);for(const e of n)this.ae(e,t)}ge(e,t){this.le(t,37),U_.fromName(e).path.forEach(e=>{this.le(t,60),this.Ie(e,t)})}le(e,t){e.fe(t)}we(e){e.fe(2)}}function e0(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}ZT.Te=new ZT;class t0{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ee(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ae(n.value),n=t.next();this.Re()}be(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Pe(n.value),n=t.next();this.ve()}Ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ae(e);else if(e<2048)this.Ae(960|e>>>6),this.Ae(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ae(480|e>>>12),this.Ae(128|63&e>>>6),this.Ae(128|63&e);else{const e=t.codePointAt(0);this.Ae(240|e>>>18),this.Ae(128|63&e>>>12),this.Ae(128|63&e>>>6),this.Ae(128|63&e)}}this.Re()}Se(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Pe(e);else if(e<2048)this.Pe(960|e>>>6),this.Pe(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Pe(480|e>>>12),this.Pe(128|63&e>>>6),this.Pe(128|63&e);else{const e=t.codePointAt(0);this.Pe(240|e>>>18),this.Pe(128|63&e>>>12),this.Pe(128|63&e>>>6),this.Pe(128|63&e)}}this.ve()}De(e){var t=this.Ce(e),n=e0(t);this.xe(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Ne(e){var t=this.Ce(e),n=e0(t);this.xe(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}ke(){this.Oe(255),this.Oe(255)}Me(){this.Fe(255),this.Fe(255)}reset(){this.position=0}seed(e){this.xe(e.length),this.buffer.set(e,this.position),this.position+=e.length}$e(){return this.buffer.slice(0,this.position)}Ce(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ae(e){var t=255&e;0==t?(this.Oe(0),this.Oe(255)):255==t?(this.Oe(255),this.Oe(0)):this.Oe(t)}Pe(e){var t=255&e;0==t?(this.Fe(0),this.Fe(255)):255==t?(this.Fe(255),this.Fe(0)):this.Fe(e)}Re(){this.Oe(0),this.Oe(1)}ve(){this.Fe(0),this.Fe(1)}Oe(e){this.xe(1),this.buffer[this.position++]=e}Fe(e){this.xe(1),this.buffer[this.position++]=~e}xe(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class n0{constructor(e){this.Be=e}me(e){this.Be.Ee(e)}de(e){this.Be.Ve(e)}fe(e){this.Be.De(e)}he(){this.Be.ke()}}class r0{constructor(e){this.Be=e}me(e){this.Be.be(e)}de(e){this.Be.Se(e)}fe(e){this.Be.Ne(e)}he(){this.Be.Me()}}class i0{constructor(){this.Be=new t0,this.Le=new n0(this.Be),this.Ue=new r0(this.Be)}seed(e){this.Be.seed(e)}qe(e){return 0===e?this.Le:this.Ue}$e(){return this.Be.$e()}reset(){this.Be.reset()}}class s0{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Ke(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new s0(this.indexId,this.documentKey,this.arrayValue,n)}}function a0(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=o0(e.arrayValue,t.arrayValue),0!==n?n:(n=o0(e.directionalValue,t.directionalValue),0!==n?n:U_.comparator(e.documentKey,t.documentKey)))}function o0(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class c0{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ge=e.orderBy,this.Qe=[];for(const t of e.filters){const e=t;e.dt()?this.je=e:this.Qe.push(e)}}We(e){var t=V_(e);if(void 0!==t&&!this.ze(t))return!1;var n=B_(e);let r=0,i=0;for(;r<n.length&&this.ze(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.je){const e=n[r];if(!this.He(this.je,e)||!this.Je(this.Ge[i++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(i>=this.Ge.length||!this.Je(this.Ge[i++],e))return!1}return!0}ze(e){for(const t of this.Qe)if(this.He(t,e))return!0;return!1}He(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}Je(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}class l0{constructor(){this.Ye=new u0}addToCollectionParentIndex(e,t){return this.Ye.add(t),J_.resolve()}getCollectionParents(e,t){return J_.resolve(this.Ye.getEntries(t))}addFieldIndex(e,t){return J_.resolve()}deleteFieldIndex(e,t){return J_.resolve()}getDocumentsMatchingTarget(e,t){return J_.resolve(null)}getIndexType(e,t){return J_.resolve(0)}getFieldIndexes(e,t){return J_.resolve([])}getNextCollectionGroupToUpdate(e){return J_.resolve(null)}getMinOffset(e,t){return J_.resolve(W_.min())}getMinOffsetFromCollectionGroup(e,t){return J_.resolve(W_.min())}updateCollectionGroup(e,t,n){return J_.resolve()}updateIndexEntries(e,t){return J_.resolve()}}class u0{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new mw(M_.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new mw(M_.comparator)).toArray()}}const h0=new Uint8Array(0);class d0{constructor(e,t){this.user=e,this.databaseId=t,this.Xe=new u0,this.Ze=new pI(e=>eb(e),(e,t)=>tb(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Xe.has(t))return J_.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Xe.add(t)});r={collectionId:n,parent:iT(r)};return p0(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[x_(n),""],!1,!0);return p0(e).W(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(aT(t.parent))}return r})}addFieldIndex(e,t){const n=g0(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=m0(e);return i.next(e=>{n.put(GT(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=g0(e),r=m0(e),i=f0(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,l){const u=f0(e);let h=!0;const n=new Map;return J_.forEach(this.tn(l),t=>this.en(e,t).next(e=>{h=h&&!!e,n.set(t,e)})).next(()=>{if(h){let c=bI();const h=[];return J_.forEach(n,(e,t)=>{h_("IndexedDbIndexManager",`Using index ${o=e,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${eb(l)}`);var n=function(e,t){var n=V_(t);if(void 0===n)return null;for(const t of rb(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of B_(t))for(const t of rb(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),i=function(e,t){const n=[];let r=!0;for(const i of B_(t)){const t=(0===i.kind?ib:sb)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new gb(n,r)}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of B_(t)){const t=(0===i.kind?sb:ib)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new gb(n,r)}(t,e),a=this.nn(e,t,i),o=this.nn(e,t,s),r=this.sn(e,t,r),r=this.rn(e.indexId,n,a,i.inclusive,o,s.inclusive,r);return J_.forEach(r,e=>u.J(e,l.limit).next(e=>{e.forEach(e=>{var t=U_.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),h.push(t))})}))}).next(()=>h)}return J_.resolve(null)})}tn(e){var t;return(t=this.Ze.get(e))||(this.Ze.set(e,t=[e]),t)}rn(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),c=o/(null!=e?e.length:1),l=[];for(let u=0;u<o;++u){const o=e?this.on(e[u/c]):h0,h=this.un(t,o,n[u%c],r),d=this.cn(t,o,i[u%c],s),p=a.map(e=>this.un(t,o,e,!0));l.push(...this.createRange(h,d,p))}return l}un(e,t,n,r){const i=new s0(e,U_.empty(),t,n);return r?i:i.Ke()}cn(e,t,n,r){const i=new s0(e,U_.empty(),t,n);return r?i.Ke():i}en(e,t){const r=new c0(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.We(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;return J_.forEach(this.tn(t),t=>this.en(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new mw(F_.comparator),n=!1;for(const r of e.filters){const e=r;e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field))}for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>n)}an(e,t){const n=new i0;for(const i of B_(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.qe(i.kind);ZT.Te.ce(e,r)}return n.$e()}on(e){const t=new i0;return ZT.Te.ce(e,t.qe(0)),t.$e()}hn(e,t){const n=new i0;return ZT.Te.ce(Vw(this.databaseId,t),n.qe(0===(r=B_(e)).length?0:r[r.length-1].kind)),n.$e();var r}sn(e,t,n){if(null===n)return[];let r=[];r.push(new i0);let i=0;for(const s of B_(e)){const e=n[i++];for(const n of r)if(this.ln(t,s.fieldPath)&&jw(e))r=this.fn(r,s,e);else{const t=n.qe(s.kind);ZT.Te.ce(e,t)}}return this.dn(r)}nn(e,t,n){return this.sn(e,t,n.position)}dn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].$e();return t}fn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new i0;r.seed(n.$e()),ZT.Te.ce(e,r.qe(t.kind)),i.push(r)}return i}ln(e,t){return!!e.filters.find(e=>e instanceof ab&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=g0(e),r=m0(e);return(t?n.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.W()).next(e=>{const s=[];return J_.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new K_(e.sequenceNumber,new W_(VT(e.readTime),new U_(aT(e.documentKey)),e.largestBatchId)):K_.empty(),r=t.fields.map(([e,t])=>new j_(F_.fromServerFormat(e),t)),new q_(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:N_(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=g0(e),s=m0(e);return this._n(e).next(t=>i.W("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>J_.forEach(e,e=>s.put(GT(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return J_.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?J_.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),J_.forEach(e,n=>this.wn(i,t,n).next(e=>{var t=this.mn(r,n);return e.isEqual(t)?J_.resolve():this.gn(i,r,n,e,t)}))))})}yn(e,t,n,r){return f0(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.hn(n,t.key),documentKey:t.key.path.toArray()})}pn(e,t,n,r){return f0(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.hn(n,t.key),t.key.path.toArray()])}wn(e,n,r){const t=f0(e);let i=new mw(a0);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.hn(r,n)])},(e,t)=>{i=i.add(new s0(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}mn(e,t){let n=new mw(a0);var r=this.an(t,e);if(null==r)return n;const i=V_(t);if(null!=i){var s=e.data.field(i.fieldPath);if(jw(s))for(const i of s.arrayValue.values||[])n=n.add(new s0(t.indexId,e.key,this.on(i),r))}else n=n.add(new s0(t.indexId,e.key,h0,r));return n}gn(t,n,r,l,e){h_("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const i=[];return function(e,n,r,i){var s=l.getIterator(),a=e.getIterator();let o=yw(s),c=yw(a);for(;o||c;){let e=!1,t=!1;if(o&&c){const r=n(o,c);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(c),c=yw(a)):t?(i(o),o=yw(s)):(o=yw(s),c=yw(a))}}(e,a0,e=>{i.push(this.yn(t,n,r,e))},e=>{i.push(this.pn(t,n,r,e))}),J_.waitFor(i)}_n(e){let r=1;return m0(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>a0(e,t)).filter((e,t,n)=>!t||0!==a0(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=a0(i,e),s=a0(i,t);if(0===n)r[0]=e.Ke();else if(0<n&&s<0)r.push(i),r.push(i.Ke());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2)i.push(IDBKeyRange.bound([r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,h0,[]],[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,h0,[]]));return i}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(v0)}getMinOffset(t,e){return J_.mapArray(this.tn(e),e=>this.en(t,e).next(e=>e||g_())).next(v0)}}function p0(e){return xT(e,"collectionParents")}function f0(e){return xT(e,"indexEntries")}function g0(e){return xT(e,"indexConfiguration")}function m0(e){return xT(e,"indexState")}function v0(e){m_(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;G_(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new W_(t.readTime,t.documentKey,n)}const y0={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class _0{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new _0(e,_0.DEFAULT_COLLECTION_PERCENTILE,_0.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function w0(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const c=r.Z({range:a},(e,t,n)=>(o++,n.delete()));s.push(c.next(()=>{m_(1===o)}));const l=[];for(const e of n.mutations){const r=lT(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return J_.waitFor(s).next(()=>l)}function b0(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 g_();t=e.noDocument}return JSON.stringify(t).length}_0.DEFAULT_COLLECTION_PERCENTILE=10,_0.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,_0.DEFAULT=new _0(41943040,_0.DEFAULT_COLLECTION_PERCENTILE,_0.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),_0.DISABLED=new _0(-1,0,0);class I0{constructor(e,t,n,r){this.userId=e,this.It=t,this.indexManager=n,this.referenceDelegate=r,this.In={}}static oe(e,t,n,r){m_(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new I0(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return E0(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,p){const f=k0(u),g=E0(u);return g.add({}).next(e=>{m_("number"==typeof e);const t=new DT(e,h,d,p),n=(i=this.It,s=this.userId,a=t,o=a.baseMutations.map(e=>HI(i.re,e)),c=a.mutations.map(e=>HI(i.re,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:c}),r=[];var i,s,a,o,c;let l=new mw((e,t)=>N_(e.canonicalString(),t.canonicalString()));for(const u of p){const h=lT(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(f.put(h,uT))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.In[e]=t.keys()}),J_.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return E0(e).get(t).next(e=>e?(m_(e.userId===this.userId),BT(this.It,e)):null)}Tn(e,n){return this.In[n]?J_.resolve(this.In[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.In[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return E0(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(m_(t.batchId>=r),i=BT(this.It,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return E0(e).Z({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return E0(e).W("userMutationsIndex",t).next(e=>e.map(e=>BT(this.It,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=cT(this.userId,o.path),t=IDBKeyRange.lowerBound(e),c=[];return k0(a).Z({range:t},(e,t,n)=>{var[r,i,s]=e,i=aT(i);if(r===this.userId&&o.path.isEqual(i))return E0(a).get(s).next(e=>{if(!e)throw g_();m_(e.userId===this.userId),c.push(BT(this.It,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new mw(N_);const n=[];return e.forEach(a=>{var e=cT(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=k0(t).Z({range:e},(e,t,n)=>{var[r,i,s]=e,i=aT(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),J_.waitFor(n).next(()=>this.En(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=cT(this.userId,a),r=IDBKeyRange.lowerBound(n);let c=new mw(N_);return k0(e).Z({range:r},(e,t,n)=>{var[r,i,s]=e,i=aT(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(c=c.add(s)):n.done()}).next(()=>this.En(e,c))}En(t,e){const n=[],r=[];return e.forEach(e=>{r.push(E0(t).get(e).next(e=>{if(null===e)throw g_();m_(e.userId===this.userId),n.push(BT(this.It,e))}))}),J_.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return w0(t.ie,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.An(n.batchId)}),J_.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}An(e){delete this.In[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return J_.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return k0(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=aT(e[1]);r.push(t)}else n.done()}).next(()=>{m_(0===r.length)})})}containsKey(e,t){return T0(e,this.userId,t)}Rn(e){return C0(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function T0(e,s,t){const n=cT(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return k0(e).Z({range:r,X:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function E0(e){return xT(e,"mutations")}function k0(e){return xT(e,"documentMutations")}function C0(e){return xT(e,"mutationQueues")}class S0{constructor(e){this.bn=e}next(){return this.bn+=2,this.bn}static Pn(){return new S0(0)}static vn(){return new S0(-1)}}class A0{constructor(e,t){this.referenceDelegate=e,this.It=t}allocateTargetId(n){return this.Vn(n).next(e=>{const t=new S0(e.highestTargetId);return e.highestTargetId=t.next(),this.Sn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Vn(e).next(e=>P_.fromTimestamp(new D_(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Vn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Vn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.Sn(t,e)))}addTargetData(t,n){return this.Dn(t,n).next(()=>this.Vn(t).next(e=>(e.targetCount+=1,this.Cn(n,e),this.Sn(t,e))))}updateTargetData(e,t){return this.Dn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>N0(t).delete(e.targetId)).next(()=>this.Vn(t)).next(e=>(m_(0<e.targetCount),--e.targetCount,this.Sn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return N0(r).Z((e,t)=>{var n=jT(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>J_.waitFor(o)).next(()=>a)}forEachTarget(e,r){return N0(e).Z((e,t)=>{var n=jT(t);r(n)})}Vn(e){return R0(e).get("targetGlobalKey").next(e=>(m_(null!==e),e))}Sn(e,t){return R0(e).put("targetGlobalKey",t)}Dn(e,t){return N0(e).put(KT(this.It,t))}Cn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Vn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=eb(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return N0(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=jT(t);tb(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=x0(n);return e.forEach(e=>{var t=iT(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),J_.waitFor(i)}removeMatchingKeys(n,e,r){const i=x0(n);return J_.forEach(e,e=>{var t=iT(e.path);return J_.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=x0(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=x0(e);let i=bI();return r.Z({range:n,X:!0},(e,t,n)=>{var r=aT(e[1]),r=new U_(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=iT(t.path),n=IDBKeyRange.bound([n],[x_(n)],!1,!0);let r=0;return x0(e).Z({index:"documentTargetsIndex",X:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}se(e,t){return N0(e).get(t).next(e=>e?jT(e):null)}}function N0(e){return xT(e,"targets")}function R0(e){return xT(e,"targetGlobal")}function x0(e){return xT(e,"targetDocuments")}function D0([e,t],[n,r]){var i=N_(e,n);return 0===i?N_(t,r):i}class P0{constructor(e){this.xn=e,this.buffer=new mw(D0),this.Nn=0}kn(){return++this.Nn}On(e){var t=[e,this.kn()];if(this.buffer.size<this.xn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();D0(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class O0{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Mn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Fn(6e4)}stop(){this.Mn&&(this.Mn.cancel(),this.Mn=null)}get started(){return null!==this.Mn}Fn(e){h_("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Mn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Mn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){nw(e)?h_("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Y_(e)}await this.Fn(3e5)})}}class M0{constructor(e,t){this.$n=e,this.params=t}calculateTargetCount(e,t){return this.$n.Bn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return J_.resolve(lw.at);const n=new P0(t);return this.$n.forEachTarget(e,e=>n.On(e.sequenceNumber)).next(()=>this.$n.Ln(e,e=>n.On(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.$n.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.$n.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(h_("LruGarbageCollector","Garbage collection skipped; disabled"),J_.resolve(y0)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(h_("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),y0):this.Un(t,n))}getCacheSize(e){return this.$n.getCacheSize(e)}Un(t,n){let r,i,s,a,o,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(h_("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=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),u_()<=k.DEBUG&&h_("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-u}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(c-o)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),J_.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class L0{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new M0(e,t))}Bn(e){const n=this.qn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}qn(e){let t=0;return this.Ln(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Ln(e,n){return this.Kn(e,(e,t)=>n(t))}addReference(e,t,n){return F0(e,n)}removeReference(e,t,n){return F0(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return F0(e,t)}Gn(t,n){let r=!1;return C0(t).tt(e=>T0(t,e,n).next(e=>(e&&(r=!0),J_.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Kn(n,(t,e)=>{if(e<=r){const r=this.Gn(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,P_.min()),x0(n).delete([0,iT(t.path)])))});s.push(r)}}).next(()=>J_.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return F0(e,t)}Kn(e,r){const t=x0(e);let i,s=lw.at;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==lw.at&&r(new U_(aT(i)),s),s=n,i=t):s=lw.at}).next(()=>{s!==lw.at&&r(new U_(aT(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function F0(e,t){return x0(e).put((e=e.currentSequenceNumber,{targetId:0,path:iT(t.path),sequenceNumber:e}))}class U0{constructor(){this.changes=new pI(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,Jw.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?J_.resolve(n):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 q0{constructor(e){this.It=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return K0(e).put(n)}removeEntry(e,n,t){return K0(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],UT(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Qn(t,e)))}getEntry(e,n){let r=Jw.newInvalidDocument(n);return K0(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only($0(n))},(e,t)=>{r=this.jn(n,t)}).next(()=>r)}Wn(e,n){let r={size:0,document:Jw.newInvalidDocument(n)};return K0(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only($0(n))},(e,t)=>{r={document:this.jn(n,t),size:b0(t)}}).next(()=>r)}getEntries(e,t){let r=fI;return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n)}).next(()=>r)}Hn(e,t){let r=fI,i=new pw(U_.comparator);return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n),i=i.insert(e,b0(t))}).next(()=>({documents:r,Jn:i}))}zn(e,t,i){if(t.isEmpty())return J_.resolve();let n=new mw(W0);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound($0(n.first()),$0(n.last())),s=n.getIterator();let a=s.getNext();return K0(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=U_.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&W0(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.j($0(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),UT(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],i=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return K0(e).W(IDBKeyRange.bound(r,i,!0)).next(e=>{let t=fI;for(const n of e){const e=this.jn(U_.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,i){let s=fI;var r=z0(t,n),a=z0(t,W_.max());return K0(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.jn(U_.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new B0(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return j0(e).get("remoteDocumentGlobalKey").next(e=>(m_(!!e),e))}Qn(e,t){return j0(e).put("remoteDocumentGlobalKey",t)}jn(e,t){if(t){const e=function(e,t){let n;if(t.document)n=GI(e.re,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=U_.fromSegments(t.noDocument.path),i=VT(t.noDocument.readTime);n=Jw.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return g_();{const e=U_.fromSegments(t.unknownDocument.path),s=VT(t.unknownDocument.version);n=Jw.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new D_(t[0],t[1]),P_.fromTimestamp(r))),n;var r}(this.It,t);if(!e.isNoDocument()||!e.version.isEqual(P_.min()))return e}return Jw.newInvalidDocument(e)}}function V0(e){return new q0(e)}class B0 extends U0{constructor(e,t){super(),this.Yn=e,this.trackRemovals=t,this.Xn=new pI(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,c=new mw((e,t)=>N_(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Xn.get(e);if(a.push(this.Yn.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=FT(this.Yn.It,t);c=c.add(e.path.popLast());var i=b0(r);o+=i-n.size,a.push(this.Yn.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=FT(this.Yn.It,t.convertToNoDocument(P_.min()));a.push(this.Yn.addEntry(s,e,o))}}),c.forEach(e=>{a.push(this.Yn.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.Yn.updateMetadata(s,o)),J_.waitFor(a)}getFromCache(e,t){return this.Yn.Wn(e,t).next(e=>(this.Xn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Yn.Hn(e,t).next(({documents:n,Jn:e})=>(e.forEach((e,t)=>{this.Xn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function j0(e){return xT(e,"remoteDocumentGlobal")}function K0(e){return xT(e,"remoteDocumentsV14")}function $0(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function z0(e,t){const n=t.documentKey.path.toArray();return[e,UT(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function W0(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=N_(n[s],r[s]),i)return i;return i=N_(n.length,r.length),i||(i=N_(n[n.length-2],r[r.length-2]),i||N_(n[n.length-1],r[r.length-1]))}class G0{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class H0{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.getBaseDocument(t,n,r))).next(e=>(null!==r&&tI(r.mutation,e,_w.empty(),D_.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,bI()).next(()=>e))}getLocalViewOfDocuments(e,t,n=bI()){const r=yI();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=mI();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=yI();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,bI()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=fI;const a=yI(),o=yI();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof iI)?s=s.insert(t.key,t):void 0!==n&&(a.set(t.key,n.mutation.getFieldMask()),tI(n.mutation,t,n.mutation.getFieldMask(),D_.now()))}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new G0(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=yI();let c=new pw((e,t)=>e-t),l=bI();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||_w.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(c.get(r.batchId)||bI()).add(e),c=c.insert(r.batchId,t))})}).next(()=>{const e=[],t=c.getReverseIterator();for(;t.hasNext();){const c=t.getNext(),n=c.key,r=c.value,i=yI();r.forEach(e=>{var t;l.has(e)||(null!==(t=Zb(a.get(e),o.get(e)))&&i.set(e,t),l=l.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return J_.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,U_.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):kb(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):J_.resolve(yI());let r=-1,i=n;return e.next(e=>J_.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?J_.resolve():this.getBaseDocument(s,t,e).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,bI())).next(e=>({batchId:r,changes:vI(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new U_(t)).next(e=>{let t=mI();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s){const a=i.collectionGroup;let o=mI();return this.indexManager.getCollectionParents(r,a).next(e=>J_.forEach(e,e=>{var t,n=(t=i,e=e.child(a),new _b(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(t,s,n){let a;return this.remoteDocumentCache.getAllFromCollection(t,s.path,n).next(e=>(a=e,this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId))).next(r=>{r.forEach((e,t)=>{var n=t.getKey();null===a.get(n)&&(a=a.insert(n,Jw.newInvalidDocument(n)))});let i=mI();return a.forEach((e,t)=>{var n=r.get(e);void 0!==n&&tI(n.mutation,t,_w.empty(),D_.now()),Db(s,t)&&(i=i.insert(e,t))}),i})}getBaseDocument(e,t,n){return null===n||1===n.mutation.type?this.remoteDocumentCache.getEntry(e,t):J_.resolve(Jw.newInvalidDocument(t))}}class Q0{constructor(e){this.It=e,this.Zn=new Map,this.ts=new Map}getBundleMetadata(e,t){return J_.resolve(this.Zn.get(t))}saveBundleMetadata(e,t){return this.Zn.set(t.id,{id:t.id,version:t.version,createTime:FI(t.createTime)}),J_.resolve()}getNamedQuery(e,t){return J_.resolve(this.ts.get(t))}saveNamedQuery(e,t){return this.ts.set(t.name,{name:(t=t).name,query:$T(t.bundledQuery),readTime:FI(t.readTime)}),J_.resolve()}}class Y0{constructor(){this.overlays=new pw(U_.comparator),this.es=new Map}getOverlay(e,t){return J_.resolve(this.overlays.get(t))}getOverlays(e,t){const n=yI();return J_.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.ue(n,r,t)}),J_.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.es.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.es.delete(n)),J_.resolve()}getOverlaysForCollection(e,t,n){const r=yI(),i=t.length+1,s=new U_(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return J_.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new pw((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=yI(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=yI(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return J_.resolve(a)}ue(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.es.get(r.largestBatchId).delete(n.key);this.es.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new OT(t,n));let i=this.es.get(t);void 0===i&&(i=bI(),this.es.set(t,i)),this.es.set(t,i.add(n.key))}}class J0{constructor(){this.ns=new mw(X0.ss),this.rs=new mw(X0.os)}isEmpty(){return this.ns.isEmpty()}addReference(e,t){var n=new X0(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}us(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.cs(new X0(e,t))}hs(e,t){e.forEach(e=>this.removeReference(e,t))}ls(e){const t=new U_(new M_([])),n=new X0(t,e),r=new X0(t,e+1),i=[];return this.rs.forEachInRange([n,r],e=>{this.cs(e),i.push(e.key)}),i}fs(){this.ns.forEach(e=>this.cs(e))}cs(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}ds(e){var t=new U_(new M_([])),n=new X0(t,e),t=new X0(t,e+1);let r=bI();return this.rs.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new X0(e,0),t=this.ns.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class X0{constructor(e,t){this.key=e,this._s=t}static ss(e,t){return U_.comparator(e.key,t.key)||N_(e._s,t._s)}static os(e,t){return N_(e._s,t._s)||U_.comparator(e.key,t.key)}}class Z0{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.ws=1,this.gs=new mw(X0.ss)}checkEmpty(e){return J_.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.ws;this.ws++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new DT(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.gs=this.gs.add(new X0(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return J_.resolve(s)}lookupMutationBatch(e,t){return J_.resolve(this.ys(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.ps(t+1),n=n<0?0:n;return J_.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return J_.resolve(0===this.mutationQueue.length?-1:this.ws-1)}getAllMutationBatches(e){return J_.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new X0(t,0),r=new X0(t,Number.POSITIVE_INFINITY),i=[];return this.gs.forEachInRange([n,r],e=>{var t=this.ys(e._s);i.push(t)}),J_.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new mw(N_);return t.forEach(e=>{var t=new X0(e,0),n=new X0(e,Number.POSITIVE_INFINITY);this.gs.forEachInRange([t,n],e=>{r=r.add(e._s)})}),J_.resolve(this.Is(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;U_.isDocumentKey(i)||(i=i.child(""));var s=new X0(new U_(i),0);let a=new mw(N_);return this.gs.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e._s)),!0)},s),J_.resolve(this.Is(a))}Is(e){const n=[];return e.forEach(e=>{var t=this.ys(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){m_(0===this.Ts(r.batchId,"removed")),this.mutationQueue.shift();let i=this.gs;return J_.forEach(r.mutations,e=>{var t=new X0(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.gs=i})}An(e){}containsKey(e,t){var n=new X0(t,0),n=this.gs.firstAfterOrEqual(n);return J_.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,J_.resolve()}Ts(e,t){return this.ps(e)}ps(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ys(e){var t=this.ps(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class eE{constructor(e){this.Es=e,this.docs=new pw(U_.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Es(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return J_.resolve(n?n.document.mutableCopy():Jw.newInvalidDocument(t))}getEntries(e,t){let n=fI;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Jw.newInvalidDocument(e))}),J_.resolve(n)}getAllFromCollection(e,t,n){let r=fI;const i=new U_(t.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i}}=s.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||G_(z_(i),n)<=0||(r=r.insert(i.key,i.mutableCopy()))}return J_.resolve(r)}getAllFromCollectionGroup(e,t,n,r){g_()}As(e,t){return J_.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new tE(this)}getSize(e){return J_.resolve(this.size)}}class tE extends U0{constructor(e){super(),this.Yn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Yn.addEntry(n,t)):this.Yn.removeEntry(e)}),J_.waitFor(r)}getFromCache(e,t){return this.Yn.getEntry(e,t)}getAllFromCache(e,t){return this.Yn.getEntries(e,t)}}class nE{constructor(e){this.persistence=e,this.Rs=new pI(e=>eb(e),tb),this.lastRemoteSnapshotVersion=P_.min(),this.highestTargetId=0,this.bs=0,this.Ps=new J0,this.targetCount=0,this.vs=S0.Pn()}forEachTarget(e,n){return this.Rs.forEach((e,t)=>n(t)),J_.resolve()}getLastRemoteSnapshotVersion(e){return J_.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return J_.resolve(this.bs)}allocateTargetId(e){return this.highestTargetId=this.vs.next(),J_.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),J_.resolve()}Dn(e){this.Rs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.vs=new S0(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}addTargetData(e,t){return this.Dn(t),this.targetCount+=1,J_.resolve()}updateTargetData(e,t){return this.Dn(t),J_.resolve()}removeTargetData(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),--this.targetCount,J_.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Rs.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Rs.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),J_.waitFor(a).next(()=>s)}getTargetCount(e){return J_.resolve(this.targetCount)}getTargetData(e,t){var n=this.Rs.get(t)||null;return J_.resolve(n)}addMatchingKeys(e,t,n){return this.Ps.us(t,n),J_.resolve()}removeMatchingKeys(t,e,n){this.Ps.hs(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),J_.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Ps.ls(t),J_.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Ps.ds(t);return J_.resolve(n)}containsKey(e,t){return J_.resolve(this.Ps.containsKey(t))}}class rE{constructor(e,t){this.Vs={},this.overlays={},this.Ss=new lw(0),this.Ds=!1,this.Ds=!0,this.referenceDelegate=e(this),this.Cs=new nE(this),this.indexManager=new l0,this.remoteDocumentCache=(e=e=>this.referenceDelegate.xs(e),new eE(e)),this.It=new LT(t),this.Ns=new Q0(this.It)}start(){return Promise.resolve()}shutdown(){return this.Ds=!1,Promise.resolve()}get started(){return this.Ds}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Y0,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Vs[e.toKey()];return n||(n=new Z0(t,this.referenceDelegate),this.Vs[e.toKey()]=n),n}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ns}runTransaction(e,t,n){h_("MemoryPersistence","Starting transaction:",e);const r=new iE(this.Ss.next());return this.referenceDelegate.ks(),n(r).next(e=>this.referenceDelegate.Os(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ms(t,n){return J_.or(Object.values(this.Vs).map(e=>()=>e.containsKey(t,n)))}}class iE extends Q_{constructor(e){super(),this.currentSequenceNumber=e}}class sE{constructor(e){this.persistence=e,this.Fs=new J0,this.$s=null}static Bs(e){return new sE(e)}get Ls(){if(this.$s)return this.$s;throw g_()}addReference(e,t,n){return this.Fs.addReference(n,t),this.Ls.delete(n.toString()),J_.resolve()}removeReference(e,t,n){return this.Fs.removeReference(n,t),this.Ls.add(n.toString()),J_.resolve()}markPotentiallyOrphaned(e,t){return this.Ls.add(t.toString()),J_.resolve()}removeTarget(e,t){this.Fs.ls(t.targetId).forEach(e=>this.Ls.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Ls.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}ks(){this.$s=new Set}Os(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return J_.forEach(this.Ls,e=>{const t=U_.fromPath(e);return this.Us(n,t).next(e=>{e||r.removeEntry(t,P_.min())})}).next(()=>(this.$s=null,r.apply(n)))}updateLimboDocument(e,t){return this.Us(e,t).next(e=>{e?this.Ls.delete(t.toString()):this.Ls.add(t.toString())})}xs(e){return 0}Us(e,t){return J_.or([()=>J_.resolve(this.Fs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ms(e,t)])}}class aE{constructor(e){this.It=e}$(t,e,n,r){const i=new X_("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",oT,{unique:!0}),s.createObjectStore("documentMutations"),oE(t),t.createObjectStore("remoteDocuments"));let a=J_.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),oE(t)),a=a.next(()=>function(){const e=i.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:P_.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").W().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",oT,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return J_.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.qs(i))),n<6&&6<=r&&(a=a.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.Ks(i)))),n<7&&7<=r&&(a=a.next(()=>this.Gs(i))),n<8&&8<=r&&(a=a.next(()=>this.Qs(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.js(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:IT});e.createIndex("collectionPathOverlayIndex",TT,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",ET,{unique:!1})}()})),n<13&&13<=r&&(a=a.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:hT});e.createIndex("documentKeyIndex",dT),e.createIndex("collectionGroupIndex",pT)}()).next(()=>this.Ws(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.zs(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:yT}).createIndex("sequenceNumberIndex",_T,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:wT}).createIndex("documentKeyIndex",bT,{unique:!1})}(t))),a}Ks(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=b0(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}qs(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.W().next(e=>J_.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.W("userMutationsIndex",e).next(e=>J_.forEach(e,e=>{m_(e.userId===n.userId);var t=BT(this.It,e);return w0(r,n.userId,t).next(()=>{})}))}))}Gs(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Z((e,t)=>{const n=new M_(e),r=[0,iT(n)];s.push(a.get(r).next(e=>e?J_.resolve():(e=>a.put({targetId:0,path:iT(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>J_.waitFor(s))})}Qs(e,t){e.createObjectStore("collectionParents",{keyPath:vT});const n=t.store("collectionParents"),r=new u0,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:iT(r)})}};return t.store("remoteDocuments").Z({X:!0},(e,t)=>{const n=new M_(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Z({X:!0},([,e],t)=>{const n=aT(e);return i(n.popLast())}))}js(e){const r=e.store("targets");return r.Z((e,t)=>{var n=jT(t),n=KT(this.It,n);return r.put(n)})}Ws(e,s){const t=s.store("remoteDocuments"),a=[];return t.Z((e,t)=>{const n=s.store("remoteDocumentsV14"),r=((i=t).document?new U_(M_.fromString(i.document.name).popFirst(5)):i.noDocument?U_.fromSegments(i.noDocument.path):i.unknownDocument?U_.fromSegments(i.unknownDocument.path):g_()).path.toArray();var i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.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(()=>J_.waitFor(a))}zs(e,s){const t=s.store("mutations"),a=V0(this.It),o=new rE(sE.Bs,this.It.re);return t.W().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:bI();BT(this.It,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),J_.forEach(r,(e,t)=>{var n=new o_(t),r=JT.oe(this.It,n),i=o.getIndexManager(n),n=I0.oe(n,this.It,i,o.referenceDelegate);return new H0(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new RT(s,lw.at),e).next()})})}}function oE(e){e.createObjectStore("targetDocuments",{keyPath:gT}).createIndex("documentTargetsIndex",mT,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",fT,{unique:!0}),e.createObjectStore("targetGlobal")}const cE="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 lE{constructor(e,t,n,r,i,s,a,o,c,l,u=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Hs=i,this.window=s,this.document=a,this.Js=c,this.Ys=l,this.Xs=u,this.Ss=null,this.Ds=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Zs=null,this.inForeground=!1,this.ti=null,this.ei=null,this.ni=Number.NEGATIVE_INFINITY,this.si=e=>Promise.resolve(),!lE.C())throw new y_(v_.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new L0(this,r),this.ii=t+"main",this.It=new LT(o),this.ri=new Z_(this.ii,this.Xs,new aE(this.It)),this.Cs=new A0(this.referenceDelegate,this.It),this.remoteDocumentCache=V0(this.It),this.Ns=new HT,this.window&&this.window.localStorage?this.oi=this.window.localStorage:(this.oi=null,!1===l&&d_("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.ui().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new y_(v_.FAILED_PRECONDITION,cE);return this.ci(),this.ai(),this.hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Cs.getHighestSequenceNumber(e))}).then(e=>{this.Ss=new lw(e,this.Js)}).then(()=>{this.Ds=!0}).catch(e=>(this.ri&&this.ri.close(),Promise.reject(e)))}li(t){return this.si=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ri.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Hs.enqueueAndForget(async()=>{this.started&&await this.ui()}))}ui(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>hE(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.Hs.enqueueRetryable(()=>this.si(!1)))})}).next(()=>this.di(t)).next(e=>this.isPrimary&&!e?this._i(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(nw(e))return h_("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return h_("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Hs.enqueueRetryable(()=>this.si(e)),this.isPrimary=e})}fi(e){return uE(e).get("owner").next(e=>J_.resolve(this.mi(e)))}gi(e){return hE(e).delete(this.clientId)}async yi(){if(this.isPrimary&&!this.pi(this.ni,18e5)){this.ni=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=xT(e,"clientMetadata");return r.W().next(e=>{const t=this.Ii(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return J_.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.oi)for(const t of e)this.oi.removeItem(this.Ti(t.clientId))}}hi(){this.ei=this.Hs.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.ui().then(()=>this.yi()).then(()=>this.hi()))}mi(e){return!!e&&e.ownerId===this.clientId}di(t){return this.Ys?J_.resolve(!0):uE(t).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)){if(this.mi(e)&&this.networkEnabled)return!0;if(!this.mi(e)){if(!e.allowTabSynchronization)throw new y_(v_.FAILED_PRECONDITION,cE);return!1}}return!(!this.networkEnabled||!this.inForeground)||hE(t).W().next(e=>void 0===this.Ii(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&h_("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Ds=!1,this.Ai(),this.ei&&(this.ei.cancel(),this.ei=null),this.Ri(),this.bi(),await this.ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new RT(e,lw.at);return this._i(t).next(()=>this.gi(t))}),this.ri.close(),this.Pi()}Ii(e,t){return e.filter(e=>this.pi(e.updateTimeMs,t)&&!this.Ei(e.clientId))}vi(){return this.runTransaction("getActiveClients","readonly",e=>hE(e).W().next(e=>this.Ii(e,18e5).map(e=>e.clientId)))}get started(){return this.Ds}getMutationQueue(e,t){return I0.oe(e,this.It,t,this.referenceDelegate)}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new d0(e,this.It.re.databaseId)}getDocumentOverlayCache(e){return JT.oe(this.It,e)}getBundleCache(){return this.Ns}runTransaction(t,n,r){h_("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",e=15===(e=this.Xs)?NT:14===e?AT:13===e?ST:12===e?CT:11===e?kT:void g_();let s;return this.ri.runTransaction(t,i,e,e=>(s=new RT(e,this.Ss?this.Ss.next():lw.at),"readwrite-primary"===n?this.fi(s).next(e=>!!e||this.di(s)).next(e=>{if(!e)throw d_(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Hs.enqueueRetryable(()=>this.si(!1)),new y_(v_.FAILED_PRECONDITION,H_);return r(s)}).next(e=>this.wi(s).next(()=>e)):this.Vi(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}Vi(e){return uE(e).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)&&!this.mi(e)&&!(this.Ys||this.allowTabSynchronization&&e.allowTabSynchronization))throw new y_(v_.FAILED_PRECONDITION,cE)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return uE(e).put("owner",t)}static C(){return Z_.C()}_i(e){const t=uE(e);return t.get("owner").next(e=>this.mi(e)?(h_("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):J_.resolve())}pi(e,t){var n=Date.now();return!(e<n-t||n<e&&(d_(`Detected an update time that is in the future: ${e} > ${n}`),1))}ci(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ti=()=>{this.Hs.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.ui()))},this.document.addEventListener("visibilitychange",this.ti),this.inForeground="visible"===this.document.visibilityState)}Ri(){this.ti&&(this.document.removeEventListener("visibilitychange",this.ti),this.ti=null)}ai(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Zs=()=>{this.Ai(),!l()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match(/Version\/1[45]/)&&this.Hs.enterRestrictedMode(!0),this.Hs.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Zs))}bi(){this.Zs&&(this.window.removeEventListener("pagehide",this.Zs),this.Zs=null)}Ei(e){var t;try{var n=null!==(null===(t=this.oi)||void 0===t?void 0:t.getItem(this.Ti(e)));return h_("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return d_("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ai(){if(this.oi)try{this.oi.setItem(this.Ti(this.clientId),String(Date.now()))}catch(e){d_("Failed to set zombie client id.",e)}}Pi(){if(this.oi)try{this.oi.removeItem(this.Ti(this.clientId))}catch(e){}}Ti(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function uE(e){return xT(e,"owner")}function hE(e){return xT(e,"clientMetadata")}function dE(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class pE{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Si=n,this.Di=r}static Ci(e,t){let n=bI(),r=bI();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new pE(e,t.fromCache,n,r)}}class fE{constructor(){this.xi=!1}initialize(e,t){this.Ni=e,this.indexManager=t,this.xi=!0}getDocumentsMatchingQuery(t,n,r,i){return this.ki(t,n).next(e=>e||this.Oi(t,n,i,r)).next(e=>e||this.Mi(t,n))}ki(i,s){if(Ib(s))return J_.resolve(null);let t=Sb(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Ab(s,null,"F"),t=Sb(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=bI(...e);return this.Ni.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Fi(s,n);return this.$i(s,t,r,e.readTime)?this.ki(i,Ab(s,null,"F")):this.Bi(i,t,s,e)}))})))}Oi(n,r,i,s){return Ib(r)||s.isEqual(P_.min())?this.Mi(n,r):this.Ni.getDocuments(n,i).next(e=>{var t=this.Fi(r,e);return this.$i(r,t,i,s)?this.Mi(n,r):(u_()<=k.DEBUG&&h_("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),xb(r)),this.Bi(n,t,r,$_(s,-1)))})}Fi(n,e){let r=new mw(Ob(n));return e.forEach((e,t)=>{Db(n,t)&&(r=r.add(t))}),r}$i(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Mi(e,t){return u_()<=k.DEBUG&&h_("QueryEngine","Using full collection scan to execute query:",xb(t)),this.Ni.getDocumentsMatchingQuery(e,t,W_.min())}Bi(e,n,t,r){return this.Ni.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class gE{constructor(e,t,n,r){this.persistence=e,this.Li=t,this.It=r,this.Ui=new pw(N_),this.qi=new pI(e=>eb(e),tb),this.Ki=new Map,this.Gi=e.getRemoteDocumentCache(),this.Cs=e.getTargetCache(),this.Ns=e.getBundleCache(),this.Qi(n)}Qi(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new H0(this.Gi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Gi.setIndexManager(this.indexManager),this.Li.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Ui))}}function mE(e,t,n,r){return new gE(e,t,n,r)}async function vE(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a.Qi(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=bI();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({ji:e,removedBatchIds:t,addedBatchIds:n}))})})}function yE(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Cs.getLastRemoteSnapshotVersion(e))}function _E(e,l){const u=e,h=l.snapshotVersion;let d=u.Ui;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=u.Gi.newChangeBuffer({trackRemovals:!0});d=u.Ui;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.Cs.removeMatchingKeys(o,t.removedDocuments,n).next(()=>u.Cs.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;l.targetMismatches.has(n)?e=e.withResumeToken(ww.EMPTY_BYTE_STRING,P_.min()).withLastLimboFreeSnapshotVersion(P_.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||c.push(u.Cs.updateTargetData(o,e))}});let t=fI,n=bI();if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),c.push(wE(o,e,l.documentUpdates).next(e=>{t=e.Wi,n=e.zi})),!h.isEqual(P_.min())){const l=u.Cs.getLastRemoteSnapshotVersion(o).next(e=>u.Cs.setTargetsMetadata(o,o.currentSequenceNumber,h));c.push(l)}return J_.waitFor(c).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(u.Ui=d,e))}function wE(e,s,t){let n=bI(),a=bI();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=fI;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(P_.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):h_("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{Wi:i,zi:a}})}function bE(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Cs.getTargetData(t,r).next(e=>e?(n=e,J_.resolve(n)):i.Cs.allocateTargetId(t).next(e=>(n=new MT(r,e,0,t.currentSequenceNumber),i.Cs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Ui.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Ui=i.Ui.insert(e.targetId,e),i.qi.set(r,e.targetId)),e})}async function IE(e,t,n){const r=e,i=r.Ui.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!nw(e))throw e;h_("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Ui=r.Ui.remove(t),r.qi.delete(i.target)}function TE(e,n,r){const i=e;let s=P_.min(),a=bI();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.qi.get(n);return void 0!==i?J_.resolve(r.Ui.get(i)):r.Cs.getTargetData(t,n)}(i,t,Sb(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Cs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.Li.getDocumentsMatchingQuery(t,n,r?s:P_.min(),r?a:bI())).next(e=>(CE(i,Pb(n),e),{documents:e,Hi:a})))}function EE(e,t){const n=e,r=n.Cs,i=n.Ui.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.se(e,t).next(e=>e?e.target:null))}function kE(e,t){const n=e,r=n.Ki.get(t)||P_.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.Gi.getAllFromCollectionGroup(e,t,$_(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(CE(n,t,e),e))}function CE(e,t,n){let r=e.Ki.get(t)||P_.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.Ki.set(t,r)}function SE(e,t){return`firestore_clients_${e}_${t}`}function AE(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function NE(e,t){return`firestore_targets_${e}_${t}`}class RE{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Zi(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new y_(r.error.code,r.error.message))),s?new RE(e,t,r.state,i):(d_("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class xE{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Zi(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new y_(n.error.code,n.error.message))),i?new xE(e,n.state,r):(d_("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class DE{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Zi(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=II;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=xw(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new DE(e,i):(d_("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class PE{constructor(e,t){this.clientId=e,this.onlineState=t}static Zi(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new PE(t.clientId,t.onlineState):(d_("SharedClientState",`Failed to parse online state: ${e}`),null)}}class OE{constructor(){this.activeTargetIds=II}er(e){this.activeTargetIds=this.activeTargetIds.add(e)}nr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}tr(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class ME{constructor(e,t,n,r,i){this.window=e,this.Hs=t,this.persistenceKey=n,this.sr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ir=this.rr.bind(this),this.ur=new pw(N_),this.started=!1,this.cr=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.ar=SE(this.persistenceKey,this.sr),this.hr=`firestore_sequence_number_${this.persistenceKey}`,this.ur=this.ur.insert(this.sr,new OE),this.lr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.dr=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this._r=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.wr=`firestore_online_state_${this.persistenceKey}`,this.mr=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.ir)}static C(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.vi();for(const n of e)if(n!==this.sr){const e=this.getItem(SE(this.persistenceKey,n));var t;!e||(t=DE.Zi(n,e))&&(this.ur=this.ur.insert(t.clientId,t))}this.gr();const n=this.storage.getItem(this.wr);if(n){const e=this.yr(n);e&&this.pr(e)}for(const e of this.cr)this.rr(e);this.cr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.hr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ir(this.ur)}isActiveQueryTarget(n){let r=!1;return this.ur.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Tr(e,"pending")}updateMutationState(e,t,n){this.Tr(e,t,n),this.Er(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(NE(this.persistenceKey,e)))||(n=xE.Zi(e,n))&&(t=n.state)),this.Ar.er(e),this.gr(),t}removeLocalQueryTarget(e){this.Ar.nr(e),this.gr()}isLocalQueryTarget(e){return this.Ar.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(NE(this.persistenceKey,e))}updateQueryState(e,t,n){this.Rr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Er(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Pr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ir),this.removeItem(this.ar),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return h_("SharedClientState","READ",e,t),t}setItem(e,t){h_("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){h_("SharedClientState","REMOVE",e),this.storage.removeItem(e)}rr(e){const i=e;i.storageArea===this.storage&&(h_("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.ar?this.Hs.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.lr.test(i.key)){if(null==i.newValue){var e=this.vr(i.key);return this.Vr(e,null)}e=this.Sr(i.key,i.newValue);if(e)return this.Vr(e.clientId,e)}else if(this.dr.test(i.key)){if(null!==i.newValue){var t=this.Dr(i.key,i.newValue);if(t)return this.Cr(t)}}else if(this._r.test(i.key)){if(null!==i.newValue){t=this.Nr(i.key,i.newValue);if(t)return this.kr(t)}}else if(i.key===this.wr){if(null!==i.newValue){var n=this.yr(i.newValue);if(n)return this.pr(n)}}else if(i.key===this.hr){n=function(e){let t=lw.at;if(null!=e)try{var n=JSON.parse(e);m_("number"==typeof n),t=n}catch(e){d_("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==lw.at&&this.sequenceNumberHandler(n)}else if(i.key===this.mr){const r=this.Or(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Mr(e)))}}else this.cr.push(i)}):d_("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Ar(){return this.ur.get(this.sr)}gr(){this.setItem(this.ar,this.Ar.tr())}Tr(e,t,n){const r=new RE(this.currentUser,e,t,n),i=AE(this.persistenceKey,this.currentUser,e);this.setItem(i,r.tr())}Er(e){var t=AE(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){var t={clientId:this.sr,onlineState:e};this.storage.setItem(this.wr,JSON.stringify(t))}Rr(e,t,n){const r=NE(this.persistenceKey,e),i=new xE(e,t,n);this.setItem(r,i.tr())}Pr(e){var t=JSON.stringify(Array.from(e));this.setItem(this.mr,t)}vr(e){var t=this.lr.exec(e);return t?t[1]:null}Sr(e,t){var n=this.vr(e);return DE.Zi(n,t)}Dr(e,t){var n=this.dr.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return RE.Zi(new o_(n),r,t)}Nr(e,t){var n=this._r.exec(e),n=Number(n[1]);return xE.Zi(n,t)}yr(e){return PE.Zi(e)}Or(e){return JSON.parse(e)}async Cr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Fr(e.batchId,e.state,e.error);h_("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}kr(e){return this.syncEngine.$r(e.targetId,e.state,e.error)}Vr(e,t){const n=t?this.ur.insert(e,t):this.ur.remove(e),r=this.Ir(this.ur),i=this.Ir(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Br(s,a).then(()=>{this.ur=n})}pr(e){this.ur.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ir(e){let n=II;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class LE{constructor(){this.Lr=new OE,this.Ur={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Lr.er(e),this.Ur[e]||"not-current"}updateQueryState(e,t,n){this.Ur[e]=t}removeLocalQueryTarget(e){this.Lr.nr(e)}isLocalQueryTarget(e){return this.Lr.activeTargetIds.has(e)}clearQueryState(e){delete this.Ur[e]}getAllActiveQueryTargets(){return this.Lr.activeTargetIds}isActiveQueryTarget(e){return this.Lr.activeTargetIds.has(e)}start(){return this.Lr=new OE,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class FE{qr(e){}shutdown(){}}class UE{constructor(){this.Kr=()=>this.Gr(),this.Qr=()=>this.jr(),this.Wr=[],this.zr()}qr(e){this.Wr.push(e)}shutdown(){window.removeEventListener("online",this.Kr),window.removeEventListener("offline",this.Qr)}zr(){window.addEventListener("online",this.Kr),window.addEventListener("offline",this.Qr)}Gr(){h_("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Wr)e(0)}jr(){h_("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Wr)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const qE={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class VE{constructor(e){this.Hr=e.Hr,this.Jr=e.Jr}Yr(e){this.Xr=e}Zr(e){this.eo=e}onMessage(e){this.no=e}close(){this.Jr()}send(e){this.Hr(e)}so(){this.Xr()}io(e){this.eo(e)}ro(e){this.no(e)}}class BE extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.oo=t+"://"+e.host,this.uo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get co(){return!1}ao(t,e,n,r,i){const s=this.ho(t,e);h_("RestConnection","Sending: ",s,n);var a={};return this.lo(a,r,i),this.fo(t,s,a,n).then(e=>(h_("RestConnection","Received: ",e),e),e=>{throw p_("RestConnection",`${t} failed with error: `,e,"url: ",s,"request:",n),e})}_o(e,t,n,r,i,s){return this.ao(e,t,n,r,i)}lo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+c_,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}ho(e,t){var n=qE[e];return`${this.oo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(o,t,n,r){return new Promise((i,s)=>{const a=new s_;a.setWithCredentials(!0),a.listenOnce(Zy.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case Xy.NO_ERROR:var e=a.getResponseJson();h_("Connection","XHR received:",JSON.stringify(e)),i(e);break;case Xy.TIMEOUT:h_("Connection",'RPC "'+o+'" timed out'),s(new y_(v_.DEADLINE_EXCEEDED,"Request time out"));break;case Xy.HTTP_ERROR:var t,n=a.getStatus();if(h_("Connection",'RPC "'+o+'" failed with status:',n,"response text:",a.getResponseText()),0<n){const o=a.getResponseJson().error;o&&o.status&&o.message?(r=o.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(v_).indexOf(r)?r:v_.UNKNOWN,s(new y_(t,o.message))):s(new y_(v_.UNKNOWN,"Server responded with status "+a.getStatus()))}else s(new y_(v_.UNAVAILABLE,"Connection failed."));break;default:g_()}}finally{h_("Connection",'RPC "'+o+'" completed.')}var r});var e=JSON.stringify(r);a.send(t,"POST",e,n,15)})}wo(e,t,n){const r=[this.oo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=new zy,s=Jy(),a={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};this.useFetchStreams&&(a.xmlHttpFactory=new r_({})),this.lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;var o=r.join("");h_("Connection","Creating WebChannel: "+o,a);const c=i.createWebChannel(o,a);let l=!1,u=!1;const h=new VE({Hr:e=>{u?h_("Connection","Not sending because WebChannel is closed:",e):(l||(h_("Connection","Opening WebChannel transport."),c.open(),l=!0),h_("Connection","WebChannel sending:",e),c.send(e))},Jr:()=>c.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(c,i_.EventType.OPEN,()=>{u||h_("Connection","WebChannel transport opened.")}),d(c,i_.EventType.CLOSE,()=>{u||(u=!0,h_("Connection","WebChannel transport closed"),h.io())}),d(c,i_.EventType.ERROR,e=>{u||(u=!0,p_("Connection","WebChannel transport errored:",e),h.io(new y_(v_.UNAVAILABLE,"The operation could not be completed")))}),d(c,i_.EventType.MESSAGE,n=>{if(!u){var e=n.data[0];m_(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){h_("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=Yy[e];if(void 0!==t)return dI(t)}(n),t=r.message;void 0===e&&(e=v_.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),u=!0,h.io(new y_(e,t)),c.close()}else h_("Connection","WebChannel received:",e),h.ro(e)}}),d(s,e_.STAT_EVENT,e=>{e.stat===t_?h_("Connection","Detected buffering proxy"):e.stat===n_&&h_("Connection","Detected no buffering proxy")}),setTimeout(()=>{h.so()},0),h}}function jE(){return"undefined"!=typeof window?window:null}function KE(){return"undefined"!=typeof document?document:null}function $E(e){return new OI(e,!0)}class zE{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Hs=e,this.timerId=t,this.mo=n,this.yo=r,this.po=i,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();var t=Math.floor(this.Io+this.bo()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);0<r&&h_("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Io} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.To=this.Hs.enqueueAfterDelay(this.timerId,r,()=>(this.Eo=Date.now(),e())),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}Po(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}bo(){return(Math.random()-.5)*this.Io}}class WE{constructor(e,t,n,r,i,s,a,o){this.Hs=e,this.vo=n,this.Vo=r,this.So=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Do=0,this.Co=null,this.xo=null,this.stream=null,this.No=new zE(e,t)}ko(){return 1===this.state||5===this.state||this.Oo()}Oo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Mo()}async stop(){this.ko()&&await this.close(0)}Fo(){this.state=0,this.No.reset()}$o(){this.Oo()&&null===this.Co&&(this.Co=this.Hs.enqueueAfterDelay(this.vo,6e4,()=>this.Bo()))}Lo(e){this.Uo(),this.stream.send(e)}async Bo(){if(this.Oo())return this.close(0)}Uo(){this.Co&&(this.Co.cancel(),this.Co=null)}qo(){this.xo&&(this.xo.cancel(),this.xo=null)}async close(e,t){this.Uo(),this.qo(),this.No.cancel(),this.Do++,4!==e?this.No.reset():t&&t.code===v_.RESOURCE_EXHAUSTED?(d_(t.toString()),d_("Using maximum backoff delay to prevent overloading the backend."),this.No.Ao()):t&&t.code===v_.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Ko(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Zr(t)}Ko(){}auth(){this.state=1;const e=this.Go(this.Do),n=this.Do;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Do===n&&this.Qo(e,t)},t=>{e(()=>{var e=new y_(v_.UNKNOWN,"Fetching auth token failed: "+t.message);return this.jo(e)})})}Qo(e,t){const n=this.Go(this.Do);this.stream=this.Wo(e,t),this.stream.Yr(()=>{n(()=>(this.state=2,this.xo=this.Hs.enqueueAfterDelay(this.Vo,1e4,()=>(this.Oo()&&(this.state=3),Promise.resolve())),this.listener.Yr()))}),this.stream.Zr(e=>{n(()=>this.jo(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Mo(){this.state=5,this.No.Ro(async()=>{this.state=0,this.start()})}jo(e){return h_("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Go(t){return e=>{this.Hs.enqueueAndForget(()=>this.Do===t?e():(h_("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class GE extends WE{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.It=i}Wo(e,t){return this.So.wo("Listen",e,t)}onMessage(e){this.No.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(p=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===p?1:"REMOVE"===p?2:"CURRENT"===p?3:"RESET"===p?4:g_(),i=t.targetChange.targetIds||[],s=(p=t.targetChange.resumeToken,e.gt?(m_(void 0===p||"string"==typeof p),ww.fromBase64String(p||"")):(m_(void 0===p||p instanceof Uint8Array),ww.fromUint8Array(p||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(p=a).code?v_.UNKNOWN:dI(p.code),new y_(o,p.message||""));n=new SI(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var o=BI(e,c.document.name),l=FI(c.document.updateTime),u=new Yw({mapValue:{fields:c.document.fields}}),l=Jw.newFoundDocument(o,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new kI(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=BI(e,u.document),l=u.readTime?FI(u.readTime):P_.min(),l=Jw.newNoDocument(c,l),u=u.removedTargetIds||[];n=new kI([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=BI(e,h.document),h=h.removedTargetIds||[];n=new kI([],h,d,null)}else{if(!("filter"in t))return g_();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new uI(h),h=e.targetId;n=new CI(h,d)}}var o,p;return n}(this.It,e),n=function(e){if(!("targetChange"in e))return P_.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?FI(t.readTime):P_.min()}(e);return this.listener.zo(t,n)}Ho(e){const t={};t.database=$I(this.It),t.addTarget=function(e,t){let n;var r=t.target;return n=nb(r)?{documents:YI(e,r)}:{query:JI(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=LI(e,t.resumeToken):0<t.snapshotVersion.compareTo(P_.min())&&(n.readTime=MI(e,t.snapshotVersion.toTimestamp())),n}(this.It,e);var n,r,r=(this.It,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return g_()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Lo(t)}Jo(e){const t={};t.database=$I(this.It),t.removeTarget=e,this.Lo(t)}}class HE extends WE{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.It=i,this.Yo=!1}get Xo(){return this.Yo}start(){this.Yo=!1,this.lastStreamToken=void 0,super.start()}Ko(){this.Yo&&this.Zo([])}Wo(e,t){return this.So.wo("Write",e,t)}onMessage(e){if(m_(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Yo){this.No.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(m_(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?FI(e.updateTime):FI(t);return n.isEqual(P_.min())&&(n=FI(t)),new Qb(n,e.transformResults||[])}(e,i))):[]),n=FI(e.commitTime);return this.listener.tu(n,t)}var r,i;return m_(!e.writeResults||0===e.writeResults.length),this.Yo=!0,this.listener.eu()}nu(){const e={};e.database=$I(this.It),this.Lo(e)}Zo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>HI(this.It,e))};this.Lo(t)}}class QE extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.So=n,this.It=r,this.su=!1}iu(){if(this.su)throw new y_(v_.FAILED_PRECONDITION,"The client has already been terminated.")}ao(n,r,i){return this.iu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.So.ao(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===v_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new y_(v_.UNKNOWN,e.toString())})}_o(n,r,i,s){return this.iu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.So._o(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===v_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new y_(v_.UNKNOWN,e.toString())})}terminate(){this.su=!0}}class YE{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.ru=0,this.ou=null,this.uu=!0}cu(){0===this.ru&&(this.au("Unknown"),this.ou=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.ou=null,this.hu("Backend didn't respond within 10 seconds."),this.au("Offline"),Promise.resolve())))}lu(e){"Online"===this.state?this.au("Unknown"):(this.ru++,1<=this.ru&&(this.fu(),this.hu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.au("Offline")))}set(e){this.fu(),this.ru=0,"Online"===e&&(this.uu=!1),this.au(e)}au(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}hu(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis 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.uu?(d_(t),this.uu=!1):h_("OnlineStateTracker",t)}fu(){null!==this.ou&&(this.ou.cancel(),this.ou=null)}}class JE{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.du=[],this._u=new Map,this.wu=new Set,this.mu=[],this.gu=i,this.gu.qr(e=>{n.enqueueAndForget(async()=>{ak(this)&&(h_("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.wu.add(4),await ZE(t),t.yu.set("Unknown"),t.wu.delete(4),await XE(t)}(this))})}),this.yu=new YE(n,r)}}async function XE(e){if(ak(e))for(const t of e.mu)await t(!0)}async function ZE(e){for(const t of e.mu)await t(!1)}function ek(e,t){const n=e;n._u.has(t.targetId)||(n._u.set(t.targetId,t),sk(n)?ik(n):gk(n).Oo()&&nk(n,t))}function tk(e,t){const n=e,r=gk(n);n._u.delete(t),r.Oo()&&rk(n,t),0===n._u.size&&(r.Oo()?r.$o():ak(n)&&n.yu.set("Unknown"))}function nk(e,t){e.pu.Mt(t.targetId),gk(e).Ho(t)}function rk(e,t){e.pu.Mt(t),gk(e).Jo(t)}function ik(t){t.pu=new NI({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),se:e=>t._u.get(e)||null}),gk(t).start(),t.yu.cu()}function sk(e){return ak(e)&&!gk(e).ko()&&0<e._u.size}function ak(e){return 0===e.wu.size}function ok(e){e.pu=void 0}async function ck(e,t,n){if(!nw(t))throw t;e.wu.add(1),await ZE(e),e.yu.set("Offline"),n=n||(()=>yE(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{h_("RemoteStore","Retrying IndexedDB access"),await n(),e.wu.delete(1),await XE(e)})}function lk(t,n){return n().catch(e=>ck(t,e,n))}async function uk(e){const t=e,n=mk(t);let r=0<t.du.length?t.du[t.du.length-1].batchId:-1;for(;ak(i=t)&&i.du.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.du.length&&n.$o();break}r=e.batchId,function(e,t){e.du.push(t);const n=mk(e);n.Oo()&&n.Xo&&n.Zo(t.mutations)}(t,e)}catch(e){await ck(t,e)}var i;hk(t)&&dk(t)}function hk(e){return ak(e)&&!mk(e).ko()&&0<e.du.length}function dk(e){mk(e).start()}async function pk(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),h_("RemoteStore","RemoteStore received new credentials");var r=ak(n);n.wu.add(3),await ZE(n),r&&n.yu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.wu.delete(3),await XE(n)}async function fk(e,t){const n=e;t?(n.wu.delete(2),await XE(n)):(n.wu.add(2),await ZE(n),n.yu.set("Unknown"))}function gk(t){return t.Iu||(t.Iu=function(e,t,n){const r=e;return r.iu(),new GE(t,r.So,r.authCredentials,r.appCheckCredentials,r.It,n)}(t.datastore,t.asyncQueue,{Yr:(async function(n){n._u.forEach((e,t)=>{nk(n,e)})}).bind(null,t),Zr:(async function(e,t){ok(e),sk(e)?(e.yu.lu(t),ik(e)):e.yu.set("Unknown")}).bind(null,t),zo:(async function(e,r,t){if(e.yu.set("Online"),r instanceof SI&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e._u.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e._u.delete(n),e.pu.removeTarget(n))}(e)}catch(t){h_("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await ck(e,t)}else if(r instanceof kI?e.pu.Gt(r):r instanceof CI?e.pu.Yt(r):e.pu.Wt(r),!t.isEqual(P_.min()))try{const r=await yE(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.pu.te(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r._u.get(t);n&&r._u.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r._u.get(e);var n;t&&(r._u.set(e,t.withResumeToken(ww.EMPTY_BYTE_STRING,t.snapshotVersion)),rk(r,e),n=new MT(t.target,e,1,t.sequenceNumber),nk(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){h_("RemoteStore","Failed to raise snapshot:",r),await ck(e,r)}}).bind(null,t)}),t.mu.push(async e=>{e?(t.Iu.Fo(),sk(t)?ik(t):t.yu.set("Unknown")):(await t.Iu.stop(),ok(t))})),t.Iu}function mk(t){return t.Tu||(t.Tu=function(e,t,n){const r=e;return r.iu(),new HE(t,r.So,r.authCredentials,r.appCheckCredentials,r.It,n)}(t.datastore,t.asyncQueue,{Yr:(async function(e){mk(e).nu()}).bind(null,t),Zr:(async function(e,t){t&&mk(e).Xo&&await async function(e,t){if(hI(n=t.code)&&n!==v_.ABORTED){const n=e.du.shift();mk(e).Fo(),await lk(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await uk(e)}var n}(e,t),hk(e)&&dk(e)}).bind(null,t),eu:(async function(e){const t=mk(e);for(const n of e.du)t.Zo(n.mutations)}).bind(null,t),tu:(async function(e,t,n){const r=e.du.shift(),i=PT.from(r,t,n);await lk(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await uk(e)}).bind(null,t)}),t.mu.push(async e=>{e?(t.Tu.Fo(),await uk(t)):(await t.Tu.stop(),0<t.du.length&&(h_("RemoteStore",`Stopping write stream with ${t.du.length} pending writes`),t.du=[]))})),t.Tu}class vk{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new __,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new vk(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new y_(v_.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 yk(e,t){if(d_("AsyncQueue",`${t}: ${e}`),nw(e))return new y_(v_.UNAVAILABLE,`${t}: ${e}`);throw e}class _k{constructor(n){this.comparator=n?(e,t)=>n(e,t)||U_.comparator(e.key,t.key):(e,t)=>U_.comparator(e.key,t.key),this.keyedMap=mI(),this.sortedSet=new pw(this.comparator)}static emptySet(e){return new _k(e.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(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const 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 _k))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new _k;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class wk{constructor(){this.Eu=new pw(U_.comparator)}track(e){var t=e.doc.key,n=this.Eu.get(t);!n||0!==e.type&&3===n.type?this.Eu=this.Eu.insert(t,e):3===e.type&&1!==n.type?this.Eu=this.Eu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Eu=this.Eu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Eu=this.Eu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Eu=this.Eu.remove(t):1===e.type&&2===n.type?this.Eu=this.Eu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Eu=this.Eu.insert(t,{type:2,doc:e.doc}):g_()}Au(){const n=[];return this.Eu.inorderTraversal((e,t)=>{n.push(t)}),n}}class bk{constructor(e,t,n,r,i,s,a,o,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new bk(e,t,_k.emptySet(t),s,n,r,!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)&&Nb(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Ik{constructor(){this.Ru=void 0,this.listeners=[]}}class Tk{constructor(){this.queries=new pI(e=>Rb(e),Nb),this.onlineState="Unknown",this.bu=new Set}}async function Ek(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new Ik),i)try{s.Ru=await n.onListen(r)}catch(e){const n=yk(e,`Initialization of query '${xb(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Pu(n.onlineState),!s.Ru||t.vu(s.Ru)&&Ck(n)}async function kk(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Ck(e){e.bu.forEach(e=>{e.next()})}class Sk{constructor(e,t,n){this.query=e,this.Vu=t,this.Su=!1,this.Du=null,this.onlineState="Unknown",this.options=n||{}}vu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new bk(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Su?this.Cu(e)&&(this.Vu.next(e),t=!0):this.xu(e,this.onlineState)&&(this.Nu(e),t=!0),this.Du=e,t}onError(e){this.Vu.error(e)}Pu(e){this.onlineState=e;let t=!1;return this.Du&&!this.Su&&this.xu(this.Du,e)&&(this.Nu(this.Du),t=!0),t}xu(e,t){return!e.fromCache||(!this.options.ku||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Cu(e){if(0<e.docChanges.length)return!0;var t=this.Du&&this.Du.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Nu(e){e=bk.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Su=!0,this.Vu.next(e)}}class Ak{constructor(e,t){this.payload=e,this.byteLength=t}Ou(){return"metadata"in this.payload}}class Nk{constructor(e){this.It=e}Ji(e){return BI(this.It,e)}Yi(e){return e.metadata.exists?GI(this.It,e.document,!1):Jw.newNoDocument(this.Ji(e.metadata.name),this.Xi(e.metadata.readTime))}Xi(e){return FI(e)}}class Rk{constructor(e,t,n){this.Mu=e,this.localStore=t,this.It=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=xk(e)}Fu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.payload.namedQuery)this.queries.push(e.payload.namedQuery);else if(e.payload.documentMetadata){this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t;const n=M_.fromString(e.payload.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}$u(e){const t=new Map,n=new Nk(this.It);for(const i of e)if(i.metadata.queries){const e=n.Ji(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||bI()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=bI(),a=fI;for(const e of n){const n=t.Ji(e.metadata.name);e.document&&(s=s.add(n));const l=t.Yi(e);l.setReadTime(t.Xi(e.metadata.readTime)),a=a.insert(n,l)}const o=i.Gi.newChangeBuffer({trackRemovals:!0}),c=await bE(i,(r=r,Sb(bb(M_.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>wE(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Cs.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.Cs.addMatchingKeys(t,s,c.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.Wi,e.zi)).next(()=>e.Wi)))}(this.localStore,new Nk(this.It),this.documents,this.Mu.id),t=this.$u(this.documents);for(const e of this.queries)await async function(e,n,r=bI()){const i=await bE(e,Sb($T(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=FI(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Ns.saveNamedQuery(e,n);t=i.withResumeToken(ww.EMPTY_BYTE_STRING,t);return s.Ui=s.Ui.insert(t.targetId,t),s.Cs.updateTargetData(e,t).next(()=>s.Cs.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Cs.addMatchingKeys(e,r,i.targetId)).next(()=>s.Ns.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function xk(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Dk{constructor(e){this.key=e}}class Pk{constructor(e){this.key=e}}class Ok{constructor(e,t){this.query=e,this.Uu=t,this.qu=null,this.hasCachedResults=!1,this.current=!1,this.Ku=bI(),this.mutatedKeys=bI(),this.Gu=Ob(e),this.Qu=new _k(this.Gu)}get ju(){return this.Uu}Wu(e,t){const o=t?t.zu:new wk,c=(t||this).Qu;let l=(t||this).mutatedKeys,u=c,h=!1;const d="F"===this.query.limitType&&c.size===this.query.limit?c.last():null,p="L"===this.query.limitType&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=Db(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Hu(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Gu(r,d)||p&&this.Gu(r,p)<0)&&(h=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||p)&&(h=!0)),a&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){const e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),o.track({type:1,doc:e})}return{Qu:u,zu:o,$i:h,mutatedKeys:l}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const i=e.zu.Au();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return g_()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc)),this.Ju(n);var s=t?this.Yu():[],a=0===this.Ku.size&&this.current?1:0,o=a!==this.qu;return this.qu=a,0!==i.length||o?{snapshot:new bk(this.query,e.Qu,r,i,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),Xu:s}:{Xu:s}}Pu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new wk,mutatedKeys:this.mutatedKeys,$i:!1},!1)):{Xu:[]}}Zu(e){return!this.Uu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}Ju(e){e&&(e.addedDocuments.forEach(e=>this.Uu=this.Uu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Uu=this.Uu.delete(e)),this.current=e.current)}Yu(){if(!this.current)return[];const t=this.Ku;this.Ku=bI(),this.Qu.forEach(e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))});const n=[];return t.forEach(e=>{this.Ku.has(e)||n.push(new Pk(e))}),this.Ku.forEach(e=>{t.has(e)||n.push(new Dk(e))}),n}tc(e){this.Uu=e.Hi,this.Ku=bI();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}ec(){return bk.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.qu,this.hasCachedResults)}}class Mk{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Lk{constructor(e){this.key=e,this.nc=!1}}class Fk{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.sc={},this.ic=new pI(e=>Rb(e),Nb),this.rc=new Map,this.oc=new Set,this.uc=new pw(U_.comparator),this.cc=new Map,this.ac=new J0,this.hc={},this.lc=new Map,this.fc=S0.vn(),this.onlineState="Unknown",this.dc=void 0}get isPrimaryClient(){return!0===this.dc}}async function Uk(n,e,t,r,i){n._c=(e,s,t)=>async function(e,t,n){let r=t.view.Wu(s);r.$i&&(r=await TE(e.localStore,t.query,!1).then(({documents:e})=>t.view.Wu(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return Gk(e,t.targetId,i.Xu),i.snapshot}(n,e,t);const s=await TE(n.localStore,e,!0),a=new Ok(e,s.Hi),o=a.Wu(s.documents),c=EI.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,i),l=a.applyChanges(o,n.isPrimaryClient,c);Gk(n,t,l.Xu);var u=new Mk(e,t,a);return n.ic.set(e,u),n.rc.has(t)?n.rc.get(t).push(e):n.rc.set(t,[e]),l.snapshot}async function qk(e,t,n){const r=eC(e);try{const e=await function(e,i){const s=e,a=D_.now(),o=i.reduce((e,t)=>e.add(t.key),bI());let c,l;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=fI,r=bI();return s.Gi.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{c=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=qb(r.transform,e||null);null!=i&&(null===n&&(n=Yw.empty()),n.set(r.field,i))}return n||null}(n,c.get(n.key).overlayedDocument);null!=i&&t.push(new iI(n.key,i,function r(e){const i=[];return hw(e.fields,(e,t)=>{const n=new F_([e]);if(zw(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new _w(i)}(i.value.mapValue),Yb.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(l=e).applyToLocalDocumentSet(c,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:l.batchId,changes:vI(c)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.hc[e.currentUser.toKey()];r=r||new pw(N_),r=r.insert(t,n),e.hc[e.currentUser.toKey()]=r}(r,e.batchId,n),await Qk(r,e.changes),await uk(r.remoteStore)}catch(e){const t=yk(e,"Failed to persist write");n.reject(t)}}async function Vk(e,t){const r=e;try{const e=await _E(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.cc.get(t);n&&(m_(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.nc=!0:0<e.modifiedDocuments.size?m_(n.nc):0<e.removedDocuments.size&&(m_(n.nc),n.nc=!1))}),await Qk(r,e,t)}catch(e){await Y_(e)}}function Bk(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ic.forEach((e,t)=>{var n=t.view.Pu(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.Pu(n)&&(r=!0)}),r&&Ck(t)}(t.eventManager,i),r.length&&t.sc.zo(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function jk(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.Gi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=J_.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);m_(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=bI();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);$k(n,r,null),Kk(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Qk(n,e)}catch(e){await Y_(e)}}function Kk(e,t){(e.lc.get(t)||[]).forEach(e=>{e.resolve()}),e.lc.delete(t)}function $k(e,t,n){const r=e;let i=r.hc[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.hc[r.currentUser.toKey()]=i}}function zk(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.rc.get(e))t.ic.delete(r),n&&t.sc.wc(r,n);t.rc.delete(e),t.isPrimaryClient&&t.ac.ls(e).forEach(e=>{t.ac.containsKey(e)||Wk(t,e)})}function Wk(e,t){e.oc.delete(t.path.canonicalString());var n=e.uc.get(t);null!==n&&(tk(e.remoteStore,n),e.uc=e.uc.remove(t),e.cc.delete(n),Hk(e))}function Gk(e,t,n){for(const r of n)r instanceof Dk?(e.ac.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.uc.get(n)||e.oc.has(r)||(h_("SyncEngine","New document in limbo: "+n),e.oc.add(r),Hk(e))}(e,r)):r instanceof Pk?(h_("SyncEngine","Document no longer in limbo: "+r.key),e.ac.removeReference(r.key,t),e.ac.containsKey(r.key)||Wk(e,r.key)):g_()}function Hk(e){for(;0<e.oc.size&&e.uc.size<e.maxConcurrentLimboResolutions;){var t=e.oc.values().next().value;e.oc.delete(t);var n=new U_(M_.fromString(t)),t=e.fc.next();e.cc.set(t,new Lk(n)),e.uc=e.uc.insert(n,t),ek(e.remoteStore,new MT(Sb(bb(n.path)),t,2,lw.at))}}async function Qk(e,t,r){const i=e,s=[],a=[],o=[];i.ic.isEmpty()||(i.ic.forEach((e,n)=>{o.push(i._c(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=pE.Ci(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.sc.zo(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>J_.forEach(t,t=>J_.forEach(t.Si,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>J_.forEach(t.Di,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!nw(e))throw e;h_("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Ui.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Ui=r.Ui.insert(t,i)}}}(i.localStore,a))}async function Yk(r,e){const i=r;if(Zk(i),eC(i),!0===e&&!0!==i.dc){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Jk(i,r.toArray());i.dc=!0,await fk(i.remoteStore,!0);for(const r of e)ek(i.remoteStore,r)}else if(!1===e&&!1!==i.dc){const r=[];let n=Promise.resolve();i.rc.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(zk(i,t),IE(i.localStore,t,!0))),tk(i.remoteStore,t)}),await n,await Jk(i,r),function(){const n=i;n.cc.forEach((e,t)=>{tk(n.remoteStore,t)}),n.ac.fs(),n.cc=new Map,n.uc=new pw(U_.comparator)}(),i.dc=!1,await fk(i.remoteStore,!1)}}async function Jk(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.rc.get(t);if(u&&0!==u.length){e=await bE(r.localStore,Sb(u[0]));for(const t of u){const n=r.ic.get(t),u=(a=r,o=n,l=c=void 0,l=await TE((c=a).localStore,o.query,!0),l=o.view.tc(l),c.isPrimaryClient&&Gk(c,o.targetId,l.Xu),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await EE(r.localStore,t);e=await bE(r.localStore,u),await Uk(r,Xk(u),t,!1,e.resumeToken)}i.push(e)}var a,o,c,l;return r.sc.zo(s),i}function Xk(e){return wb(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zk(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Vk.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.cc.get(t);if(r&&r.nc)return bI().add(r.key);{let e=bI();const r=n.rc.get(t);if(!r)return e;for(const t of r){const r=n.ic.get(t);e=e.unionWith(r.view.ju)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.cc.get(t),s=i&&i.key;if(s){let e=new pw(U_.comparator);e=e.insert(s,Jw.newNoDocument(s,P_.min()));const n=bI().add(s),i=new TI(P_.min(),new Map,new mw(N_),e,n);await Vk(r,i),r.uc=r.uc.remove(s),r.cc.delete(t),Hk(r)}else await IE(r.localStore,t,!1).then(()=>zk(r,t,n)).catch(Y_)}).bind(null,t),t.sc.zo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.vu(e)&&(r=!0);i.Ru=e}}r&&Ck(n)}).bind(null,t.eventManager),t.sc.wc=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function eC(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=jk.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(m_(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);$k(r,t,n),Kk(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Qk(r,e)}catch(n){await Y_(n)}}).bind(null,t),t}class tC{constructor(){this.synchronizeTabs=!1}async initialize(e){this.It=$E(e.databaseInfo.databaseId),this.sharedClientState=this.gc(e),this.persistence=this.yc(e),await this.persistence.start(),this.localStore=this.Ic(e),this.gcScheduler=this.Tc(e,this.localStore),this.indexBackfillerScheduler=this.Ec(e,this.localStore)}Tc(e,t){return null}Ec(e,t){return null}Ic(e){return mE(this.persistence,new fE,e.initialUser,this.It)}yc(e){return new rE(sE.Bs,this.It)}gc(e){return new LE}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class nC extends tC{constructor(e,t,n){super(),this.Ac=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ac.initialize(this,e),await eC(this.Ac.syncEngine),await uk(this.Ac.remoteStore),await this.persistence.li(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Ic(e){return mE(this.persistence,new fE,e.initialUser,this.It)}Tc(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new O0(n,e.asyncQueue,t)}Ec(e,t){var n=new cw(t,this.persistence);return new ow(e.asyncQueue,n)}yc(e){var t=dE(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?_0.withCacheSize(this.cacheSizeBytes):_0.DEFAULT;return new lE(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,jE(),KE(),this.It,this.sharedClientState,!!this.forceOwnership)}gc(e){return new LE}}class rC extends nC{constructor(e,t){super(e,t,!1),this.Ac=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ac.syncEngine;this.sharedClientState instanceof ME&&(this.sharedClientState.syncEngine={Fr:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Tn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):J_.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await uk(i.remoteStore):"acknowledged"===n||"rejected"===n?($k(i,t,r||null),Kk(i,t),i.localStore.mutationQueue.An(t)):g_(),await Qk(i,s)):h_("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),$r:(async function(e,t,n,r){const i=e;if(i.dc)h_("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.rc.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await kE(i.localStore,Pb(s[0])),r=TI.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,ww.EMPTY_BYTE_STRING);await Qk(i,e,r);break}case"rejected":await IE(i.localStore,t,!0),zk(i,t,r);break;default:g_()}}}).bind(null,t),Br:(async function(e,t,n){const r=Zk(e);if(r.dc){for(const e of t)if(r.rc.has(e))h_("SyncEngine","Adding an already active target "+e);else{const t=await EE(r.localStore,e),n=await bE(r.localStore,t);await Uk(r,Xk(t),n.targetId,!1,n.resumeToken),ek(r.remoteStore,n)}for(const e of n)r.rc.has(e)&&await IE(r.localStore,e,!1).then(()=>{tk(r.remoteStore,e),zk(r,e)}).catch(Y_)}}).bind(null,t),vi:(function(e){return e.localStore.persistence.vi()}).bind(null,t),Mr:(async function(e,t){const n=e;return kE(n.localStore,t).then(e=>Qk(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.li(async e=>{await Yk(this.Ac.syncEngine,e),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())})}gc(e){var t=jE();if(!ME.C(t))throw new y_(v_.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=dE(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ME(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class iC{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=>Bk(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){h_("SyncEngine","User change. New user:",t.toKey());const r=await vE(n.localStore,t);n.currentUser=t,(e=n).lc.forEach(e=>{e.forEach(e=>{e.reject(new y_(v_.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.lc.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await Qk(n,r.ji)}}).bind(null,this.syncEngine),await fk(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Tk}createDatastore(e){var t,n,r,i,s=$E(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new BE(t));return n=e.authCredentials,r=e.appCheckCredentials,i=t,e=s,new QE(n,r,i,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>Bk(this.syncEngine,e,0),s=new(UE.C()?UE:FE),new JE(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Fk(e,t,n,r,i,s);return a&&(o.dc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;h_("RemoteStore","RemoteStore shutting down."),t.wu.add(5),await ZE(t),t.gu.shutdown(),t.yu.set("Unknown")}(this.remoteStore)}}function sC(e,t,n){if(!n)throw new y_(v_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function aC(e,t,n,r){if(!0===t&&!0===r)throw new y_(v_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function oC(e){if(!U_.isDocumentKey(e))throw new y_(v_.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function cC(e){if(U_.isDocumentKey(e))throw new y_(v_.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function lC(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":g_();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function uC(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new y_(v_.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=lC(e);throw new y_(v_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function hC(e,t){if(t<=0)throw new y_(v_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}const dC=new Map;class pC{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new y_(v_.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new y_(v_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,aC("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}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&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class fC{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new pC({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new y_(v_.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new y_(v_.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 pC(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new b_;switch(e.type){case"gapi":var t=e.client;return new k_(t,e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new y_(v_.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=dC.get(e);t&&(h_("ComponentProvider","Removing Datastore"),dC.delete(e),t.terminate())}(this),Promise.resolve()}}class gC{constructor(e,t,n){this.converter=t,this._key=n,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 vC(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new gC(this.firestore,e,this._key)}}class mC{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new mC(this.firestore,e,this._query)}}class vC extends mC{constructor(e,t,n){super(e,t,bb(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new gC(this.firestore,null,new U_(e))}withConverter(e){return new vC(this.firestore,e,this._path)}}function yC(e,t,...n){if(e=ae(e),sC("collection","path",t),e instanceof fC){var r=M_.fromString(t,...n);return cC(r),new vC(e,null,r)}if(!(e instanceof gC||e instanceof vC))throw new y_(v_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(M_.fromString(t,...n));return cC(r),new vC(e.firestore,null,r)}function _C(e,t,...n){if(e=ae(e),sC("doc","path",t=1===arguments.length?A_.R():t),e instanceof fC){var r=M_.fromString(t,...n);return oC(r),new gC(e,null,new U_(r))}if(!(e instanceof gC||e instanceof vC))throw new y_(v_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(M_.fromString(t,...n));return oC(r),new gC(e.firestore,e instanceof vC?e.converter:null,new U_(r))}function wC(e,t){return e=ae(e),t=ae(t),(e instanceof gC||e instanceof vC)&&(t instanceof gC||t instanceof vC)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function bC(e,t){return e=ae(e),t=ae(t),e instanceof mC&&t instanceof mC&&e.firestore===t.firestore&&Nb(e._query,t._query)&&e.converter===t.converter}function IC(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class TC{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Rc(this.observer.next,e)}error(e){this.observer.error?this.Rc(this.observer.error,e):d_("Uncaught Error in snapshot listener:",e)}bc(){this.muted=!0}Rc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class EC{constructor(e,t){this.Pc=e,this.It=t,this.metadata=new __,this.buffer=new Uint8Array,this.vc=new TextDecoder("utf-8"),this.Vc().then(e=>{e&&e.Ou()?this.metadata.resolve(e.payload.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.payload)}`))},e=>this.metadata.reject(e))}close(){return this.Pc.cancel()}async getMetadata(){return this.metadata.promise}async mc(){return await this.getMetadata(),this.Vc()}async Vc(){var e=await this.Sc();if(null===e)return null;var t=this.vc.decode(e),n=Number(t);isNaN(n)&&this.Dc(`length string (${t}) is not valid number`);t=await this.Cc(n);return new Ak(JSON.parse(t),e.length+n)}xc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Sc(){for(;this.xc()<0&&!await this.Nc(););if(0===this.buffer.length)return null;var e=this.xc();e<0&&this.Dc("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Cc(e){for(;this.buffer.length<e;)await this.Nc()&&this.Dc("Reached the end of bundle when more is expected.");var t=this.vc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Dc(e){throw this.Pc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Nc(){var e=await this.Pc.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class kC{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new y_(v_.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=$I(r.It)+"/documents",i={documents:t.map(e=>VI(r.It,e))},s=await r._o("BatchGetDocuments",n,i,t.length),a=new Map;s.forEach(e=>{const t=(n=r.It,"found"in(e=e)?function(e,t){m_(!!t.found),t.found.name,t.found.updateTime;var n=BI(e,t.found.name),r=FI(t.found.updateTime),i=new Yw({mapValue:{fields:t.found.fields}});return Jw.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){m_(!!t.missing),m_(!!t.readTime);var n=BI(e,t.missing),r=FI(t.readTime);return Jw.newNoDocument(n,r)}(n,e):g_());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());m_(!!t),o.push(t)}),o}(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.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new cI(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=U_.fromPath(t);this.mutations.push(new lI(n,this.precondition(n)))}),await async function(e,t){const n=e,r=$I(n.It)+"/documents",i={writes:t.map(e=>HI(n.It,e))};await n.ao("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw g_();t=P_.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new y_(v_.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(P_.min())?Yb.exists(!1):Yb.updateTime(t):Yb.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Yb.exists(!0);if(t.isEqual(P_.min()))throw new y_(v_.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Yb.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class CC{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.kc=n.maxAttempts,this.No=new zE(this.asyncQueue,"transaction_retry")}run(){--this.kc,this.Oc()}Oc(){this.No.Ro(async()=>{const t=new kC(this.datastore),e=this.Mc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Fc(e)}))}).catch(e=>{this.Fc(e)})})}Mc(e){try{var t=this.updateFunction(e);return!Nw(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}}Fc(e){0<this.kc&&this.$c(e)?(--this.kc,this.asyncQueue.enqueueAndForget(()=>(this.Oc(),Promise.resolve()))):this.deferred.reject(e)}$c(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!hI(t)}}class SC{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=o_.UNAUTHENTICATED,this.clientId=A_.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{h_("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(h_("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new y_(v_.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new __;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=yk(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function AC(e,t){e.asyncQueue.verifyOperationInProgress(),h_("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await vE(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function NC(e,n){e.asyncQueue.verifyOperationInProgress();var t=await RC(e);h_("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>pk(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>pk(n.remoteStore,t)),e.onlineComponents=n}async function RC(e){return e.offlineComponents||(h_("FirestoreClient","Using default OfflineComponentProvider"),await AC(e,new tC)),e.offlineComponents}async function xC(e){return e.onlineComponents||(h_("FirestoreClient","Using default OnlineComponentProvider"),await NC(e,new iC)),e.onlineComponents}function DC(e){return RC(e).then(e=>e.persistence)}function PC(e){return RC(e).then(e=>e.localStore)}function OC(e){return xC(e).then(e=>e.remoteStore)}function MC(e){return xC(e).then(e=>e.syncEngine)}async function LC(e){const t=await xC(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Zk(e);let r,i;const s=n.ic.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.ec();else{const e=await bE(n.localStore,Sb(t));n.isPrimaryClient&&ek(n.remoteStore,e);const s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Uk(n,t,r,"current"===s,e.resumeToken)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ic.get(t),i=n.rc.get(r.targetId);if(1<i.length)return n.rc.set(r.targetId,i.filter(e=>!Nb(e,t))),void n.ic.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await IE(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),tk(n.remoteStore,r.targetId),zk(n,r.targetId)}).catch(Y_)):(zk(n,r.targetId),await IE(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function FC(e,t,n={}){const r=new __;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new TC({next:e=>{r.enqueueAndForget(()=>kk(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new y_(v_.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new y_(v_.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.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new Sk(bb(i.path),e,{includeMetadataChanges:!0,ku:!0});return Ek(n,o)}(await LC(e),e.asyncQueue,t,n,r)),r.promise}function UC(e,t,n={}){const r=new __;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new TC({next:e=>{n.enqueueAndForget(()=>kk(t,a)),e.fromCache&&"server"===r.source?i.reject(new y_(v_.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.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new Sk(e,s,{includeMetadataChanges:!0,ku:!0});return Ek(t,a)}(await LC(e),e.asyncQueue,t,n,r)),r.promise}function qC(e,t,n,r){const i=(n=n,t=$E(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return IC(e,void 0);if(e instanceof ArrayBuffer)return IC(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new EC(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=FI(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ns.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(xk(i));const a=new Rk(i,t.localStore,n.It);let e=await n.mc();for(;e;){const t=await a.Fu(e);t&&r._updateProgress(t),e=await n.mc()}var s=await a.complete();return await Qk(t,s.Lu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ns.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.Bu)}catch(t){return p_("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await MC(e),i,r)})}class VC{constructor(){this.Bc=Promise.resolve(),this.Lc=[],this.Uc=!1,this.qc=[],this.Kc=null,this.Gc=!1,this.Qc=!1,this.jc=[],this.No=new zE(this,"async_queue_retry"),this.Wc=()=>{var e=KE();e&&h_("AsyncQueue","Visibility state changed to "+e.visibilityState),this.No.Po()};const e=KE();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Wc)}get isShuttingDown(){return this.Uc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.zc(),this.Hc(e)}enterRestrictedMode(e){if(!this.Uc){this.Uc=!0,this.Qc=e||!1;const t=KE();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Wc)}}enqueue(e){if(this.zc(),this.Uc)return new Promise(()=>{});const t=new __;return this.Hc(()=>this.Uc&&this.Qc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Lc.push(e),this.Jc()))}async Jc(){if(0!==this.Lc.length){try{await this.Lc[0](),this.Lc.shift(),this.No.reset()}catch(e){if(!nw(e))throw e;h_("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Lc.length&&this.No.Ro(()=>this.Jc())}}Hc(e){var t=this.Bc.then(()=>(this.Gc=!0,e().catch(e=>{throw this.Kc=e,this.Gc=!1,d_("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Gc=!1,e))));return this.Bc=t}enqueueAfterDelay(e,t,n){this.zc(),-1<this.jc.indexOf(e)&&(t=0);var r=vk.createAndSchedule(this,e,t,n,e=>this.Yc(e));return this.qc.push(r),r}zc(){this.Kc&&g_()}verifyOperationInProgress(){}async Xc(){for(var e;await(e=this.Bc),e!==this.Bc;);}Zc(e){for(const t of this.qc)if(t.timerId===e)return!0;return!1}ta(t){return this.Xc().then(()=>{this.qc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.qc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Xc()})}ea(e){this.jc.push(e)}Yc(e){var t=this.qc.indexOf(e);this.qc.splice(t,1)}}function BC(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class jC{constructor(){this._progressObserver={},this._taskCompletionResolver=new __,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}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 KC,$C,zC,WC,GC;class HC extends fC{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new VC,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||YC(this),this._firestoreClient.terminate()}}function QC(e){return e._firestoreClient||YC(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function YC(e){var t,n,r,i,s,a=e._freezeSettings(),a=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",i=e._persistenceKey,s=a,new Sw(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new SC(e._authCredentials,e._appCheckCredentials,e._queue,a)}function JC(e,n,r){const i=new __;return e.asyncQueue.enqueue(async()=>{try{await AC(e,r),await NC(e,n),i.resolve()}catch(e){const n=e;if(!("FirebaseError"===(t=n).name?t.code===v_.FAILED_PRECONDITION||t.code===v_.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw n;p_("Error enabling offline persistence. Falling back to persistence disabled: "+n),i.reject(n)}var t}).then(()=>i.promise)}function XC(e){return function(e){const t=new __;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;ak(n.remoteStore)||h_("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.lc.get(e)||[];r.push(t),n.lc.set(e,r)}catch(e){const n=yk(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await MC(e),t)),t.promise}(QC(e=uC(e,HC)))}function ZC(e){return(n=QC(e=uC(e,HC))).asyncQueue.enqueue(async()=>{const e=await DC(n),t=await OC(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.wu.delete(0),XE(e)}()});var n}function eS(e){return(n=QC(e=uC(e,HC))).asyncQueue.enqueue(async()=>{const e=await DC(n),t=await OC(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.wu.add(0),await ZE(e),e.yu.set("Offline")}()});var n}function tS(t,e){return n=QC(t=uC(t,HC)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ns.getNamedQuery(e,t))}(await PC(n),r)).then(e=>e?new mC(t,null,e.query):null);var n,r}function nS(e){if(e._initialized||e._terminated)throw new y_(v_.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.")}class rS{constructor(e){this._byteString=e}static fromBase64String(e){try{return new rS(ww.fromBase64String(e))}catch(e){throw new y_(v_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new rS(ww.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 iS{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new y_(v_.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new F_(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class sS{constructor(e){this._methodName=e}}class aS{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new y_(v_.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new y_(v_.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 N_(this._lat,e._lat)||N_(this._long,e._long)}}const oS=/^__.*__$/;class cS{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new iI(e,this.data,this.fieldMask,t,this.fieldTransforms):new rI(e,this.data,t,this.fieldTransforms)}}class lS{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new iI(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function uS(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw g_()}}class hS{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.It=n,this.ignoreUndefinedProperties=r,void 0===i&&this.na(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get sa(){return this.settings.sa}ia(e){return new hS(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.It,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ra(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.ua(e),r}ca(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.na(),r}aa(e){return this.ia({path:void 0,oa:!0})}ha(e){return xS(e,this.settings.methodName,this.settings.la||!1,this.path,this.settings.fa)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}na(){if(this.path)for(let e=0;e<this.path.length;e++)this.ua(this.path.get(e))}ua(e){if(0===e.length)throw this.ha("Document fields must not be empty");if(uS(this.sa)&&oS.test(e))throw this.ha('Document fields cannot begin and end with "__"')}}class dS{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.It=n||$E(e)}da(e,t,n,r=!1){return new hS({sa:e,methodName:t,fa:n,path:F_.emptyPath(),oa:!1,la:r},this.databaseId,this.It,this.ignoreUndefinedProperties)}}function pS(e){var t=e._freezeSettings(),n=$E(e._databaseId);return new dS(e._databaseId,!!t.ignoreUndefinedProperties,n)}function fS(e,t,n,r,i,s={}){const a=e.da(s.merge||s.mergeFields?2:0,t,n,i);SS("Data must be an object, but it was:",a,r);var o=kS(r,a);let c,l;if(s.merge)c=new _w(a.fieldMask),l=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=AS(t,r,n);if(!a.contains(i))throw new y_(v_.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);DS(e,i)||e.push(i)}c=new _w(e),l=a.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=a.fieldTransforms;return new cS(new Yw(o),c,l)}class gS extends sS{_toFieldTransform(e){if(2!==e.sa)throw 1===e.sa?e.ha(`${this._methodName}() can only appear at the top level of your update data`):e.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof gS}}function mS(e,t,n){return new hS({sa:3,fa:t.settings.fa,methodName:e._methodName,oa:n},t.databaseId,t.It,t.ignoreUndefinedProperties)}class vS extends sS{_toFieldTransform(e){return new Hb(e.path,new Vb)}isEqual(e){return e instanceof vS}}class yS extends sS{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=mS(this,e,!0),n=this._a.map(e=>ES(e,t)),r=new Bb(n);return new Hb(e.path,r)}isEqual(e){return this===e}}class _S extends sS{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=mS(this,e,!0),n=this._a.map(e=>ES(e,t)),r=new Kb(n);return new Hb(e.path,r)}isEqual(e){return this===e}}class wS extends sS{constructor(e,t){super(e),this.wa=t}_toFieldTransform(e){var t=new zb(e.It,Fb(e.It,this.wa));return new Hb(e.path,t)}isEqual(e){return this===e}}function bS(e,i,s,t){const a=e.da(1,i,s);SS("Data must be an object, but it was:",a,t);const o=[],c=Yw.empty();hw(t,(e,t)=>{var n=RS(i,e,s);t=ae(t);var r=a.ca(n);if(t instanceof gS)o.push(n);else{const e=ES(t,r);null!=e&&(o.push(n),c.set(n,e))}});var n=new _w(o);return new lS(c,n,a.fieldTransforms)}function IS(e,t,n,r,i,s){const a=e.da(1,t,n),o=[AS(t,r,n)],c=[i];if(s.length%2!=0)throw new y_(v_.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(AS(t,s[p])),c.push(s[p+1]);const l=[],u=Yw.empty();for(let f=o.length-1;0<=f;--f)if(!DS(l,o[f])){const t=o[f];var h=ae(h=c[f]);const r=a.ca(t);if(h instanceof gS)l.push(t);else{const e=ES(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new _w(l);return new lS(u,d,a.fieldTransforms)}function TS(e,t,n,r=!1){return ES(n,e.da(r?4:3,t))}function ES(s,e){if(CS(s=ae(s)))return SS("Unsupported field value:",e,s),kS(s,e);if(s instanceof sS)return function(e,t){if(!uS(t.sa))throw t.ha(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ha(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(s,e),null;if(void 0===s&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),s instanceof Array){if(e.settings.oa&&4!==e.sa)throw e.ha("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=ES(i,t.aa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=ae(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Fb(t.It,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=D_.fromDate(e);return{timestampValue:MI(t.It,n)}}if(e instanceof D_){n=new D_(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:MI(t.It,n)}}if(e instanceof aS)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof rS)return{bytesValue:LI(t.It,e._byteString)};if(e instanceof gC){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.ha(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:UI(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ha(`Unsupported field value: ${lC(e)}`)}(0,e)}function kS(e,r){const i={};return dw(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):hw(e,(e,t)=>{var n=ES(t,r.ra(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function CS(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof D_||e instanceof aS||e instanceof rS||e instanceof gC||e instanceof sS)}function SS(e,t,n){if(!CS(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=lC(n);throw"an object"===r?t.ha(e+" a custom object"):t.ha(e+" "+r)}var i}function AS(e,t,n){if((t=ae(t))instanceof iS)return t._internalPath;if("string"==typeof t)return RS(e,t);throw xS("Field path arguments must be of type string or ",e,!1,void 0,n)}const NS=new RegExp("[~\\*/\\[\\]]");function RS(t,n,r){if(0<=n.search(NS))throw xS(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new iS(...n.split("."))._internalPath}catch(e){throw xS(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function xS(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let c="";return(s||a)&&(c+=" (found",s&&(c+=` in field ${r}`),a&&(c+=` in document ${i}`),c+=")"),new y_(v_.INVALID_ARGUMENT,o+e+c)}function DS(e,t){return e.some(e=>e.isEqual(t))}class PS{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new gC(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new OS(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(MS("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class OS extends PS{data(){return super.data()}}function MS(e,t){return"string"==typeof t?RS(e,t):(t instanceof iS?t:t._delegate)._internalPath}function LS(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new y_(v_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class FS{}function US(e,...t){for(const n of t)e=n._apply(e);return e}class qS extends FS{constructor(e,t,n){super(),this.ma=e,this.ga=t,this.ya=n,this.type="where"}_apply(e){var t=pS(e.firestore),t=function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new y_(v_.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){WS(a,s);const t=[];for(const n of a)t.push(zS(r,e,n));o={arrayValue:{values:t}}}else o=zS(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||WS(a,s),o=TS(n,t,a,"in"===s||"not-in"===s);var c=ab.create(i,s,o);return function(e,t){if(t.dt()){const r=Eb(e);if(null!==r&&!r.isEqual(t.field))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${t.field.toString()}'`);var n=Tb(e);null!==n&&GS(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new y_(v_.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new y_(v_.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,c),c}(e._query,"where",t,e.firestore._databaseId,this.ma,this.ga,this.ya);return new mC(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new _b(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class VS extends FS{constructor(e,t){super(),this.ma=e,this.pa=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new y_(v_.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new y_(v_.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new mb(t,n);return n=i,null!==Tb(e=e)||null!==(r=Eb(e))&&GS(0,r,n.field),i}(e._query,this.ma,this.pa);return new mC(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new _b(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class BS extends FS{constructor(e,t,n){super(),this.type=e,this.Ia=t,this.Ta=n}_apply(e){return new mC(e.firestore,e.converter,Ab(e._query,this.Ia,this.Ta))}}class jS extends FS{constructor(e,t,n){super(),this.type=e,this.Ea=t,this.Aa=n}_apply(e){var t,n=$S(e,this.type,this.Ea,this.Aa);return new mC(e.firestore,e.converter,(t=e._query,e=n,new _b(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class KS extends FS{constructor(e,t,n){super(),this.type=e,this.Ea=t,this.Aa=n}_apply(e){var t,n=$S(e,this.type,this.Ea,this.Aa);return new mC(e.firestore,e.converter,(t=e._query,e=n,new _b(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function $S(e,t,n,r){if(n[0]=ae(n[0]),n[0]instanceof PS)return function(e,t,n,r,i){if(!r)throw new y_(v_.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Cb(e))if(n.field.isKeyField())s.push(Vw(t,r.key));else{const e=r.data.field(n.field);if(kw(e))throw new y_(v_.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.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){const e=n.field.canonicalString();throw new y_(v_.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.`)}s.push(e)}return new gb(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=pS(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new y_(v_.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let c=0;c<i.length;c++){const l=i[c];if(a[c].field.isKeyField()){if("string"!=typeof l)throw new y_(v_.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!kb(e)&&-1!==l.indexOf("/"))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(M_.fromString(l));if(!U_.isDocumentKey(n))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new U_(n);o.push(Vw(t,i))}else{const e=TS(n,r,l);o.push(e)}}return new gb(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function zS(e,t,n){if("string"==typeof(n=ae(n))){if(""===n)throw new y_(v_.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!kb(t)&&-1!==n.indexOf("/"))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(M_.fromString(n));if(!U_.isDocumentKey(r))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Vw(e,new U_(r))}if(n instanceof gC)return Vw(e,n._key);throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${lC(n)}.`)}function WS(e,t){if(!Array.isArray(e)||0===e.length)throw new y_(v_.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new y_(v_.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function GS(e,t,n){if(!n.isEqual(t))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class HS{convertValue(e,t="none"){switch(Ow(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Tw(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(Ew(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 10:return this.convertObject(e.mapValue,t);default:throw g_()}}convertObject(e,n){const r={};return hw(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new aS(Tw(e.latitude),Tw(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return kw(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Cw(e));default:return null}}convertTimestamp(e){var t=Iw(e);return new D_(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=M_.fromString(e);m_(rT(n));const r=new Aw(n.get(1),n.get(3)),i=new U_(n.popFirst(5));return r.isEqual(t)||d_(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function QS(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class YS extends HS{constructor(e){super(),this.firestore=e}convertBytes(e){return new rS(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new gC(this.firestore,null,t)}}class JS{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class XS extends PS{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new ZS(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(MS("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class ZS extends XS{data(e={}){return super.data(e)}}class eA{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new JS(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new ZS(this._firestore,this._userDataWriter,e.key,e,new JS(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 y_(v_.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=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let t=0;return s._snapshot.docChanges.map(e=>({type:"added",doc:new ZS(s._firestore,s._userDataWriter,e.doc.key,e.doc,new JS(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter),oldIndex:-1,newIndex:t++}))}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new ZS(s._firestore,s._userDataWriter,e.doc.key,e.doc,new JS(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return g_()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function tA(e,t){return e instanceof XS&&t instanceof XS?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 eA&&t instanceof eA&&e._firestore===t._firestore&&bC(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class nA extends HS{constructor(e){super(),this.firestore=e}convertBytes(e){return new rS(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new gC(this.firestore,null,t)}}function rA(t){t=uC(t,gC);const n=uC(t.firestore,HC),e=QC(n),r=new nA(n);return function(e,t){const n=new __;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new y_(v_.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){var r=yk(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await PC(e),t,n)),n.promise}(e,t._key).then(e=>new XS(n,r,t._key,e,new JS(null!==e&&e.hasLocalMutations,!0),t.converter))}function iA(t){t=uC(t,mC);const n=uC(t.firestore,HC),e=QC(n),r=new nA(n);return function(e,t){const n=new __;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await TE(e,t,!0),s=new Ok(t,i.Hi),a=s.Wu(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=yk(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await PC(e),t,n)),n.promise}(e,t._query).then(e=>new eA(n,r,t,e))}function sA(e,t,n){e=uC(e,gC);var r=uC(e.firestore,HC),i=QS(e.converter,t,n);return lA(r,[fS(pS(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Yb.none())])}function aA(e,t,n,...r){e=uC(e,gC);var i=uC(e.firestore,HC),s=pS(i);let a;return a="string"==typeof(t=ae(t))||t instanceof iS?IS(s,"updateDoc",e._key,t,n,r):bS(s,"updateDoc",e._key,t),lA(i,[a.toMutation(e._key,Yb.exists(!0))])}function oA(t,...n){var e;t=ae(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||BC(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(BC(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,c;if(t instanceof gC)o=uC(t.firestore,HC),c=bb(t._key.path),a={next:e=>{n[i]&&n[i](uA(o,t,e))},error:n[i+1],complete:n[i+2]};else{const l=uC(t,mC);o=uC(l.firestore,HC),c=l._query;const u=new nA(o);a={next:e=>{n[i]&&n[i](new eA(o,u,l,e))},error:n[i+1],complete:n[i+2]},LS(t._query)}return function(e,t,n,r){const i=new TC(r),s=new Sk(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Ek(await LC(e),s)),()=>{i.bc(),e.asyncQueue.enqueueAndForget(async()=>kk(await LC(e),s))}}(QC(o),c,s,a)}function cA(e,t){return function(e,t){const n=new TC(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.bu.add(t),t.next()}(await LC(e),n)),()=>{n.bc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.bu.delete(t)}(await LC(e),n))}}(QC(e=uC(e,HC)),BC(t)?t:{next:t})}function lA(e,t){return function(e,t){const n=new __;return e.asyncQueue.enqueueAndForget(async()=>qk(await MC(e),t,n)),n.promise}(QC(e),t)}function uA(e,t,n){var r=n.docs.get(t._key),i=new nA(e);return new XS(e,i,t._key,r,new JS(n.hasPendingWrites,n.fromCache),t.converter)}const hA={maxAttempts:5};class dA{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=pS(e)}set(e,t,n){this._verifyNotCommitted();const r=pA(e,this._firestore),i=QS(r.converter,t,n),s=fS(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Yb.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=pA(e,this._firestore);let s;return s="string"==typeof(t=ae(t))||t instanceof iS?IS(this._dataReader,"WriteBatch.update",i._key,t,n,r):bS(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Yb.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=pA(e,this._firestore);return this._mutations=this._mutations.concat(new cI(t._key,Yb.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 y_(v_.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function pA(e,t){if((e=ae(e)).firestore!==t)throw new y_(v_.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class fA extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=pS(e)}get(e){const n=pA(e,this._firestore),r=new YS(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return g_();const t=e[0];if(t.isFoundDocument())return new PS(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new PS(this._firestore,r,n._key,null,n.converter);throw g_()})}set(e,t,n){var r=pA(e,this._firestore),i=QS(r.converter,t,n),i=fS(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=pA(e,this._firestore),s="string"==typeof(t=ae(t))||t instanceof iS?IS(this._dataReader,"Transaction.update",i._key,t,n,r):bS(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=pA(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=pA(e,this._firestore),n=new nA(this._firestore);return super.get(e).then(e=>new XS(this._firestore,n,t._key,e._document,new JS(!1,!1),t.converter))}}function gA(t,n,e){t=uC(t,HC);var r=Object.assign(Object.assign({},hA),e);return function(){if(r.maxAttempts<1)throw new y_(v_.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(t,n,r){const i=new __;return t.asyncQueue.enqueueAndForget(async()=>{var e=await xC(t).then(e=>e.datastore);new CC(t.asyncQueue,e,r,n,i).run()}),i.promise}(QC(t),e=>n(new fA(t,e)),r)}KC=Ye,c_=KC,We(new oe("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new HC(new T_(e.getProvider("auth-internal")),new S_(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new y_(v_.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Aw(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:!0},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),et(a_,"3.7.1",void 0),et(a_,"3.7.1","esm2017");function mA(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new y_("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function vA(){if("undefined"==typeof Uint8Array)throw new y_("unimplemented","Uint8Arrays are not available in this environment.")}function yA(){if("undefined"==typeof atob)throw new y_("unimplemented","Blobs are unavailable in Firestore in this environment.")}class _A{constructor(e){this._delegate=e}static fromBase64String(e){return yA(),new _A(rS.fromBase64String(e))}static fromUint8Array(e){return vA(),new _A(rS.fromUint8Array(e))}toBase64(){return yA(),this._delegate.toBase64()}toUint8Array(){return vA(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function wA(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class bA{enableIndexedDbPersistence(e,t){return function(e,t){nS(e=uC(e,HC));var n=QC(e),r=e._freezeSettings(),i=new iC;return JC(n,i,new nC(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){nS(e=uC(e,HC));var t=QC(e),n=e._freezeSettings(),r=new iC;return JC(t,r,new rC(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new y_(v_.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new __;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Z_.C())return Promise.resolve();var t=e+"main";await Z_.delete(t)}(dE(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class IA{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Aw||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||p_("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(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=uC(n,fC))._getSettings();if("firestore.googleapis.com"!==s.host&&s.host!==e&&p_("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},s),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=o_.MOCK_USER;else{e=N(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new y_(v_.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new o_(s)}n._authCredentials=new I_(new w_(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return ZC(this._delegate)}disableNetwork(){return eS(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,aC("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return XC(this._delegate)}onSnapshotsInSync(e){return cA(this._delegate,e)}get app(){if(!this._appCompat)throw new y_("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new LA(this,yC(this._delegate,e))}catch(e){throw AA(e,"collection()","Firestore.collection()")}}doc(e){try{return new SA(this,_C(this._delegate,e))}catch(e){throw AA(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new PA(this,function(e,t){if(e=uC(e,fC),sC("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new y_(v_.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new mC(e,null,(t=t,new _b(M_.emptyPath(),t)))}(this._delegate,e))}catch(e){throw AA(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return gA(this._delegate,e=>t(new EA(this,e)))}batch(){return QC(this._delegate),new kA(new dA(this._delegate,e=>lA(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=QC(t=uC(t,HC)),r=new jC,qC(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return tS(this._delegate,e).then(e=>e?new PA(this,e):null)}}class TA extends HS{constructor(e){super(),this.firestore=e}convertBytes(e){return new _A(new rS(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return SA.forKey(t,this.firestore,null)}}class EA{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new TA(e)}get(e){const t=FA(e);return this._delegate.get(t).then(e=>new xA(this._firestore,new XS(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=FA(e);return n?(mA("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=FA(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=FA(e);return this._delegate.delete(t),this}}class kA{constructor(e){this._delegate=e}set(e,t,n){var r=FA(e);return n?(mA("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=FA(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=FA(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class CA{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new ZS(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new DA(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=CA.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new CA(e,new TA(e),t),r.set(t,i)),i}}CA.INSTANCES=new WeakMap;class SA{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new TA(e)}static forPath(e,t,n){if(e.length%2!=0)throw new y_("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new SA(t,new gC(t._delegate,n,new U_(e)))}static forKey(e,t,n){return new SA(t,new gC(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new LA(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new LA(this.firestore,yC(this._delegate,e))}catch(e){throw AA(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=ae(e))instanceof gC&&wC(this._delegate,e)}set(e,t){t=mA("DocumentReference.set",t);try{return t?sA(this._delegate,e,t):sA(this._delegate,e)}catch(e){throw AA(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?aA(this._delegate,e):aA(this._delegate,e,t,...n)}catch(e){throw AA(e,"updateDoc()","DocumentReference.update()")}}delete(){return lA(uC((e=this._delegate).firestore,HC),[new cI(e._key,Yb.none())]);var e}onSnapshot(...e){var t=NA(e),n=RA(e,e=>new xA(this.firestore,new XS(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return oA(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?rA:"server"===(null==e?void 0:e.source)?function(t){t=uC(t,gC);const n=uC(t.firestore,HC);return FC(QC(n),t._key,{source:"server"}).then(e=>uA(n,t,e))}:function(t){t=uC(t,gC);const n=uC(t.firestore,HC);return FC(QC(n),t._key).then(e=>uA(n,t,e))})(this._delegate),t.then(e=>new xA(this.firestore,new XS(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new SA(this.firestore,e?this._delegate.withConverter(CA.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function AA(e,t,n){return e.message=e.message.replace(t,n),e}function NA(e){for(const t of e)if("object"==typeof t&&!wA(t))return t;return{}}function RA(e,t){var n;let r;return r=wA(e[0])?e[0]:wA(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=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class xA{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new SA(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 tA(this._delegate,e._delegate)}}class DA extends xA{data(e){var t=this._delegate.data(e);return void 0!==t||g_(),t}}class PA{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new TA(e)}where(e,t,n){try{return new PA(this.firestore,US(this._delegate,(r=n,i=t,s=MS("where",e),new qS(s,i,r))))}catch(e){throw AA(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new PA(this.firestore,US(this._delegate,([n,r="asc"]=[e,t],i=r,s=MS("orderBy",n),new VS(s,i))))}catch(e){throw AA(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new PA(this.firestore,US(this._delegate,(hC("limit",t=e),new BS("limit",t,"F"))))}catch(e){throw AA(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new PA(this.firestore,US(this._delegate,(hC("limitToLast",t=e),new BS("limitToLast",t,"L"))))}catch(e){throw AA(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new PA(this.firestore,US(this._delegate,function(...e){return new jS("startAt",e,!0)}(...e)))}catch(e){throw AA(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new PA(this.firestore,US(this._delegate,function(...e){return new jS("startAfter",e,!1)}(...e)))}catch(e){throw AA(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new PA(this.firestore,US(this._delegate,function(...e){return new KS("endBefore",e,!1)}(...e)))}catch(e){throw AA(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new PA(this.firestore,US(this._delegate,function(...e){return new KS("endAt",e,!0)}(...e)))}catch(e){throw AA(e,"endAt()","Query.endAt()")}}isEqual(e){return bC(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?iA:"server"===(null==e?void 0:e.source)?function(t){t=uC(t,mC);const n=uC(t.firestore,HC),e=QC(n),r=new nA(n);return UC(e,t._query,{source:"server"}).then(e=>new eA(n,r,t,e))}:function(t){t=uC(t,mC);const n=uC(t.firestore,HC),e=QC(n),r=new nA(n);return LS(t._query),UC(e,t._query).then(e=>new eA(n,r,t,e))})(this._delegate),t.then(e=>new MA(this.firestore,new eA(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=NA(e),n=RA(e,e=>new MA(this.firestore,new eA(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return oA(this._delegate,t,n)}withConverter(e){return new PA(this.firestore,e?this._delegate.withConverter(CA.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class OA{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new DA(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class MA{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new PA(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 DA(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new OA(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new DA(this._firestore,e))})}isEqual(e){return tA(this._delegate,e._delegate)}}class LA extends PA{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 SA(this.firestore,e):null}doc(e){try{return void 0===e?new SA(this.firestore,_C(this._delegate)):new SA(this.firestore,_C(this._delegate,e))}catch(e){throw AA(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=uC(e.firestore,HC),r=_C(e),i=QS(e.converter,t);return lA(n,[fS(pS(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Yb.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new SA(this.firestore,e))}isEqual(e){return wC(this._delegate,e._delegate)}withConverter(e){return new LA(this.firestore,e?this._delegate.withConverter(CA.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function FA(e){return uC(e,gC)}const UA={Firestore:IA,GeoPoint:aS,Timestamp:D_,Blob:_A,Transaction:EA,WriteBatch:kA,DocumentReference:SA,DocumentSnapshot:xA,Query:PA,QueryDocumentSnapshot:DA,QuerySnapshot:MA,CollectionReference:LA,FieldPath:class $P{constructor(...e){this._delegate=new iS(...e)}static documentId(){return new $P(F_.keyField().canonicalString())}isEqual(e){return(e=ae(e))instanceof iS&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class zP{constructor(e){this._delegate=e}static serverTimestamp(){const e=new vS("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new zP(e)}static delete(){const e=new gS("deleteField");return e._methodName="FieldValue.delete",new zP(e)}static arrayUnion(...e){const t=function(...e){return new yS("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new zP(t)}static arrayRemove(...e){const t=function(...e){return new _S("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new zP(t)}static increment(e){const t=new wS("increment",e);return t._methodName="FieldValue.increment",new zP(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,l_.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};$C=wt,zC=(e,t)=>new IA(e,t,new bA),$C.INTERNAL.registerComponent(new oe("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return zC(t,n)},"PUBLIC").setServiceProps(Object.assign({},UA))),$C.registerVersion("@firebase/firestore-compat","0.2.1");const qA="type.googleapis.com/google.protobuf.Int64Value",VA="type.googleapis.com/google.protobuf.UInt64Value";function BA(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function jA(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case qA:case VA: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=>jA(e)):"function"==typeof e||"object"==typeof e?BA(e,e=>jA(e)):e}const KA="functions",$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 zA extends R{constructor(e,t,n){super(`${KA}/${e}`,t||""),this.details=n}}function WA(e,t){let n=function(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),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!$A[e])return new zA("internal","internal");n=$A[e],r=e}var a=s.message;"string"==typeof a&&(r=a),i=s.details,void 0!==i&&(i=jA(i))}}catch(e){}return"ok"===n?null:new zA(n,r,i)}class GA{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||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){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){var e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const HA="us-central1";class QA{constructor(e,t,n,r,i=HA,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new GA(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var a=new URL(i);this.customDomain=a.origin,this.region=HA}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function YA(i,s,a){return e=>{return t=e,n=a||{},r=(e=i)._url(s),JA(e,r,t,n);var t,n,r}}async function JA(e,t,n,r){var i={data:n=function t(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=>t(e));if("function"==typeof e||"object"==typeof e)return BA(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)};const s={};var a=await e.contextProvider.getContext();a.authToken&&(s.Authorization="Bearer "+a.authToken),a.messagingToken&&(s["Firebase-Instance-ID-Token"]=a.messagingToken),null!==a.appCheckToken&&(s["X-Firebase-AppCheck"]=a.appCheckToken);const o=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new zA("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(r.timeout||7e4);a=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}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),o.promise,e.cancelAllRequests]);if(o.cancel(),!a)throw new zA("cancelled","Firebase Functions instance was deleted.");i=WA(a.status,a.json);if(i)throw i;if(!a.json)throw new zA("internal","Response is not valid JSON object.");let c=a.json.data;if(void 0===c&&(c=a.json.result),void 0===c)throw new zA("internal","Response is missing data field.");return{data:jA(c)}}const XA="@firebase/functions";function ZA(e,t,n){ae(e).emulatorOrigin=`http://${t}:${n}`}function eN(e,t,n){return r=ae(e),i=t,s=n,e=>JA(r,i,e,s||{});var r,i,s}WC=fetch.bind(self),We(new oe(KA,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new QA(n,r,i,s,t,WC)},"PUBLIC").setMultipleInstances(!0)),et(XA,"0.8.7",GC),et(XA,"0.8.7","esm2017");var tN,nN,rN,iN;class sN{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return YA(ae(this._delegate),e,t)}httpsCallableFromURL(e,t){return eN(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new R("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new R("functions","Port missing in origin provided to useFunctionsEmulator()");return ZA(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return ZA(this._delegate,e,t)}}const aN="us-central1",oN=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:aN});return new sN(n,r)};tN={Functions:sN},wt.INTERNAL.registerComponent(new oe("functions-compat",oN,"PUBLIC").setServiceProps(tN).setMultipleInstances(!0)),wt.registerVersion("@firebase/functions-compat","0.2.7");const cN="/firebase-messaging-sw.js",lN="/firebase-cloud-messaging-push-scope",uN="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",hN="https://fcmregistrations.googleapis.com/v1",dN="google.c.a.c_id",pN="google.c.a.e";function fN(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(Wc=CD=CD||{})[Wc.DATA_MESSAGE=1]="DATA_MESSAGE",Wc[Wc.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(Wc=nN=nN||{}).PUSH_RECEIVED="push-received",Wc.NOTIFICATION_CLICKED="notification-clicked";const gN="fcm_token_details_db",mN="fcm_token_object_Store";async function vN(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(gN))return null}let l=null;const e=await Re(gN,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(mN)){const o=r.objectStore(mN);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:fN(s.vapidKey)}}):3===t?(s=a,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=a,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)}}))}}});return e.close(),await xe(gN),await xe("fcm_vapid_details_db"),await xe("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"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}const yN="firebase-messaging-database",_N=1,wN="firebase-messaging-store";let bN=null;function IN(){return bN=bN||Re(yN,_N,{upgrade:(e,t)=>{0===t&&e.createObjectStore(wN)}}),bN}async function TN(e){var t=kN(e);const n=await IN();t=await n.transaction(wN).objectStore(wN).get(t);if(t)return t;t=await vN(e.appConfig.senderId);return t?(await EN(e,t),t):void 0}async function EN(e,t){var n=kN(e);const r=await IN(),i=r.transaction(wN,"readwrite");return await i.objectStore(wN).put(t,n),await i.done,t}function kN({appConfig:e}){return e.appId}const CN=new x("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 n={method:"DELETE",headers:await NN(e)};try{const s=await fetch(`${AN(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw CN.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw CN.create("token-unsubscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}}function AN({projectId:e}){return`${hN}/projects/${e}/registrations`}async function NN({appConfig:e,installations:t}){var n=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 ${n}`})}function RN({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==uN&&(i.web.applicationPubKey=r),i}const xN=6048e5;async function DN(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:fN(t.getKey("auth")),p256dh:fN(t.getKey("p256dh"))},c=await TN(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+xN?async function(t,e){try{var n=await async function(e,t){var n=await NN(e),r=RN(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${AN(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw CN.create("token-update-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw CN.create("token-update-failed",{errorInfo:r})}if(!i.token)throw CN.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await EN(t.firebaseDependencies,r),n}catch(e){throw await PN(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await SN(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return ON(e.firebaseDependencies,o)}return ON(e.firebaseDependencies,o)}async function PN(e){var t=await TN(e.firebaseDependencies);t&&(await SN(e.firebaseDependencies,t.token),await async function(e){var t=kN(e);const n=await IN(),r=n.transaction(wN,"readwrite");await r.objectStore(wN).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function ON(e,t){var n={token:await async function(e,t){var n=await NN(e),r=RN(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(AN(e.appConfig),r);i=await s.json()}catch(e){throw CN.create("token-subscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw CN.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw CN.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await EN(e,n),n.token}function MN(e){var t,n,r,i,s,a={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return r=a,(n=e).notification&&(r.notification={},(t=n.notification.title)&&(r.notification.title=t),(t=n.notification.body)&&(r.notification.body=t),(t=n.notification.image)&&(r.notification.image=t)),n=a,(r=e).data&&(n.data=r.data),r=a,((e=e).fcmOptions||null!==(i=e.notification)&&void 0!==i&&i.click_action)&&(r.fcmOptions={},(s=null!==(i=null===(i=e.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=e.notification)||void 0===s?void 0:s.click_action)&&(r.fcmOptions.link=s),(s=null===(s=e.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(r.fcmOptions.analyticsLabel=s)),a}function LN(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function FN(e){return CN.create("missing-app-config-values",{valueName:e})}LN("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),LN("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class UN{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw FN("App Configuration Object");if(!e.name)throw FN("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw FN(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function qN(e){try{e.swRegistration=await navigator.serviceWorker.register(cN,{scope:lN}),e.swRegistration.update().catch(()=>{})}catch(e){throw CN.create("failed-service-worker-registration",{browserErrorMessage:null===e||void 0===e?void 0:e.message})}}async function VN(e,t){if(!navigator)throw CN.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw CN.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=uN)),await async function(e,t){if(t||e.swRegistration||await qN(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw CN.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),DN(e)}async function BN(e,t,n){var r=function(e){switch(e){case nN.NOTIFICATION_CLICKED:return"notification_open";case nN.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[dN],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function jN(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===nN.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(MN(r)):e.onMessageHandler.next(MN(r))),n=r.data,"object"==typeof(t=n)&&t&&dN in t&&"1"===n[pN]&&await BN(e,r.messageType,n))}const KN="@firebase/messaging",$N=e=>{const t=new UN(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>jN(t,e)),t},zN=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>VN(t,e)}};function WN(e){return async function(e){if(!navigator)throw CN.create("only-available-in-window");return e.swRegistration||await qN(e),PN(e)}(e=ae(e))}function GN(e,t){return function(e,t){if(!navigator)throw CN.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=ae(e),t)}We(new oe("messaging",$N,"PUBLIC")),We(new oe("messaging-internal",zN,"PRIVATE")),et(KN,"0.9.19"),et(KN,"0.9.19","esm2017");const HN="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",QN="https://fcmregistrations.googleapis.com/v1",YN="FCM_MSG",JN="google.c.a.c_id",XN=3,ZN=1;function eR(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(Wc=rN=rN||{})[Wc.DATA_MESSAGE=1]="DATA_MESSAGE",Wc[Wc.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(It=iN=iN||{}).PUSH_RECEIVED="push-received",It.NOTIFICATION_CLICKED="notification-clicked";const tR="fcm_token_details_db",nR="fcm_token_object_Store";async function rR(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(tR))return null}let l=null;const e=await Re(tR,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(nR)){const o=r.objectStore(nR);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:eR(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:eR(s.auth),p256dh:eR(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:eR(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:eR(a.auth),p256dh:eR(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:eR(a.vapidKey)}}))}}});return e.close(),await xe(tR),await xe("fcm_vapid_details_db"),await xe("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"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}const iR="firebase-messaging-database",sR=1,aR="firebase-messaging-store";let oR=null;function cR(){return oR=oR||Re(iR,sR,{upgrade:(e,t)=>{0===t&&e.createObjectStore(aR)}}),oR}async function lR(e){var t=hR(e);const n=await cR();t=await n.transaction(aR).objectStore(aR).get(t);if(t)return t;t=await rR(e.appConfig.senderId);return t?(await uR(e,t),t):void 0}async function uR(e,t){var n=hR(e);const r=await cR(),i=r.transaction(aR,"readwrite");return await i.objectStore(aR).put(t,n),await i.done,t}function hR({appConfig:e}){return e.appId}const dR=new x("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 pR(e,t){var n={method:"DELETE",headers:await gR(e)};try{const s=await fetch(`${fR(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw dR.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw dR.create("token-unsubscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}}function fR({projectId:e}){return`${QN}/projects/${e}/registrations`}async function gR({appConfig:e,installations:t}){var n=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 ${n}`})}function mR({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==HN&&(i.web.applicationPubKey=r),i}async function vR(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:eR(t.getKey("auth")),p256dh:eR(t.getKey("p256dh"))},c=await lR(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await gR(e),r=mR(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${fR(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw dR.create("token-update-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw dR.create("token-update-failed",{errorInfo:r})}if(!i.token)throw dR.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await uR(t.firebaseDependencies,r),n}catch(e){throw await yR(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await pR(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return _R(e.firebaseDependencies,o)}return _R(e.firebaseDependencies,o)}async function yR(e){var t=await lR(e.firebaseDependencies);t&&(await pR(e.firebaseDependencies,t.token),await async function(e){var t=hR(e);const n=await cR(),r=n.transaction(aR,"readwrite");await r.objectStore(aR).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function _R(e,t){var n={token:await async function(e,t){var n=await gR(e),r=mR(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(fR(e.appConfig),r);i=await s.json()}catch(e){throw dR.create("token-subscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw dR.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw dR.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await uR(e,n),n.token}async function wR(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=rN.DISPLAY_NOTIFICATION.toString():r.message_type=rN.DATA_MESSAGE.toString();r.sdk_platform=XN.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=ZN.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function bR(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function IR(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await wR(t,n);var r,i,s,a,o=await ER();if(o.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=iN.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(o,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[YN]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(a={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},o=a,(e=r).notification&&(o.notification={},(n=e.notification.title)&&(o.notification.title=n),(n=e.notification.body)&&(o.notification.body=n),(n=e.notification.image)&&(o.notification.image=n)),e=a,(o=r).data&&(e.data=o.data),o=a,((r=r).fcmOptions||null!==(i=r.notification)&&void 0!==i&&i.click_action)&&(o.fcmOptions={},(s=null!==(i=null===(i=r.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=r.notification)||void 0===s?void 0:s.click_action)&&(o.fcmOptions.link=s),(s=null===(s=r.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(o.fcmOptions.analyticsLabel=s)),a=a,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(a):t.onBackgroundMessageHandler.next(a))}}async function TR(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[YN];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&JN in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await ER();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=iN.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function ER(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function kR(e){return dR.create("missing-app-config-values",{valueName:e})}bR("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),bR("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class CR{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw kR("App Configuration Object");if(!e.name)throw kR("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw kR(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const SR=e=>{const t=new CR(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(IR(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await lR(t.firebaseDependencies),await yR(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:HN,await vR(t)):await yR(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(TR(e))}),t};function AR(e,t){return function(e,t){if(void 0!==self.document)throw dR.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=ae(e),t)}We(new oe("messaging-sw",SR,"PUBLIC"));var NR,RR,xR;class DR{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return VN(e=ae(e),t)}(this._delegate,e)}async deleteToken(){return WN(this._delegate)}onMessage(e){return GN(this._delegate,e)}onBackgroundMessage(e){return AR(this._delegate,e)}}const PR=e=>self&&"ServiceWorkerGlobalScope"in self?new DR(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new DR(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),OR={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?v()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&v()&&_()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};wt.INTERNAL.registerComponent(new oe("messaging-compat",PR,"PUBLIC").setServiceProps(OR)),wt.registerVersion("@firebase/messaging-compat","0.1.19");const MR="firebasestorage.googleapis.com",LR="storageBucket";class FR extends R{constructor(e,t,n=0){super(UR(e),`Firebase Storage: ${t} (${UR(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,FR.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return UR(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function UR(e){return"storage/"+e}function qR(){return new FR("unknown","An unknown error occurred, please check the error payload for server response.")}function VR(){return new FR("retry-limit-exceeded","Max retry time for operation exceeded, please try again.")}function BR(){return new FR("canceled","User canceled the upload/download.")}function jR(){return new FR("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function KR(e){return new FR("invalid-argument",e)}function $R(){return new FR("app-deleted","The Firebase app was deleted.")}function zR(e){return new FR("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 WR(e,t){return new FR("invalid-format","String does not match format '"+e+"': "+t)}function GR(e){throw new FR("internal-error","Internal error: "+e)}class HR{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=HR.makeFromUrl(t,e)}catch(e){return new HR(t,"")}if(""===n.path)return n;throw t=t,new FR("invalid-default-bucket","Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),o=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),a=t===MR?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{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:o,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${a}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new HR(u,e),d.postModify(n);break}}if(null==n)throw t=e,new FR("invalid-url","Invalid URL '"+t+"'.");return n}}class QR{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function YR(e){return"string"==typeof e||e instanceof String}function JR(e){return XR()&&e instanceof Blob}function XR(){return"undefined"!=typeof Blob}function ZR(e,t,n,r){if(r<t)throw KR(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw KR(`Invalid value for '${e}'. Expected ${n} or less.`)}function ex(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function tx(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}function nx(e,t){var n=500<=e&&e<600,r=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return n||r||i}(It=NR=NR||{})[It.NO_ERROR=0]="NO_ERROR",It[It.NETWORK_ERROR=1]="NETWORK_ERROR",It[It.ABORT=2]="ABORT";class rx{constructor(e,t,n,r,i,s,a,o,c,l,u,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=a,this.errorCallback_=o,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.retry=h,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=(r,e)=>{if(e)r(!1,new ix(!1,null,!0));else{const i=this.connectionFactory_();this.pendingConnection_=i;const s=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&i.addUploadProgressListener(s),i.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&i.removeUploadProgressListener(s),this.pendingConnection_=null;var e,t=i.getErrorCode()===NR.NO_ERROR,n=i.getStatus();t&&!nx(n,this.additionalRetryCodes_)||!this.retry?(e=-1!==this.successCodes_.indexOf(n),r(!0,new ix(e,i))):(e=i.getErrorCode()===NR.ABORT,r(!1,new ix(!1,null,e)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const o=qR();o.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,o)):r(o)}else{var a;t.canceled?(a=(this.appDelete_?$R:BR)(),r(a)):(a=VR(),r(a))}};this.canceled_?t(0,new ix(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,a=!1,o=0;function c(){return 2===o}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(p,c())},e)}function d(){s&&clearTimeout(s)}function p(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||a)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===o?(o=2,0):1e3*(r+Math.random()),h(e)}}let f=!1;function g(e){f||(f=!0,d(),l||(null!==i?(e||(o=2),clearTimeout(i),h(0)):e||(o=1)))}return h(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 ix{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function sx(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(XR())return new Blob(t);throw new FR("unsupported-environment","This browser doesn't seem to support creating Blobs")}const ax={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class ox{constructor(e,t){this.data=e,this.contentType=t||null}}function cx(e,t){switch(e){case ax.RAW:return new ox(lx(t));case ax.BASE64:case ax.BASE64URL:return new ox(ux(e,t));case ax.DATA_URL:return new ox((n=t,(r=new hx(n)).base64?ux(ax.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw WR(ax.DATA_URL,"Malformed data URL.")}return lx(t)}(r.rest)),(n=t,new hx(n).contentType))}var n,r;throw qR()}function lx(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function ux(t,e){switch(t){case ax.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw WR(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case ax.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw WR(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw WR(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return s}class hx{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw WR(ax.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class dx{constructor(e,t){let n=0,r="";JR(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(JR(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new dx(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new dx(n,!0)}static getBlob(...e){if(XR()){var t=e.map(e=>e instanceof dx?e.data_:e);return new dx(sx.apply(null,t))}{const r=e.map(e=>YR(e)?cx(ax.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new dx(i,!0)}}uploadData(){return this.data_}}function px(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function fx(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function gx(e,t){return t}class mx{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||gx}}let vx=null;function yx(){if(vx)return vx;const e=[];e.push(new mx("bucket")),e.push(new mx("generation")),e.push(new mx("metageneration")),e.push(new mx("name","fullPath",!0));const t=new mx("name");t.xform=function(e,t){return!YR(t=t)||t.length<2?t:fx(t)},e.push(t);const n=new mx("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new mx("timeCreated")),e.push(new mx("updated")),e.push(new mx("md5Hash",null,!0)),e.push(new mx("cacheControl",null,!0)),e.push(new mx("contentDisposition",null,!0)),e.push(new mx("contentEncoding",null,!0)),e.push(new mx("contentLanguage",null,!0)),e.push(new mx("contentType",null,!0)),e.push(new mx("metadata","customMetadata",!0)),vx=e,vx}function _x(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new HR(e,t);return r._makeStorageReference(t)}})}function wx(e,t,n){var r=px(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const a=n[s];r[a.local]=a.xform(r,t[a.server])}return _x(r,e),r}(e,r,n)}function bx(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}const Ix="prefixes";function Tx(e,t,n){var r=px(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[Ix])for(const a of n[Ix]){var i=a.replace(/\/$/,""),i=e._makeStorageReference(new HR(t,i));r.prefixes.push(i)}if(n.items)for(const o of n.items){var s=e._makeStorageReference(new HR(t,o.name));r.items.push(s)}return r}(e,t,r)}class Ex{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function kx(e){if(!e)throw qR()}function Cx(r,i){return function(e,t){var n=wx(r,t,i);return kx(null!==n),n}}function Sx(r,i){return function(e,t){var n=Tx(r,i,t);return kx(null!==n),n}}function Ax(r,i){return function(e,t){var n=wx(r,t,i);return kx(null!==n),function(r,e,i,s){var t=px(e);if(null===t)return null;if(!YR(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const a=encodeURIComponent,o=n.split(",");return o.map(e=>{var t=r.bucket,n=r.fullPath;return ex("/b/"+a(t)+"/o/"+a(n),i,s)+tx({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function Nx(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new FR("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new FR("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new FR("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(r=i.path,new FR("unauthorized","User does not have permission to access '"+r+"'.")):t,n.status=e.getStatus(),n.serverResponse=t.serverResponse,n}}function Rx(r){const i=Nx(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new FR("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function xx(e,t,n){var r=ex(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new Ex(r,"GET",Cx(e,n),i);return s.errorHandler=Rx(t),s}function Dx(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function Px(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const a={"X-Goog-Upload-Protocol":"multipart"};var o=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();a["Content-Type"]="multipart/related; boundary="+o;var c=Dx(t,r,i),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+bx(c,n)+"\r\n--"+o+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",o="\r\n--"+o+"--";const u=dx.getBlob(l,r,o);if(null===u)throw jR();o={name:c.fullPath},c=ex(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new Ex(c,"POST",Cx(e,n),s);return h.urlParams=o,h.headers=a,h.body=u.uploadData(),h.errorHandler=Nx(t),h}class Ox{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function Mx(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){kx(!1)}const r=t||["active"];return kx(!!n&&-1!==r.indexOf(n)),n}function Lx(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),a=Dx(t,r,i),o={name:a.fullPath},c=ex(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},s=bx(a,n),a=e.maxUploadRetryTime;const u=new Ex(c,"POST",function(e){Mx(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){kx(!1)}return kx(YR(t)),t},a);return u.urlParams=o,u.headers=l,u.body=s,u.errorHandler=Nx(t),u}function Fx(e,t,n,i){var r=e.maxUploadRetryTime;const s=new Ex(n,"POST",function(e){var t=Mx(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){kx(!1)}n||kx(!1);var r=Number(n);return kx(!isNaN(r)),new Ox(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=Nx(t),s}function Ux(e,a,t,o,n,c,r,i){const l=new Ox(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=o.size()),o.size()!==l.total)throw new FR("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u;let p="";p=0===u?"finalize":s===u?"upload, finalize":"upload";s={"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":`${l.current}`};const f=o.slice(h,d);if(null===f)throw jR();d=a.maxUploadRetryTime;const g=new Ex(t,"POST",function(e,t){var n=Mx(e,["active","final"]),r=l.current+u,i=o.size();let s;return s="final"===n?Cx(a,c)(e,t):null,new Ox(r,i,"final"===n,s)},d);return g.headers=s,g.body=f.uploadData(),g.progressCallback=i||null,g.errorHandler=Nx(e),g}const qx={STATE_CHANGED:"state_changed"},Vx={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Bx(e){switch(e){case"running":case"pausing":case"canceling":return Vx.RUNNING;case"paused":return Vx.PAUSED;case"success":return Vx.SUCCESS;case"canceled":return Vx.CANCELED;default:return Vx.ERROR}}class jx{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function Kx(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class $x extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=NR.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=NR.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=NR.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw GR("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw GR("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw GR("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw GR("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw GR("cannot .getErrorText() before sending");return this.xhr_.statusText}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 zx(){return new $x}class Wx{constructor(e,t,n=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=n,this._mappings=yx(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals("canceled"))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(nx(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=VR()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals("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,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const 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(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=Lx(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,zx,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=Fx(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,zx,e,t);this._request=r,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(){const i=262144*this._chunkMultiplier,s=new Ox(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=Ux(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")}const r=this._ref.storage._makeRequest(n,zx,e,t,!1);this._request=r,r.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 n=xx(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,zx,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=Px(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,zx,e,t);this._request=r,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=BR(),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=Bx(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new jx(t||void 0,n||void 0,r||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();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(Bx(this._state)){case Vx.SUCCESS:Kx(this._resolve.bind(null,this.snapshot))();break;case Vx.CANCELED:case Vx.ERROR:const t=this._reject;Kx(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Bx(this._state)){case Vx.RUNNING:case Vx.PAUSED:e.next&&Kx(e.next.bind(e,this.snapshot))();break;case Vx.SUCCESS:e.complete&&Kx(e.complete.bind(e))();break;case Vx.CANCELED:case Vx.ERROR:default:e.error&&Kx(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 Gx{constructor(e,t){this._service=e,t instanceof HR?this._location=t:this._location=HR.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Gx(e,t)}get root(){var e=new HR(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return fx(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new HR(this._location.bucket,e);return new Gx(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw zR(e)}}function Hx(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await Qx(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function Qx(e,t){null!=t&&"number"==typeof t.maxResults&&ZR("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var a=ex(t.bucketOnlyServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime;const c=new Ex(a,"GET",Sx(e,t.bucket),o);return c.urlParams=s,c.errorHandler=Nx(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,zx)}function Yx(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=ex(t.fullServerUrl(),e.host,e._protocol),s=bx(n,r),a=e.maxOperationRetryTime;const o=new Ex(i,"PATCH",Cx(e,r),a);return o.headers={"Content-Type":"application/json; charset=utf-8"},o.body=s,o.errorHandler=Rx(t),o}(e.storage,e._location,t,yx());return e.storage.makeRequestWithTokens(n,zx)}function Jx(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=ex(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new Ex(r,"GET",Ax(e,n),i);return s.errorHandler=Rx(t),s}(e.storage,e._location,yx());return e.storage.makeRequestWithTokens(t,zx).then(e=>{if(null===e)throw new FR("no-download-url","The given file does not have any download URLs.");return e})}function Xx(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=ex(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new Ex(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=Rx(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,zx)}function Zx(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new HR(e._location.bucket,r);return new Gx(e.storage,r)}function eD(e,t){if(e instanceof rD){var n=e;if(null==n._bucket)throw new FR("no-default-bucket","No default bucket found. Did you set the '"+LR+"' property when initializing the app?");n=new Gx(n,n._bucket);return null!=t?eD(n,t):n}return void 0!==t?Zx(e,t):e}function tD(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof rD)return n=e,r=t,new Gx(n,r);throw KR("To use ref(service, url), the first argument must be a Storage instance.")}return eD(e,t);var n,r}function nD(e,t){var n=null==t?void 0:t[LR];return null==n?null:HR.makeFromBucketSpec(n,e)}class rD{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=MR,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?HR.makeFromBucketSpec(r,this._host):nD(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=HR.makeFromBucketSpec(this._url,e):this._bucket=nD(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){ZR("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){ZR("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(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 Gx(this,e)}_makeRequest(e,t,n,r,i=!0){if(this._deleted)return new QR($R());{const u=([s,a,o,e,n,r,t=!0]=[e,this._appId,n,r,t,this._firebaseVersion,i],c=tx(s.urlParams),l=s.url+c,c=Object.assign({},s.headers),i=c,(a=a)&&(i["X-Firebase-GMPID"]=a),a=c,null!==(o=o)&&0<o.length&&(a.Authorization="Firebase "+o),r=r,c["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=c,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new rx(l,s.method,c,s.body,s.successCodes,s.additionalRetryCodes,s.handler,s.errorHandler,s.timeout,s.progressCallback,n,t));return this._requests.add(u),u.getPromise().then(()=>this._requests.delete(u),()=>this._requests.delete(u)),u}var s,a,o,c,l}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const iD="@firebase/storage";function sD(e,t,n){return e=ae(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new Wx(e,new dx(t),n)}function aD(e){return function(e){e._throwIfRoot("getMetadata");var t=xx(e.storage,e._location,yx());return e.storage.makeRequestWithTokens(t,zx)}(e=ae(e))}function oD(e,t){return tD(e=ae(e),t)}function cD(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:N(i,e.app.options.projectId))}(e,t,n,r)}function lD(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new rD(n,r,i,t,Ye)}We(new oe("storage",lD,"PUBLIC").setMultipleInstances(!0)),et(iD,"0.9.12",""),et(iD,"0.9.12","esm2017");class uD{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}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 hD{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 uD(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new uD(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new uD(e,this,this._ref)):{next:t.next?e=>t.next(new uD(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class dD{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new pD(e,this._service))}get items(){return this._delegate.items.map(e=>new pD(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class pD{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=Zx(this._delegate,e);return new pD(t,this.storage)}get root(){return new pD(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new pD(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new hD(sD(this._delegate,e,t),this)}putString(e,t=ax.RAW,n){this._throwIfRoot("putString");var r=cx(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new hD(new Wx(this._delegate,new dx(r.data,!0),i),this)}listAll(){return Hx(ae(this._delegate)).then(e=>new dD(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,Qx(t=ae(t),e).then(e=>new dD(e,this.storage));var t}getMetadata(){return aD(this._delegate)}updateMetadata(e){return Yx(ae(this._delegate),e)}getDownloadURL(){return Jx(ae(this._delegate))}delete(){return this._throwIfRoot("delete"),Xx(ae(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw zR(e)}}class fD{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(gD(e))throw KR("ref() expected a child path but got a URL, use refFromURL instead.");return new pD(oD(this._delegate,e),this)}refFromURL(e){if(!gD(e))throw KR("refFromURL() expected a full URL but got a child path, use ref() instead.");try{HR.makeFromUrl(e,this._delegate.host)}catch(e){throw KR("refFromUrl() expected a valid full URL but got an invalid one.")}return new pD(oD(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){cD(this._delegate,e,t,n)}}function gD(e){return/^[A-Za-z]+:\/\//.test(e)}function mD(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new fD(n,r)}RR=wt,xR={TaskState:Vx,TaskEvent:qx,StringFormat:ax,Storage:fD,Reference:pD},RR.INTERNAL.registerComponent(new oe("storage-compat",mD,"PUBLIC").setServiceProps(xR).setMultipleInstances(!0)),RR.registerVersion("@firebase/storage-compat","0.1.20");const vD="@firebase/performance",yD="0.5.15",_D=yD,wD="FB-PERF-TRACE-MEASURE",bD="@firebase/performance/config",ID="@firebase/performance/configexpire";var TD,ED,kD,CD="Performance";const SD=new x("performance",CD,{"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."}),AD=new me(CD);AD.logLevel=k.INFO;let ND,RD;class xD{constructor(e){if(!(this.window=e))throw SD.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)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}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&&_()?!!v()||(AD.info("IndexedDB is not supported by current browswer"),!1):(AD.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===ND&&(ND=new xD(RD)),ND}}let DD;function PD(e,t){var n=e.length-t.length;if(n<0||1<n)throw SD.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let OD;class MD{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=PD("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=PD("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 void 0===OD&&(OD=new MD),OD}}(It=TD=TD||{})[It.UNKNOWN=0]="UNKNOWN",It[It.VISIBLE=1]="VISIBLE",It[It.HIDDEN=2]="HIDDEN";const LD=["firebase_","google_","ga_"],FD=new RegExp("^[a-zA-Z]\\w*$");function UD(){switch(xD.getInstance().document.visibilityState){case"visible":return TD.VISIBLE;case"hidden":return TD.HIDDEN;default:return TD.UNKNOWN}}function qD(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw SD.create("no app id");return t}const VD="0.0.1",BD={loggingEnabled:!0},jD="FIREBASE_INSTALLATIONS_AUTH";function KD(e,t){var r,i,n=function(){const e=xD.getInstance().localStorage;if(e){var t=e.getItem(ID);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(bD);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(zD(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw SD.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw SD.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${jD} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:qD(r.app),app_version:_D,sdk_version:VD})});return fetch(n).then(e=>{if(e.ok)return e.json();throw SD.create("RC response not ok")})}).catch(()=>{AD.info($D)}).then(zD).then(e=>function(e){const t=xD.getInstance().localStorage;e&&t&&(t.setItem(bD,JSON.stringify(e)),t.setItem(ID,String(Date.now()+60*MD.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const $D="Could not fetch config, will use default configs";function zD(e){if(!e)return e;const t=MD.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=BD.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):BD.logSource&&(t.logSource=BD.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:BD.logEndPointUrl&&(t.logEndPointUrl=BD.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:BD.transportKey&&(t.transportKey=BD.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==BD.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=BD.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==BD.tracesSamplingRate&&(t.tracesSamplingRate=BD.tracesSamplingRate),t.logTraceAfterSampling=WD(t.tracesSamplingRate),t.logNetworkAfterSampling=WD(t.networkRequestsSamplingRate),e}function WD(e){return Math.random()<=e}let GD=1,HD;function QD(e){var t;return GD=2,HD=HD||(t=e,function(){const n=xD.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{DD=e}),t}(t.installations)).then(e=>KD(t,e)).then(()=>YD(),()=>YD())),HD}function YD(){GD=3}const JD=1e4,XD=3,ZD=1e3;let eP=XD,tP=[],nP=!1;function rP(e){setTimeout(()=>{if(0!==eP)return tP.length?void function(){const e=tP.splice(0,ZD),t=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:MD.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=MD.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||AD.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=JD;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(tP=[...r,...tP],AD.info("Retry transport request later.")),eP=XD,rP(n)})}(n,e).catch(()=>{tP=[...e,...tP],eP--,AD.info(`Tries left: ${eP}.`),rP(JD)})}():rP(JD)},e)}function iP(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw SD.create("invalid cc log");tP=[...tP,e]}({message:t(...e),eventTime:Date.now()})}}let sP;function aP(e,t){sP=sP||iP(lP),sP(e,t)}function oP(e){var t=MD.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&xD.getInstance().requiredApisAvailable()&&(e.isAuto&&UD()!==TD.VISIBLE||(3===GD?cP(e):QD(e.performanceController).then(()=>cP(e),()=>cP(e))))}function cP(e){var t;!DD||(t=MD.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>aP(e,1),0)}function lP(e,t){return 0===t?(n={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},n={application_info:uP(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:uP(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function uP(e){return{google_app_id:qD(e),app_instance_id:DD,web_app_info:{sdk_version:_D,page_url:xD.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=xD.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:UD(),effective_connection_type:function(){var e=xD.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}const hP=["_fp","_fcp","_fid"];class dP{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=xD.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=r||`${wD}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw SD.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw SD.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(),oP(this)}record(e,t,n){if(e<=0)throw SD.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw SD.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));oP(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(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<hP.indexOf(r))&&r.startsWith("_"))throw SD.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&AD.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!LD.some(e=>n.startsWith(e))&&!!n.match(FD)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw SD.create("invalid attribute name",{attributeName:e});if(!s)throw SD.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,n,r){var i=xD.getInstance().getUrl();if(i){const s=new dP(e,"_wt_"+i,!0);i=Math.floor(1e3*xD.getInstance().getTimeOrigin());s.setStartTime(i),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)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),oP(s)}}static createUserTimingTrace(e,t){oP(new dP(e,t,!1,t))}}function pP(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=xD.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=MD.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>aP(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const fP=5e3;function gP(e){DD&&(setTimeout(()=>function(n){const e=xD.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{dP.createOobTrace(n,r,i),t=void 0},fP);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),dP.createOobTrace(n,r,i,e))})}else dP.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=xD.getInstance(),n=e.getEntriesByType("resource");for(const r of n)pP(t,r);e.setupObserver("resource",e=>pP(t,e))}(e),0),setTimeout(()=>function(t){const e=xD.getInstance(),n=e.getEntriesByType("measure");for(const r of n)mP(t,r);e.setupObserver("measure",e=>mP(t,e))}(e),0))}function mP(e,t){const n=t.name;n.substring(0,wD.length)!==wD&&dP.createUserTimingTrace(e,n)}class vP{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),xD.getInstance().requiredApisAvailable()?y().then(e=>{e&&(nP||(rP(5500),nP=!0),QD(this).then(()=>gP(this),()=>gP(this)),this.initialized=!0)}).catch(e=>{AD.info(`Environment doesn't support IndexedDB: ${e}`)}):AD.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){MD.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return MD.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){MD.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return MD.getInstance().dataCollectionEnabled}}const yP="[DEFAULT]";const _P=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==yP)throw SD.create("FB not default");if("undefined"==typeof window)throw SD.create("no window");e=window,RD=e;const i=new vP(n,r);return i._init(t),i};We(new oe("performance",_P,"PUBLIC")),et(vD,yD),et(vD,yD,"esm2017");class wP{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=ae(t),new dP(t,e);var t}}function bP(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new wP(t,n)}(ED=wt).INTERNAL.registerComponent(new oe("performance-compat",bP,"PUBLIC")),ED.registerVersion("@firebase/performance-compat","0.1.15");const IP="@firebase/remote-config";class TP{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const EP=new x("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"});const kP=["1","true","t","yes","y","on"];class CP{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=kP.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function SP(e){const t=ae(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function AP(e){const t=ae(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function NP(t){const n=ae(t),e=new TP;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof R&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function RP(n){const e=ae(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=xP(n,t),e),{});var t,r}function xP(e,t){const n=ae(e);n._isInitializationComplete||n._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.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new CP("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new CP("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new CP("static"))}class DP{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class PP{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=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":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let a;try{await Promise.race([i,r]),a=await i}catch(e){let t="fetch-client-network";throw"AbortError"===(null===e||void 0===e?void 0:e.name)&&(t="fetch-timeout"),EP.create(t,{originalErrorMessage:null===e||void 0===e?void 0:e.message})}let o=a.status;i=a.headers.get("ETag")||void 0;let c,l;if(200===a.status){let e;try{e=await a.json()}catch(e){throw EP.create("fetch-client-parse",{originalErrorMessage:null===e||void 0===e?void 0:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?o=500:"NO_CHANGE"===l?o=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==o&&200!==o)throw EP.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:c}}}class OP{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:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(EP.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof R&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+se(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class MP{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function LP(e,t){var n=e.target.error||void 0;return EP.create(t,{originalErrorMessage:n&&(null===n||void 0===n?void 0:n.message)})}const FP="app_namespace_store";class UP{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(LP(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(FP,{keyPath:"compositeKey"})}}catch(e){n(EP.create("storage-open",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}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")}async get(a){const o=await this.openDbPromise;return new Promise((n,t)=>{const e=o.transaction([FP],"readonly"),r=e.objectStore(FP);var i=this.createCompositeKey(a);try{const s=r.get(i);s.onerror=e=>{t(LP(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(EP.create("storage-get",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}async set(a,o){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([FP],"readwrite"),r=n.objectStore(FP);var i=this.createCompositeKey(a);try{const s=r.put({compositeKey:i,value:o});s.onerror=e=>{t(LP(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(EP.create("storage-set",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}async delete(a){const o=await this.openDbPromise;return new Promise((e,t)=>{const n=o.transaction([FP],"readwrite"),r=n.objectStore(FP);var i=this.createCompositeKey(a);try{const s=r.delete(i);s.onerror=e=>{t(LP(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(EP.create("storage-delete",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class qP{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}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 function VP(){if(!v())return!1;try{return await y()}catch(e){return!1}}We(new oe("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw EP.create("registration-window");if(!v())throw EP.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=n.options;if(!i)throw EP.create("registration-project-id");if(!s)throw EP.create("registration-api-key");if(!a)throw EP.create("registration-app-id");t=t||"firebase";const o=new UP(a,n.name,t),c=new qP(o),l=new me(IP);l.logLevel=k.ERROR;a=new PP(r,Ye,t,i,s,a),a=new OP(a,o),a=new DP(a,o,c,l),a=new MP(n,a,c,o,l);return AP(a),a},"PUBLIC").setMultipleInstances(!0)),et(IP,"0.3.14"),et(IP,"0.3.14","esm2017");class BP{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 SP(this._delegate)}ensureInitialized(){return AP(this._delegate)}fetch(){return NP(this._delegate)}fetchAndActivate(){return async function(e){return await NP(e=ae(e)),SP(e)}(this._delegate)}getAll(){return RP(this._delegate)}getBoolean(e){return xP(ae(this._delegate),e).asBoolean()}getNumber(e){return xP(ae(this._delegate),e).asNumber()}getString(e){return xP(ae(this._delegate),e).asString()}getValue(e){return xP(this._delegate,e)}setLogLevel(e){!function(e,t){const n=ae(e);switch(t){case"debug":n._logger.logLevel=k.DEBUG;break;case"silent":n._logger.logLevel=k.SILENT;break;default:n._logger.logLevel=k.ERROR}}(this._delegate,e)}}function jP(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new BP(n,r)}return(kD=wt).INTERNAL.registerComponent(new oe("remoteConfig-compat",jP,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:VP})),kD.registerVersion("@firebase/remote-config-compat","0.1.15"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),wt.registerVersion("firebase","9.12.1","compat-cdn"),wt});
9
+ `)}const kr={error:"UNKNOWN_ERROR"};async function Sr(e,t=!1){var n=e.app;ar(n);const r=Xn(n);let i=r.token,s=void 0;if(i&&!xr(i)&&(Zn(n,Object.assign(Object.assign({},r),{token:void 0})),i=void 0),i||(o=await r.cachedTokenPromise)&&(xr(o)?i=o:await br(n,void 0)),!t&&i&&xr(i))return{token:i.token};let a=!1;if(Tr()){r.exchangeTokenPromise||(r.exchangeTokenPromise=lr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${er}/projects/${n}/apps/${r}:${tr}?key=${i}`,body:{debug_token:t}}}(n,await Er()),e.heartbeatServiceProvider).finally(()=>{r.exchangeTokenPromise=void 0}),a=!0);var o=await r.exchangeTokenPromise;return await br(n,o),Zn(n,Object.assign(Object.assign({},r),{token:o})),{token:o.token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().finally(()=>{r.exchangeTokenPromise=void 0}),a=!0),i=await r.exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?_r.warn(e.message):_r.error(e),s=e}let c;return i?s?c=xr(i)?{token:i.token,internalError:s}:Dr(s):(c={token:i.token},Zn(n,Object.assign(Object.assign({},r),{token:i})),await br(n,i)):c=Dr(s),a&&Rr(n,c),c}function Cr(e,t,n,r){var i=e["app"];const s=Xn(i);var a={next:n,error:r,type:t};if(Zn(i,Object.assign(Object.assign({},s),{tokenObservers:[...s.tokenObservers,a]})),s.token&&xr(s.token)){const o=s.token;Promise.resolve().then(()=>{n({token:o.token}),Nr(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Nr(e))}function Ar(e,t){const n=Xn(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),Zn(e,Object.assign(Object.assign({},n),{tokenObservers:r}))}function Nr(e){var t=e["app"],n=Xn(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new rr(async()=>{var e=Xn(r);let t;if(t=e.token?await Sr(n,!0):await Sr(n),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=Xn(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},nr.RETRIAL_MIN_WAIT,nr.RETRIAL_MAX_WAIT)}(e),Zn(t,Object.assign(Object.assign({},n),{tokenRefresher:r}))),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function Rr(e,t){for(const n of Xn(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function xr(e){return 0<e.expireTimeMillis-Date.now()}function Dr(e){return{token:(t=kr,r.encodeString(JSON.stringify(t),!1)),error:e};var t}class Pr{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=Xn(this.app)["tokenObservers"];for(const t of e)Ar(this.app,t.next);return Promise.resolve()}}const Or="https://www.google.com/recaptcha/api.js",Mr="https://www.google.com/recaptcha/enterprise.js";function Lr(t,n){var e=Xn(t);const r=new A;Zn(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=qr(t);e=sr(!1);return e?Ur(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Or,t.onload=e,document.head.appendChild(t)}(()=>{var e=sr(!1);if(!e)throw new Error("no recaptcha");Ur(t,n,e,i,r)}),r.promise}function Fr(t,n){var e=Xn(t);const r=new A;Zn(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=qr(t);e=sr(!0);return e?Ur(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Mr,t.onload=e,document.head.appendChild(t)}(()=>{var e=sr(!0);if(!e)throw new Error("no recaptcha");Ur(t,n,e,i,r)}),r.promise}function Ur(r,i,s,a,o){s.ready(()=>{var e,t,n;e=r,t=s.render(a,{sitekey:i,size:"invisible"}),n=Xn(e),Zn(e,Object.assign(Object.assign({},n),{reCAPTCHAState:Object.assign(Object.assign({},n.reCAPTCHAState),{widgetId:t})})),o.resolve(s)})}function qr(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function Vr(r){ar(r);const i=await Xn(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=Xn(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class Br{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Wr(this._throttleData);var t=await Vr(this._app).catch(e=>{throw ir.create("recaptcha-error")});let e;try{e=await lr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${er}/projects/${n}/apps/${r}:exchangeRecaptchaV3Token?key=${i}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=$r(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ir.create("throttled",{time:or(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=Ge(e,"heartbeat"),Lr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Br&&this._siteKey===e._siteKey}}class jr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){Wr(this._throttleData);var t=await Vr(this._app).catch(e=>{throw ir.create("recaptcha-error")});let e;try{e=await lr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${er}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=$r(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ir.create("throttled",{time:or(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._heartbeatServiceProvider=Ge(e,"heartbeat"),Fr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof jr&&this._siteKey===e._siteKey}}class Kr{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=M(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof Kr&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function $r(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=se(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function Wr(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw ir.create("throttled",{time:or(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function zr(e=Xe(),t){const n=Ge(e=ae(e),"app-check");if(Jn.initialized||function(){var e=w();const t=Jn;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new A;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Ir())}}(),Tr()&&Er().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.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw ir.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=Xn(t),i=Object.assign(Object.assign({},r),{activated:!0});i.provider=e,i.cachedTokenPromise=wr(t).then(e=>(e&&xr(e)&&(Zn(t,Object.assign(Object.assign({},Xn(t)),{token:e})),Rr(t,{token:e.token})),e)),i.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,Zn(t,i),i.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),Xn(e).isTokenAutoRefreshEnabled&&Cr(r,"INTERNAL",()=>{}),r}const Gr="app-check-internal";ze(new oe("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new Pr(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(Gr).initialize()})),ze(new oe(Gr,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>Sr(t,e),addTokenListener:e=>Cr(t,"INTERNAL",e),removeTokenListener:e=>Ar(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),et("@firebase/app-check","0.5.16");const Hr=new x("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 Qr{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new Br(e):e instanceof jr||e instanceof Br||e instanceof Kr?e:new Kr({getToken:e.getToken}),this._delegate=zr(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw Hr.create("use-before-activation",{appName:this.app.name});!function(e,t){var n=e.app;const r=Xn(n);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),Zn(n,Object.assign(Object.assign({},r),{isTokenAutoRefreshEnabled:t}))}(this._delegate,e)}getToken(e){if(!this._delegate)throw Hr.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Sr(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw Hr.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Cr(e,"EXTERNAL",r,i),()=>Ar(e.app,r)}(this._delegate,e,t)}}const Yr=e=>{var t=e.getProvider("app-compat").getImmediate();return new Qr(t)};function Jr(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}wt.INTERNAL.registerComponent(new oe("appCheck-compat",Yr,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:jr,ReCaptchaV3Provider:Br,CustomProvider:Kr})),wt.registerVersion("@firebase/app-check-compat","0.2.16");const Xr={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},Zr={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 ei(){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 ti(){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 registed 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 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-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."}}const ni=ei,ri=new x("auth","Firebase",ei()),ii=new me("@firebase/auth");function si(e,...t){ii.logLevel<=k.ERROR&&ii.error(`Auth (${Ye}): ${e}`,...t)}function ai(e,...t){throw ui(e,...t)}function oi(e,...t){return ui(e,...t)}function ci(e,t,n){var r=Object.assign(Object.assign({},ni()),{[t]:n});const i=new x("auth","Firebase",r);return i.create(t,{appName:e.name})}function li(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&ai(e,"argument-error"),ci(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function ui(e,...t){if("string"==typeof e)return ri.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function hi(e,t,...n){if(!e)throw ui(t,...n)}function di(e){var t="INTERNAL ASSERTION FAILED: "+e;throw si(t),new Error(t)}function pi(e,t){e||di(t)}const fi=new Map;function gi(e){pi(e instanceof Function,"Expected a class definition");let t=fi.get(e);return t?pi(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,fi.set(e,t)),t}function mi(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function vi(){return"http:"===yi()||"https:"===yi()}function yi(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class _i{constructor(e,t){pi((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=o()||p()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(vi()||d()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function wi(e,t){pi(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class bi{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void di("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:void di("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:void di("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Ii={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:"internal-error",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",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"},Ti=new _i(3e4,6e4);function Ei(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function ki(i,s,a,o,e={}){return Si(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var n=j(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),bi.fetch()(Ai(i,i.config.apiHost,a,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Si(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Ii),e);try{const a=new Ni(t),o=await Promise.race([n(),a.promise]);a.clearNetworkTimeout();var i=await o.json();if("needConfirmation"in i)throw Ri(t,"account-exists-with-different-credential",i);if(o.ok&&!("errorMessage"in i))return i;{const c=o.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Ri(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Ri(t,"email-already-in-use",i);if("USER_DISABLED"===l)throw Ri(t,"user-disabled",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw ci(t,s,u);ai(t,s)}}catch(e){if(e instanceof R)throw e;ai(t,"network-request-failed")}}async function Ci(e,t,n,r,i={}){var s=await ki(e,t,n,r,i);return"mfaPendingCredential"in s&&ai(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Ai(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?wi(e.config,i):`${e.config.apiScheme}://${i}`}class Ni{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(oi(this.auth,"network-request-failed")),Ti.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Ri(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=oi(e,t,r);return i.customData._tokenResponse=n,i}function xi(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Di(e){return 1e3*Number(e)}function Pi(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return si("JWT malformed, contained fewer than 3 sections"),null;try{var i=a(n);return i?JSON.parse(i):(si("Failed to decode base64 JWT payload"),null)}catch(e){return si("Caught error parsing JWT payload as JSON",null===e||void 0===e?void 0:e.toString()),null}}async function Oi(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof R&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class Mi{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){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return 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?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class Li{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=xi(this.lastLoginAt),this.creationTime=xi(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Fi(e){var t=e.auth,n=await e.getIdToken(),r=await Oi(e,async function(e,t){return ki(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));hi(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,a,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=Jr(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,a=t,[...s.filter(t=>!a.some(e=>e.providerId===t.providerId)),...a]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new Li(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class Ui{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){hi(e.idToken,"internal-error"),hi(void 0!==e.idToken,"internal-error"),hi(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,hi(n=Pi(t),"internal-error"),hi(void 0!==n.exp,"internal-error"),hi(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return hi(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:a}=(s=t,await{accessToken:(a=await Si(i=e,{},async()=>{var e=j({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=Ai(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",bi.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:a.expires_in,refreshToken:a.refresh_token});this.updateTokensAndExpiration(n,r,Number(a))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new Ui;return n&&(hi("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(hi("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(hi("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 Ui,this.toJSON())}_performRefresh(){return di("not implemented")}}function qi(e,t){hi("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Vi{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=Jr(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Mi(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.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 Li(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Oi(this,this.stsTokenManager.getToken(this.auth,e));return hi(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 function(e,t=!1){const n=ae(e);var r=await n.getIdToken(t),i=Pi(r);hi(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,a=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:xi(Di(i.auth_time)),issuedAtTime:xi(Di(i.iat)),expirationTime:xi(Di(i.exp)),signInProvider:a||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=ae(e);await Fi(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(hi(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){return new Vi(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){hi(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await Fi(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await Oi(this,async function(e,t){return ki(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 n=null!==(a=t.displayName)&&void 0!==a?a:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(o=t.phoneNumber)&&void 0!==o?o:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,a=null!==(c=t.tenantId)&&void 0!==c?c:void 0,o=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:p,stsTokenManager:f}=t;hi(u&&f,e,"internal-error");var g=Ui.fromJSON(this.name,f);hi("string"==typeof u,e,"internal-error"),qi(n,e.name),qi(r,e.name),hi("boolean"==typeof h,e,"internal-error"),hi("boolean"==typeof d,e,"internal-error"),qi(i,e.name),qi(s,e.name),qi(a,e.name),qi(o,e.name),qi(c,e.name),qi(l,e.name);const m=new Vi({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:g,createdAt:c,lastLoginAt:l});return p&&Array.isArray(p)&&(m.providerData=p.map(e=>Object.assign({},e))),o&&(m._redirectEventId=o),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new Ui;r.updateFromServerResponse(t);var i=new Vi({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Fi(i),i}}class Bi{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){}}Bi.type="NONE";const ji=Bi;function Ki(e,t,n){return`firebase:${e}:${t}:${n}`}class $i{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=Ki(this.userKey,r.apiKey,i),this.fullPersistenceKey=Ki("persistence",r.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?Vi._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence!==e){var t=await this.getCurrentUser();return 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,n="authUser"){if(!t.length)return new $i(gi(ji),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||gi(ji);const s=Ki(n,e.config.apiKey,e.name);let a=null;for(const u of t)try{var o=await u._get(s);if(o){var c=Vi._fromJSON(e,o);u!==i&&(a=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new $i(i,e,n)}}function Wi(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Qi(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(zi(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(Ji(t))return"Blackberry";if(Xi(t))return"Webos";if(Gi(t))return"Safari";if((t.includes("chrome/")||Hi(t))&&!t.includes("edge/"))return"Chrome";if(Yi(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function zi(e=h()){return/firefox\//i.test(e)}function Gi(e=h()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function Hi(e=h()){return/crios\//i.test(e)}function Qi(e=h()){return/iemobile/i.test(e)}function Yi(e=h()){return/android/i.test(e)}function Ji(e=h()){return/blackberry/i.test(e)}function Xi(e=h()){return/webos/i.test(e)}function Zi(e=h()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function es(e=h()){return Zi(e)||Yi(e)||Xi(e)||Ji(e)||/windows phone/i.test(e)||Qi(e)}function ts(e,t=[]){let n;switch(e){case"Browser":n=Wi(h());break;case"Worker":n=`${Wi(h())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Ye}/${r}`}class ns{constructor(e){this.auth=e,this.queue=[]}pushCallback(r,e){var t=n=>new Promise((e,t)=>{try{e(r(n))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);const n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const r of t)try{r()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null===e||void 0===e?void 0:e.message})}}}}class rs{constructor(e,t,n){this.app=e,this.heartbeatServiceProvider=t,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ss(this),this.idTokenSubscription=new ss(this),this.beforeStateQueue=new ns(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=ri,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,n){return n&&(this._popupRedirectResolver=gi(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await $i.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0)}}async initializeCurrentUser(e){var t,n,r,i=await this.assertedPersistence.getCurrentUser();let s=i,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===s||void 0===s?void 0:s._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(s=r.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return hi(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 Fi(e)}catch(e){if("auth/network-request-failed"!==(null===e||void 0===e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?ae(e):null;return t&&hi(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&&hi(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 await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(gi(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new x("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(hi(t=e&&gi(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await $i.create(this,[gi(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?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?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?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return hi(s,this,"internal-error"),s.then(()=>i(this.currentUser)),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}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 hi(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=ts(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);var t=await(null===(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getHeartbeatsHeader());return t&&(e["X-Firebase-Client"]=t),e}}function is(e){return ae(e)}class ss{constructor(e){this.auth=e,this.observer=null,this.addObserver=z(e=>this.observer=e)}get next(){return hi(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function as(e,t,n){const r=is(e);hi(r._canInitEmulator,r,"emulator-config-failed"),hi(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=os(t);var{host:a,port:o}=function(e){const t=os(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:cs(r.substr(s.length+1))}}var[a,s]=r.split(":");return{host:a,port:cs(s)}}}(t);r.config.emulator={url:`${s}//${a}${null===o?"":`:${o}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const 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)}"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",e):e())}()}function os(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function cs(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class ls{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return di("not implemented")}_getIdTokenResponse(e){return di("not implemented")}_linkToIdToken(e,t){return di("not implemented")}_getReauthenticationResolver(e){return di("not implemented")}}async function us(e,t){return ki(e,"POST","/v1/accounts:resetPassword",Ei(e,t))}async function hs(e,t){return ki(e,"POST","/v1/accounts:update",t)}async function ds(e,t){return ki(e,"POST","/v1/accounts:sendOobCode",Ei(e,t))}class ps extends ls{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new ps(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new ps(e,t,"emailLink",n)}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 async function(e,t){return Ci(e,"POST","/v1/accounts:signInWithPassword",Ei(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Ci(e,"POST","/v1/accounts:signInWithEmailLink",Ei(e,t))}(e,{email:this._email,oobCode:this._password});default:ai(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return hs(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Ci(e,"POST","/v1/accounts:signInWithEmailLink",Ei(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:ai(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function fs(e,t){return Ci(e,"POST","/v1/accounts:signInWithIdp",Ei(e,t))}class gs extends ls{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new gs(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):ai("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:n,signInMethod:r}=t,t=Jr(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new gs(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return fs(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,fs(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,fs(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=j(t)}return e}}const ms={USER_NOT_FOUND:"user-not-found"};class vs extends ls{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new vs({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new vs({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Ci(e,"POST","/v1/accounts:signInWithPhoneNumber",Ei(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Ci(e,"POST","/v1/accounts:signInWithPhoneNumber",Ei(e,t));if(n.temporaryProof)throw Ri(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Ci(e,"POST","/v1/accounts:signInWithPhoneNumber",Ei(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),ms)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const 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:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new vs({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class ys{constructor(e){var t=K($(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);hi(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=K($(e=e)).link,n=t?K($(t)).deep_link_id:null,((r=K($(e)).deep_link_id)?K($(r)).link:null)||r||n||t||e);try{return new ys(t)}catch(e){return null}}}class _s{constructor(){this.providerId=_s.PROVIDER_ID}static credential(e,t){return ps._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=ys.parseLink(t);return hi(n,"argument-error"),ps._fromEmailAndCode(e,n.code,n.tenantId)}}_s.PROVIDER_ID="password",_s.EMAIL_PASSWORD_SIGN_IN_METHOD="password",_s.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class ws{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 bs extends ws{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Is extends bs{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return hi("providerId"in t&&"signInMethod"in t,"argument-error"),gs._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return hi(e.idToken||e.accessToken,"argument-error"),gs._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Is.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Is.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:a}=e;if(!(n||r||t||i))return null;if(!a)return null;try{return new Is(a)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Ts extends bs{constructor(){super("facebook.com")}static credential(e){return gs._fromParams({providerId:Ts.PROVIDER_ID,signInMethod:Ts.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Ts.credentialFromTaggedObject(e)}static credentialFromError(e){return Ts.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Ts.credential(e.oauthAccessToken)}catch(e){return null}}}Ts.FACEBOOK_SIGN_IN_METHOD="facebook.com",Ts.PROVIDER_ID="facebook.com";class Es extends bs{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return gs._fromParams({providerId:Es.PROVIDER_ID,signInMethod:Es.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Es.credentialFromTaggedObject(e)}static credentialFromError(e){return Es.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Es.credential(t,n)}catch(e){return null}}}Es.GOOGLE_SIGN_IN_METHOD="google.com",Es.PROVIDER_ID="google.com";class ks extends bs{constructor(){super("github.com")}static credential(e){return gs._fromParams({providerId:ks.PROVIDER_ID,signInMethod:ks.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ks.credentialFromTaggedObject(e)}static credentialFromError(e){return ks.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return ks.credential(e.oauthAccessToken)}catch(e){return null}}}ks.GITHUB_SIGN_IN_METHOD="github.com",ks.PROVIDER_ID="github.com";class Ss extends ls{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return fs(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,fs(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,fs(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new Ss(t,r):null}static _create(e,t){return new Ss(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Cs extends ws{constructor(e){hi(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Cs.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Cs.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Ss.fromJSON(e);return hi(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return Ss._create(n,t)}catch(e){return null}}}class As extends bs{constructor(){super("twitter.com")}static credential(e,t){return gs._fromParams({providerId:As.PROVIDER_ID,signInMethod:As.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return As.credentialFromTaggedObject(e)}static credentialFromError(e){return As.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return As.credential(t,n)}catch(e){return null}}}async function Ns(e,t){return Ci(e,"POST","/v1/accounts:signUp",Ei(e,t))}As.TWITTER_SIGN_IN_METHOD="twitter.com",As.PROVIDER_ID="twitter.com";class Rs{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await Vi._fromIdTokenResponse(e,n,r),s=xs(n);return new Rs({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=xs(n);return new Rs({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function xs(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Ds extends R{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,Ds.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new Ds(e,t,n,r)}}function Ps(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Ds._fromErrorAndOperation(t,e,n,r);throw e})}function Os(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Ms(e,t){const n=ae(e);await Fs(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await ki(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Os(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function Ls(e,t,n=!1){var r=await Oi(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Rs._forOperation(e,"link",r)}async function Fs(e,t,n){await Fi(t);const r=Os(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";hi(r.has(n)===e,t.auth,i)}async function Us(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await Oi(e,Ps(r,i,t,e),n);hi(s.idToken,r,"internal-error");var a=Pi(s.idToken);hi(a,r,"internal-error");var o=a["sub"];return hi(e.uid===o,r,"user-mismatch"),Rs._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null===e||void 0===e?void 0:e.code)&&ai(r,"user-mismatch"),e}}async function qs(e,t,n=!1){var r=await Ps(e,"signIn",t),r=await Rs._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function Vs(e,t){return qs(is(e),t)}async function Bs(e,t){var n=ae(e);return await Fs(!1,n,t.providerId),Ls(n,t)}async function js(e,t){return Us(ae(e),t)}async function Ks(e,t){const n=is(e);var r=await Ci(n,"POST","/v1/accounts:signInWithCustomToken",Ei(n,{token:t,returnSecureToken:!0})),r=await Rs._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class $s{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?Ws._fromServerResponse(e,t):ai(e,"internal-error")}}class Ws extends $s{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new Ws(t)}}function zs(e,t,n){var r;hi(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),hi(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(hi(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(hi(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function Gs(e,t,n){var r=ae(e),i={requestType:"PASSWORD_RESET",email:t};n&&zs(r,i,n),await ds(r,i)}async function Hs(e,t){await ki(e=ae(e),"POST","/v1/accounts:update",Ei(e,{oobCode:t}))}async function Qs(e,t){var n=ae(e),r=await us(n,{oobCode:t}),i=r.requestType;switch(hi(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":hi(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":hi(r.mfaInfo,n,"internal-error");default:hi(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=$s._fromServerResponse(is(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function Ys(e,t,n){var r=ae(e),i={requestType:"EMAIL_SIGNIN",email:t};hi(n.handleCodeInApp,r,"argument-error"),n&&zs(r,i,n),await ds(r,i)}async function Js(e,t){var n=vi()?mi():"http://localhost",n=(await ki(e=ae(e),"POST","/v1/accounts:createAuthUri",Ei(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function Xs(e,t){var n=ae(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&zs(n.auth,r,t);var r=(await ds(n.auth,r))["email"];r!==e.email&&await e.reload()}async function Zs(e,t,n){var r=ae(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&zs(r.auth,i,n);var i=(await ds(r.auth,i))["email"];i!==e.email&&await e.reload()}async function ea(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=ae(e);var r=await i.getIdToken(),r=await Oi(i,async function(e,t){return ki(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function ta(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await Oi(e,hs(r,i));await e._updateTokensIfNecessary(r,!0)}class na{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class ra extends na{constructor(e,t,n,r){super(e,t,n),this.username=r}}class ia extends na{constructor(e,t){super(e,"facebook.com",t)}}class sa extends ra{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class aa extends na{constructor(e,t){super(e,"google.com",t)}}class oa extends ra{constructor(e,t,n){super(e,"twitter.com",t,n)}}function ca(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=Pi(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new na(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new ia(r,n);case"github.com":return new sa(r,n);case"google.com":return new aa(r,n);case"twitter.com":return new oa(r,n,e.screenName||null);case"custom":case"anonymous":return new na(r,null);default:return new na(r,t,n)}}(n)}class la{constructor(e,t,n){this.type=e,this.credential=t,this.auth=n}static _fromIdtoken(e,t){return new la("enroll",e,t)}static _fromMfaPendingCredential(e){return new la("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)&&void 0!==t&&t.pendingCredential)return la._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return la._fromIdtoken(e.multiFactorSession.idToken)}return null}}class ua{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=is(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>$s._fromServerResponse(s,e));hi(a.mfaPendingCredential,s,"internal-error");const o=la._fromMfaPendingCredential(a.mfaPendingCredential);return new ua(o,t,async e=>{var t=await e._process(s,o);delete a.mfaInfo,delete a.mfaPendingCredential;var n=Object.assign(Object.assign({},a),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Rs._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return hi(i.user,s,"internal-error"),Rs._forOperation(i.user,i.operationType,n);default:ai(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class ha{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>$s._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new ha(e)}async getSession(){return la._fromIdtoken(await this.user.getIdToken(),this.user.auth)}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Oi(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r=await this.user.getIdToken(),r=await Oi(this.user,(n=this.user.auth,e={idToken:r,mfaEnrollmentId:t},ki(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Ei(n,e))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(r);try{await this.user.reload()}catch(e){if("auth/user-token-expired"!==(null===e||void 0===e?void 0:e.code))throw e}}}const da=new WeakMap;const pa="__sak";class fa{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(pa,"1"),this.storage.removeItem(pa),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 ga extends fa{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(Gi(e=h())||Zi(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=es(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);g()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){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]}}ga.type="LOCAL";const ma=ga;class va extends fa{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}va.type="SESSION";const ya=va;class _a{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));if(e)return e;e=new _a(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),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:n,eventType:r,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 wa(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}_a.receivers=[];class ba{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){const o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=wa("",20);o.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},a);l={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),o.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[o.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function Ia(){return window}function Ta(){return void 0!==Ia().WorkerGlobalScope&&"function"==typeof Ia().importScripts}const Ea="firebaseLocalStorageDb",ka="firebaseLocalStorage",Sa="fbase_key";class Ca{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 Aa(e,t){return e.transaction([ka],t?"readwrite":"readonly").objectStore(ka)}function Na(){const r=indexedDB.open(Ea,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(ka,{keyPath:Sa})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(ka)?n(e):(e.close(),t=indexedDB.deleteDatabase(Ea),await new Ca(t).toPromise(),n(await Na()))})})}async function Ra(e,t,n){var r=Aa(e,!0).put({fbase_key:t,value:n});return new Ca(r).toPromise()}function xa(e,t){var n=Aa(e,!0).delete(t);return new Ca(n).toPromise()}class Da{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 Na(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Ta()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=_a._getInstance(Ta()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new ba(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;var e=await Na();return await Ra(e,pa,"1"),await xa(e,pa),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ra(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=Aa(e,!1).get(t);return void 0===(n=await new Ca(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>xa(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=Aa(e,!1).getAll();return new Ca(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(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()}}Da.type="LOCAL";const Pa=Da;function Oa(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=oi("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function Ma(e){return`__${e}${Math.floor(1e6*Math.random())}`}class La{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new Fa(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class Fa{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;hi(r,"argument-error",{appName:t}),this.container=r,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=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{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!")}}const Ua=Ma("rcb"),qa=new _i(3e4,6e4);class Va{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null===(e=Ia().grecaptcha)||void 0===e||!e.render)}load(s,a=""){var e;return hi((e=a).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(a)?Promise.resolve(Ia().grecaptcha):new Promise((t,n)=>{const i=Ia().setTimeout(()=>{n(oi(s,"network-request-failed"))},qa.get());Ia()[Ua]=()=>{Ia().clearTimeout(i),delete Ia()[Ua];const e=Ia().grecaptcha;if(e){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=a,t(e)}else n(oi(s,"internal-error"))},Oa(`https://www.google.com/recaptcha/api.js??${j({onload:Ua,render:"explicit",hl:a})}`).catch(()=>{clearTimeout(i),n(oi(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null===(t=Ia().grecaptcha)||void 0===t||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class Ba{async load(e){return new La(e)}clearedOneInstance(){}}const ja="recaptcha",Ka={theme:"light",type:"image"};class $a{constructor(e,t=Object.assign({},Ka),n){this.parameters=t,this.type=ja,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=is(n),this.isInvisible="invisible"===this.parameters.size,hi("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof e?document.getElementById(e):e;hi(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?Ba:Va),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.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(){hi(!this.parameters.sitekey,this.auth,"argument-error"),hi(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),hi("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=Ia()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){hi(!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(){hi(vi()&&!Ta(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).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 ki(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");hi(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return hi(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class Wa{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=vs._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function za(t,n,r){var i,s,a,o,c,l,u=await r.verify();try{hi("string"==typeof u,t,"argument-error"),hi(r.type===ja,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return hi("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await ki(c,"POST","/v2/accounts/mfaEnrollment:start",Ei(c,l))).phoneSessionInfo.sessionInfo;hi("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return hi(d,t,"missing-multi-factor-info"),(o={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await ki(t,"POST","/v2/accounts/mfaSignIn:start",Ei(t,o))).phoneResponseInfo.sessionInfo}var p=(s=t,a={phoneNumber:e.phoneNumber,recaptchaToken:u},await ki(s,"POST","/v1/accounts:sendVerificationCode",Ei(s,a)))["sessionInfo"];return p}finally{r._reset()}}class Ga{constructor(e){this.providerId=Ga.PROVIDER_ID,this.auth=is(e)}verifyPhoneNumber(e,t){return za(this.auth,e,ae(t))}static credential(e,t){return vs._fromVerification(e,t)}static credentialFromResult(e){var t=e;return Ga.credentialFromTaggedObject(t)}static credentialFromError(e){return Ga.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?vs._fromTokenResponse(t,n):null}}function Ha(e,t){return t?gi(t):(hi(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}Ga.PROVIDER_ID="phone",Ga.PHONE_SIGN_IN_METHOD="phone";class Qa extends ls{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return fs(e,this._buildIdpRequest())}_linkToIdToken(e,t){return fs(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return fs(e,this._buildIdpRequest())}_buildIdpRequest(e){const 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 Ya(e){return qs(e.auth,new Qa(e),e.bypassAuthState)}function Ja(e){var{auth:t,user:n}=e;return hi(n,t,"internal-error"),Us(n,new Qa(e),e.bypassAuthState)}async function Xa(e){var{auth:t,user:n}=e;return hi(n,t,"internal-error"),Ls(n,new Qa(e),e.bypassAuthState)}class Za{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,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:n,postBody:r,tenantId:i,error:s,type:a}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Ya;case"linkViaPopup":case"linkViaRedirect":return Xa;case"reauthViaPopup":case"reauthViaRedirect":return Ja;default:ai(this.auth,"internal-error")}}resolve(e){pi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){pi(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()}}const eo=new _i(2e3,1e4);class to extends Za{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,to.currentPopupAction&&to.currentPopupAction.cancel(),to.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return hi(e,this.auth,"internal-error"),e}async onExecution(){pi(1===this.filter.length,"Popup operations only handle one event");var e=wa();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(oi(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(oi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,to.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(oi(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(t,eo.get())};t()}}to.currentPopupAction=null;const no="pendingRedirect",ro=new Map;class io extends Za{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=ro.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=co(t),r=oo(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}ro.set(this.auth._key(),t)}return this.bypassAuthState||ro.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function so(e,t){return oo(e)._set(co(t),"true")}function ao(e,t){ro.set(e._key(),t)}function oo(e){return gi(e._redirectPersistence)}function co(e){return Ki(no,e.config.apiKey,e.name)}function lo(e,t,n){return async function(e,t,n){var r=is(e);li(e,t,ws);const i=Ha(r,n);return await so(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function uo(e,t,n){return async function(e,t,n){var r=ae(e);li(r.auth,t,ws);const i=Ha(r.auth,n);await so(i,r.auth);var s=await fo(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function ho(e,t,n){return async function(e,t,n){var r=ae(e);li(r.auth,t,ws);const i=Ha(r.auth,n);await Fs(!1,r,t.providerId),await so(i,r.auth);var s=await fo(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function po(e,t,n=!1){const r=is(e);var i=Ha(r,t);const s=new io(r,i,n),a=await s.execute();return a&&!n&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}async function fo(e){var t=wa(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class go{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 n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return vo(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!vo(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(oi(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(mo(e))}saveEventToCache(e){this.cachedEventUids.add(mo(e)),this.lastProcessedEventTime=Date.now()}}function mo(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function vo({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function yo(e,t={}){return ki(e,"GET","/v1/projects",t)}const _o=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,wo=/^https?/;async function bo(e){if(!e.config.emulator){var t=(await yo(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=mi(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!wo.test(n))return!1;if(_o.test(e))return r===e;const s=e.replace(/\./g,"\\."),a=new RegExp("^(.+\\."+s+"|"+s+")$","i");return a.test(r)}(n))return}catch(e){}ai(e,"unauthorized-domain")}}const Io=new _i(3e4,6e4);function To(){const t=Ia().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let Eo=null;function ko(e){var i;return Eo=Eo||(i=e,new Promise((e,t)=>{function n(){To(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{To(),t(oi(i,"network-request-failed"))},timeout:Io.get()})}if(null!==(r=null===(r=Ia().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=Ia().gapi)||void 0===r||!r.load){var r=Ma("iframefcb");return Ia()[r]=()=>{gapi.load?n():t(oi(i,"network-request-failed"))},Oa(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw Eo=null,e})),Eo}const So=new _i(5e3,15e3),Co="__/auth/iframe",Ao="emulator/auth/iframe",No={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Ro=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function xo(a){const e=await ko(a);var t=Ia().gapi;return hi(t,a,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;hi(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?wi(t,Ao):`https://${e.config.authDomain}/${Co}`;const r={apiKey:t.apiKey,appName:e.name,v:Ye};(t=Ro.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${j(r).slice(1)}`}(a),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:No,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=oi(a,"network-request-failed"),r=Ia().setTimeout(()=>{t(n)},So.get());function i(){Ia().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const Do={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Po{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Oo(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let o="";const c=Object.assign(Object.assign({},Do),{width:r.toString(),height:i.toString(),top:s,left:a});s=h().toLowerCase();n&&(o=Hi(s)?"_blank":n),zi(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,a=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=h()]=[s],Zi(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==o)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",o),new Po(null);const u=window.open(t||"",o,a);hi(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Po(u)}const Mo="__/auth/handler",Lo="emulator/auth/handler";function Fo(e,t,n,r,i,s){hi(e.config.authDomain,e,"auth-domain-config-required"),hi(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Ye,eventId:i};if(t instanceof ws){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",U(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,c]of Object.entries(s||{}))a[o]=c}if(t instanceof bs){const u=t.getScopes().filter(e=>""!==e);0<u.length&&(a.scopes=u.join(","))}e.tenantId&&(a.tid=e.tenantId);const l=a;for(const h of Object.keys(l))void 0===l[h]&&delete l[h];return`${e=[e["config"]][0],e.emulator?wi(e,Lo):`https://${e.authDomain}/${Mo}`}?${j(l).slice(1)}`}const Uo="webStorageSupport";const qo=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=ya,this._completeRedirectFn=po,this._overrideRedirectResult=ao}async _openPopup(e,t,n,r){var i;return pi(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),Oo(e,Fo(e,t,n,mi(),r),wa())}async _openRedirect(e,t,n,r){return await this._originValidation(e),r=Fo(e,t,n,mi(),r),Ia().location.href=r,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(pi(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await xo(t),n=new go(t);return e.register("authEvent",e=>{return hi(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(Uo,{type:Uo},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[Uo];void 0!==t&&r(!!t),ai(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=bo(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return es()||Gi()||Zi()}};class Vo extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return di("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new Vo(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},ki(e,"POST","/v2/accounts/mfaEnrollment:finalize",Ei(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},ki(e,"POST","/v2/accounts/mfaSignIn:finalize",Ei(e,t))}}class Bo{constructor(){}static assertion(e){return Vo._fromCredential(e)}}Bo.FACTOR_ID="phone";var jo="@firebase/auth",Ko="0.20.11";class $o{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null===e||void 0===e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){hi(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var Wo,zo,Go;function Ho(){return window}Wo="authIdTokenMaxAge",null===(zo=T())||void 0===zo||zo[`_${Wo}`],Go="Browser",ze(new oe("auth",(e,{options:r})=>{var t=e.getProvider("app").getImmediate(),n=e.getProvider("heartbeat");const{apiKey:i,authDomain:s}=t.options;return((e,t)=>{hi(i&&!i.includes(":"),"invalid-api-key",{appName:e.name}),hi(!(null!==s&&void 0!==s&&s.includes(":")),"argument-error",{appName:e.name});var n={apiKey:i,authDomain:s,clientPlatform:Go,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:ts(Go)},n=new rs(e,t,n);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(gi);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(n,r),n})(t,n)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),ze(new oe("auth-internal",e=>{var t=is(e.getProvider("auth").getImmediate());return e=t,new $o(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),et(jo,Ko,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Go)),et(jo,Ko,"esm2017");async function Qo(e,t,n){var r=Ho()["BuildInfo"];pi(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(pi(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return Zi()?s.ibi=r.packageName:Yi()?s.apn=r.packageName:ai(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,Fo(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function Yo(r){const i=Ho()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=h(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const Jo=20;class Xo extends go{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function Zo(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<Jo;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:oi(e,"no-auth-event")}}async function ec(e){var t=await nc()._get(rc(e));return t&&await nc()._remove(rc(e)),t}function tc(e,t){var n,r,i;const s=(n=ic(t=t),a=n.link?decodeURIComponent(n.link):void 0,r=ic(a).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=ic(i).link)||i||r||a||t);if(s.includes("/__/auth/callback")){var a=ic(s),a=a.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(a.firebaseError)):null,a=null===(a=null===(a=null==a?void 0:a.code)||void 0===a?void 0:a.split("auth/"))||void 0===a?void 0:a[1],a=a?oi(a):null;return a?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:a,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function nc(){return gi(ma)}function rc(e){return Ki("authEvent",e.config.apiKey,e.name)}function ic(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return K(t.join("?"))}const sc=class{constructor(){this._redirectPersistence=ya,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=po,this._overrideRedirectResult=ao}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new Xo(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){ai(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,o=Ho(),hi("function"==typeof(null===(s=null==o?void 0:o.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),hi(void 0!==(null===(s=null==o?void 0:o.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),hi("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),hi("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),hi("function"==typeof(null===(o=null===(o=null==o?void 0:o.cordova)||void 0===o?void 0:o.InAppBrowser)||void 0===o?void 0:o.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const a=await this._initialize(e);await a.initialized(),a.resetRedirect(),ro.clear(),await this._originValidation(e);var o=Zo(e,n,r);n=e,r=o,await nc()._set(rc(n),r);o=await Yo(await Qo(e,o,t));return async function(a,o,c){const l=Ho()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(oi(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}o.addPassiveListener(r),document.addEventListener("resume",i,!1),Yi()&&document.addEventListener("visibilitychange",s,!1),u=()=>{o.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,a,o)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=Ho()["BuildInfo"];const n={};Zi()?n.iosBundleId=t.packageName:Yi()?n.androidPackageName=t.packageName:ai(e,"operation-not-supported-in-this-environment"),await yo(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=Ho(),s=setTimeout(async()=>{await ec(r),i.onEvent(ac())},500),a=async e=>{clearTimeout(s);var t=await ec(r);let n=null;t&&null!=e&&e.url&&(n=tc(t,e.url)),i.onEvent(n||ac())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a);const o=t,c=`${n.packageName.toLowerCase()}://`;Ho().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}};function ac(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:oi("no-auth-event")}}var oc;function cc(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function lc(e=h()){return!("file:"!==cc()&&"ionic:"!==cc()&&"capacitor:"!==cc()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function uc(e=h()){return g()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=h()]=[e],/Edge\/\d+/.test(e))}function hc(){try{const t=self.localStorage;var e=wa();if(t)return t.setItem(e,"1"),t.removeItem(e),!uc()||v()}catch(e){return dc()&&v()}return!1}function dc(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function pc(){return("http:"===cc()||"https:"===cc()||d()||lc())&&!(p()||l())&&hc()&&!dc()}function fc(){return lc()&&"undefined"!=typeof document}const gc={LOCAL:"local",NONE:"none",SESSION:"session"},mc=hi,vc="persistence";async function yc(e){await e._initializationPromise;const t=_c();var n=Ki(vc,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function _c(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const wc=hi;class bc{constructor(){this.browserResolver=gi(qo),this.cordovaResolver=gi(sc),this.underlyingResolver=null,this._redirectPersistence=ya,this._completeRedirectFn=po,this._overrideRedirectResult=ao}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return fc()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return wc(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!fc()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Ic(e){return e.unwrap()}function Tc(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===(null===t||void 0===t?void 0:t.code)){const o=t;o.resolver=new Cc(e,(n=t,i=ae(e),hi((a=n).customData.operationType,i,"argument-error"),hi(null===(r=a.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),ua._fromError(i,a)))}else if(s){var a=Ec(t);const c=t;a&&(c.credential=a,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Ec(e){var t=(e instanceof R?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof R)&&"temporaryProof"in t&&"phoneNumber"in t)return Ga.credentialFromResult(e);const n=t.providerId;if(!n||n===Xr.PASSWORD)return null;let r;switch(n){case Xr.GOOGLE:r=Es;break;case Xr.FACEBOOK:r=Ts;break;case Xr.GITHUB:r=ks;break;case Xr.TWITTER:r=As;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:c}=t;return s||a||i||o?o?n.startsWith("saml.")?Ss._create(n,o):gs._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:i,accessToken:s}):new Is(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof R?r.credentialFromError(e):r.credentialFromResult(e)}function kc(t,e){return e.catch(e=>{throw e instanceof R&&Tc(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Ec(e),additionalUserInfo:ca(e),user:Ac.getOrCreate(n)}})}async function Sc(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>kc(t,n.confirm(e))}}class Cc{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 kc(Ic(this.auth),this.resolver.resolveSignIn(e))}}class Ac{constructor(e){var t;this._delegate=e,this.multiFactor=(t=ae(e),da.has(t)||da.set(t,ha._fromUser(t)),da.get(t))}static getOrCreate(e){return Ac.USER_MAP.has(e)||Ac.USER_MAP.set(e,new Ac(e)),Ac.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 kc(this.auth,Bs(this._delegate,e))}async linkWithPhoneNumber(e,t){return Sc(this.auth,async function(e,t,n){const r=ae(e);await Fs(!1,r,"phone");var i=await za(r.auth,t,ae(n));return new Wa(i,e=>Bs(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return kc(this.auth,async function(e,t,n){var r=ae(e);li(r.auth,t,ws);var i=Ha(r.auth,n);const s=new to(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,bc))}async linkWithRedirect(e){return await yc(is(this.auth)),ho(this._delegate,e,bc)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return kc(this.auth,js(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Sc(this.auth,async function(e,t,n){const r=ae(e);var i=await za(r.auth,t,ae(n));return new Wa(i,e=>js(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return kc(this.auth,async function(e,t,n){var r=ae(e);li(r.auth,t,ws);var i=Ha(r.auth,n);const s=new to(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,bc))}async reauthenticateWithRedirect(e){return await yc(is(this.auth)),uo(this._delegate,e,bc)}sendEmailVerification(e){return Xs(this._delegate,e)}async unlink(e){return await Ms(this._delegate,e),this}updateEmail(e){return ta(ae(this._delegate),e,null)}updatePassword(e){return ta(ae(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await Ls(ae(e),t)}(this._delegate,e)}updateProfile(e){return ea(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return Zs(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}}Ac.USER_MAP=new WeakMap;const Nc=hi;class Rc{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Nc(n,"invalid-api-key",{appName:e.name}),Nc(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?bc:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=_c();if(!n)return[];var r=Ki(vc,e,t);switch(n.getItem(r)){case gc.NONE:return[ji];case gc.LOCAL:return[Pa,ya];case gc.SESSION:return[ya];default:return[]}}(e,t);"undefined"==typeof self||n.includes(Pa)||n.push(Pa);if("undefined"!=typeof window)for(const r of[ma,ya])n.includes(r)||n.push(r);n.includes(ji)||n.push(ji);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(ti),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Ac.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){as(this._delegate,e,t)}applyActionCode(e){return Hs(this._delegate,e)}checkActionCode(e){return Qs(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await us(ae(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return kc(this._delegate,async function(e,t,n){const r=is(e);var i=await Ns(r,{returnSecureToken:!0,email:t,password:n}),i=await Rs._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(i.user),i}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return Js(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=ys.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Nc(pc(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=bc,await is(e)._initializationPromise,await po(e,t,!1));return n?kc(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){is(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=xc(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=xc(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return Ys(this._delegate,e,t)}sendPasswordResetEmail(e,t){return Gs(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,mc(Object.values(gc).includes(n),t,"invalid-persistence-type"),p()?mc(n!==gc.SESSION,t,"unsupported-persistence-type"):l()?mc(n===gc.NONE,t,"unsupported-persistence-type"):dc()?mc(n===gc.NONE||n===gc.LOCAL&&v(),t,"unsupported-persistence-type"):mc(n===gc.NONE||hc(),t,"unsupported-persistence-type");let r;switch(e){case gc.SESSION:r=ya;break;case gc.LOCAL:var i=await gi(Pa)._isAvailable();r=i?Pa:ma;break;case gc.NONE:r=ji;break;default:return ai("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return kc(this._delegate,async function(e){const t=is(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Rs({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await Ns(t,{returnSecureToken:!0}),n=await Rs._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return kc(this._delegate,Vs(this._delegate,e))}signInWithCustomToken(e){return kc(this._delegate,Ks(this._delegate,e))}signInWithEmailAndPassword(e,t){return kc(this._delegate,(n=this._delegate,e=e,t=t,Vs(ae(n),_s.credential(e,t))));var n}signInWithEmailLink(e,t){return kc(this._delegate,async function(e,t,n){var r=ae(e),i=_s.credentialWithLink(t,n||mi());return hi(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),Vs(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Sc(this._delegate,async function(e,t,n){const r=is(e);var i=await za(r,t,ae(n));return new Wa(i,e=>Vs(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Nc(pc(),this._delegate,"operation-not-supported-in-this-environment"),kc(this._delegate,async function(e,t,n){var r=is(e);li(e,t,ws);var i=Ha(r,n);const s=new to(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,bc))}async signInWithRedirect(e){return Nc(pc(),this._delegate,"operation-not-supported-in-this-environment"),await yc(this._delegate),lo(this._delegate,e,bc)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await Qs(ae(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function xc(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&Ac.getOrCreate(e)),error:t,complete:n}}Rc.Persistence=gc;class Dc{constructor(){this.providerId="phone",this._delegate=new Ga(Ic(wt.auth()))}static credential(e,t){return Ga.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Dc.PHONE_SIGN_IN_METHOD=Ga.PHONE_SIGN_IN_METHOD,Dc.PROVIDER_ID=Ga.PROVIDER_ID;const Pc=hi;class Oc{constructor(e,t,n=wt.app()){var r;Pc(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new $a(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(oc=wt).INTERNAL.registerComponent(new oe("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new Rc(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:Zr.EMAIL_SIGNIN,PASSWORD_RESET:Zr.PASSWORD_RESET,RECOVER_EMAIL:Zr.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:Zr.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:Zr.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:Zr.VERIFY_EMAIL}},EmailAuthProvider:_s,FacebookAuthProvider:Ts,GithubAuthProvider:ks,GoogleAuthProvider:Es,OAuthProvider:Is,SAMLAuthProvider:Cs,PhoneAuthProvider:Dc,PhoneMultiFactorGenerator:Bo,RecaptchaVerifier:Oc,TwitterAuthProvider:As,Auth:Rc,AuthCredential:ls,Error:R}).setInstantiationMode("LAZY").setMultipleInstances(!1)),oc.registerVersion("@firebase/auth-compat","0.2.24");const Mc="@firebase/database",Lc="0.13.10";let Fc="";function Uc(e){Fc=e}class qc{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),O(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:P(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Vc{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return L(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var Bc,jc,Kc,$c,Wc,zc,Gc=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new qc(t)}}catch(e){}return new Vc};function Hc(e){var t=function(t){const n=[];let r=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);var i,s;55296<=e&&e<=56319&&(i=e-55296,a++,f(a<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(a)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new W;return n.update(t),t=n.digest(),r.encodeByteArray(t)}const Qc=Gc("localStorage"),Yc=Gc("sessionStorage"),Jc=new me("@firebase/database"),Xc=function(){let e=1;return function(){return e++}}(),Zc=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=Zc.apply(null,n):t+="object"==typeof n?O(n):n,t+=" "}return t};let el=null,tl=!0;function nl(t){return function(...e){ll(t,...e)}}function rl(...e){var t="FIREBASE INTERNAL ERROR: "+Zc(...e);Jc.error(t)}function il(e,t){return e===t?0:e<t?-1:1}function sl(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+O(t))}function al(e){if("object"!=typeof e||null===e)return O(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=O(t[i]),n+=":",n+=al(e[t[i]]);return n+="}",n}function ol(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const cl=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(Jc.logLevel=k.VERBOSE,el=Jc.log.bind(Jc),t&&Yc.set("logging_enabled",!0)):"function"==typeof e?el=e:(el=null,Yc.remove("logging_enabled"))},ll=function(...e){var t;!0===tl&&(tl=!1,null===el&&!0===Yc.get("logging_enabled")&&cl(!0)),el&&(t=Zc.apply(null,e),el(t))},ul=function(...e){var t=`FIREBASE FATAL ERROR: ${Zc(...e)}`;throw Jc.error(t),new Error(t)},hl=function(...e){var t="FIREBASE WARNING: "+Zc(...e);Jc.warn(t)},dl=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&hl("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},pl=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},fl="[MIN_NAME]",gl="[MAX_NAME]",ml=function(e,t){if(e===t)return 0;if(e===fl||t===gl)return-1;if(t===fl||e===gl)return 1;var n=Tl(e),r=Tl(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function vl(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function yl(e){f(!pl(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const a=[];for(s=52;s;--s)a.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse();const o=a.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(o.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function _l(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}const wl=new RegExp("^-?(0*)\\d{1,10}$"),bl=-2147483648,Il=2147483647,Tl=function(e){if(wl.test(e)){var t=Number(e);if(t>=bl&&t<=Il)return t}return null},El=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw hl("Exception was thrown by user callback.",e),t},Math.floor(0))}};class kl{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(e=>this.appCheck=e)}getToken(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){hl(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Sl{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(ll("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',hl(e)}}class Cl{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Cl.OWNER="owner";const Al=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Nl="websocket",Rl="long_polling";class xl{constructor(e,t,n,r,i=!1,s="",a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Qc.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()&&Qc.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 Dl(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===Nl)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Rl)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return vl(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class Pl{constructor(){this.counters_={}}incrementCounter(e,t=1){L(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return c(void 0,this.counters_)}}const Ol={},Ml={};function Ll(e){var t=e.toString();return Ol[t]||(Ol[t]=new Pl),Ol[t]}class Fl{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&El(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Ul{constructor(e,t,n,r,i,s,a){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=nl(e),this.stats_=Ll(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Dl(t,Rl,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Fl(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new ql((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Al.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Ul.forceAllow_=!0}static forceDisallow(){Ul.forceDisallow_=!0}static isAvailable(){return!!Ul.forceAllow_||!(Ul.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=O(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=i(t),n=ol(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=O(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class ql{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=Xc(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=ql.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){ll("frame writing exception"),e.stack&&ll(e.stack),ll(e)}}}static createIFrame_(){const 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||ll("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{ll("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let Vl=null;"undefined"!=typeof MozWebSocket?Vl=MozWebSocket:"undefined"!=typeof WebSocket&&(Vl=WebSocket);class Bl{constructor(e,t,n,r,i,s,a){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=nl(this.connId),this.stats_=Ll(t),this.connURL=Bl.connectionURL_(t,s,a,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={v:"5"};return"undefined"!=typeof location&&location.hostname&&Al.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),Dl(e,Nl,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Qc.set("previous_websocket_failure",!0);try{m(),this.mySock=new Vl(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Bl.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==Vl&&!Bl.forceDisallow_}static previouslyFailed(){return Qc.isInMemoryStorage||!0===Qc.get("previous_websocket_failure")}markConnectionHealthy(){Qc.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=P(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=O(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=ol(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}Bl.responsesRequiredToBeHealthy=2,Bl.healthyTimeout=3e4;class jl{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Ul,Bl]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){var t=Bl&&Bl.isAvailable();let n=t&&!Bl.previouslyFailed();if(e.webSocketOnly&&(t||hl("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[Bl];else{const r=this.transports_=[];for(const i of jl.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i);jl.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}}jl.globalTransportInitialized_=!1;class Kl{constructor(e,t,n,r,i,s,a,o,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=o,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=nl("c:"+this.id+":"),this.transportManager_=new jl(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=_l(()=>{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(r)))}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=sl("t",e),n=sl("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=sl("t",e),n=sl("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=sl("t",e);if("d"in e){var n=e.d;if("h"===t)this.onHandshake_(n);else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?rl("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):rl("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&hl("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),_l(()=>{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):_l(()=>{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()&&(Qc.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 $l{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class Wl{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class zl extends Wl{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||o()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new zl}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class Gl{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function Hl(){return new Gl("")}function Ql(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function Yl(e){return e.pieces_.length-e.pieceNum_}function Jl(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new Gl(e.pieces_,t)}function Xl(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function Zl(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function eu(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new Gl(t,0)}function tu(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof Gl)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new Gl(n,0)}function nu(e){return e.pieceNum_>=e.pieces_.length}function ru(e,t){var n=Ql(e),r=Ql(t);if(null===n)return t;if(n===r)return ru(Jl(e),Jl(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function iu(e,t){var n=Zl(e,0),r=Zl(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=ml(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function su(e,t){if(Yl(e)!==Yl(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function au(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(Yl(e)>Yl(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class ou{constructor(e,t){this.errorPrefix_=t,this.parts_=Zl(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=ee(this.parts_[n]);cu(this)}}function cu(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+lu(e))}function lu(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class uu extends Wl{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)}static getInstance(){return new uu}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class hu extends $l{constructor(e,t,n,r,i,s,a,o){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=a,this.authOverride_=o,this.id=hu.nextPersistentConnectionId_++,this.log_=nl("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&&!m())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");uu.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&zl.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(O(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new A;var t={p:e._path.toString(),q:e._queryObject};this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++;t=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var a={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,a),this.connected_&&this.sendListen_(a)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),a=i._queryIdentifier;this.log_("Listen on "+s+" for "+a);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;hu.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(a))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,a),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&L(e,"w")){const i=F(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),hl("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} to your security rules for better performance.`))}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=M(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_){const r=this.authToken_;var e=function(e){const t=M(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+O(e));var t=e.r;const n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):rl("Unrecognized action received from server: "+O(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){f(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(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 e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+hu.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,u())};this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var o=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(o),this.appCheckTokenProvider_.getToken(o)]);t?ll("getToken() completed but was canceled"):(ll("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new Kl(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{hl(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&hl(e),a())}}}interrupt(e){ll("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){ll("Resuming connection for reason: "+e),delete this.interruptReasons_[e],U(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 e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>al(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new Gl(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){ll("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){ll("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(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+Fc.replace(/\./g,"-")]=1,o()?e["framework.cordova"]=1:p()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=zl.getInstance().currentlyOnline();return U(this.interruptReasons_)&&e}}hu.nextPersistentConnectionId_=0,hu.nextConnectionId_=0;class du{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new du(e,t)}}class pu{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new du(fl,e),r=new du(fl,t);return 0!==this.compare(n,r)}minPost(){return du.MIN}}let fu;class gu extends pu{static get __EMPTY_NODE(){return fu}static set __EMPTY_NODE(e){fu=e}compare(e,t){return ml(e.name,t.name)}isDefinedOn(e){throw u("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return du.MIN}maxPost(){return new du(gl,fu)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new du(e,fu)}toString(){return".key"}}const mu=new gu;class vu{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class yu{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:yu.RED,this.left=null!=r?r:_u.EMPTY_NODE,this.right=null!=i?i:_u.EMPTY_NODE}copy(e,t,n,r,i){return new yu(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return _u.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return _u.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,yu.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,yu.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}yu.RED=!0,yu.BLACK=!1;class _u{constructor(e,t=_u.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new _u(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,yu.BLACK,null,null))}remove(e){return new _u(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,yu.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new vu(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new vu(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new vu(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new vu(this.root_,null,this.comparator_,!0,e)}}function wu(e,t){return ml(e.name,t.name)}function bu(e,t){return ml(e,t)}_u.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new yu(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let Iu;function Tu(e){return"number"==typeof e?"number:"+yl(e):"string:"+e}function Eu(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&L(t,".sv"),"Priority must be a string or number.")):f(e===Iu||e.isEmpty(),"priority of unexpected type."),f(e===Iu||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let ku;class Su{constructor(e,t=Su.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Eu(this.priorityNode_)}static set __childrenNodeConstructor(e){ku=e}static get __childrenNodeConstructor(){return ku}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Su(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Su.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return nu(e)?this:".priority"===Ql(e)?this.priorityNode_:Su.__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:Su.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=Ql(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===Yl(e),".priority must be the last token in a path"),this.updateImmediateChild(n,Su.__childrenNodeConstructor.EMPTY_NODE.updateChild(Jl(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:"+Tu(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?yl(this.value_):this.value_,this.lazyHash_=Hc(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Su.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Su.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=Su.VALUE_TYPE_ORDER.indexOf(t),i=Su.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}Su.VALUE_TYPE_ORDER=["object","boolean","number","string"];let Cu,Au;const Nu=new class extends pu{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?ml(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return du.MIN}maxPost(){return new du(gl,new Su("[PRIORITY-POST]",Au))}makePost(e,t){var n=Cu(e);return new du(t,new Su("[PRIORITY-POST]",n))}toString(){return".priority"}},Ru=Math.log(2);class xu{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Ru,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function Du(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new yu(i,r.node,yu.BLACK,null,null);var s=parseInt(n/2,10)+e,a=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new yu(i,r.node,yu.BLACK,a,n)};var n=function(e){let s=null,a=null,o=c.length;function t(e,t){var n=o-e,r=o;o-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{a=e;s=e}}(new yu(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,yu.BLACK):(t(r,yu.BLACK),t(r,yu.RED))}return a}(new xu(c.length));return new _u(t||e,n)}let Pu;const Ou={};class Mu{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return f((Ou,Nu),"ChildrenNode.ts has not been loaded"),Pu=Pu||new Mu({".priority":Ou},{".priority":Nu}),Pu}get(e){var t=F(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof _u?t:null}hasIndex(e){return L(this.indexSet_,e.toString())}addIndex(e,t){f(e!==mu,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(du.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let a;a=r?Du(n,e.getCompare()):Ou;var o=e.toString();const c=Object.assign({},this.indexSet_);c[o]=e;const l=Object.assign({},this.indexes_);return l[o]=a,new Mu(l,c)}addToIndexes(a,o){var e=q(this.indexes_,(t,e)=>{const n=F(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Ou){if(n.isDefinedOn(a.node)){const i=[],s=o.getIterator(du.Wrap);let e=s.getNext();for(;e;)e.name!==a.name&&i.push(e),e=s.getNext();return i.push(a),Du(i,n.getCompare())}return Ou}{var r=o.get(a.name);let e=t;return r&&(e=e.remove(new du(a.name,r))),e.insert(a,a.node)}});return new Mu(e,this.indexSet_)}removeFromIndexes(n,r){var e=q(this.indexes_,e=>{if(e===Ou)return e;var t=r.get(n.name);return t?e.remove(new du(n.name,t)):e});return new Mu(e,this.indexSet_)}}let Lu;class Fu{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Eu(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Lu=Lu||new Fu(new _u(bu),null,Mu.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Lu}updatePriority(e){return this.children_.isEmpty()?this:new Fu(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?Lu:t}getChild(e){var t=Ql(e);return null===t?this:this.getImmediateChild(t).getChild(Jl(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new du(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Lu:this.priorityNode_;return new Fu(e,i,t)}}updateChild(e,t){var n=Ql(e);if(null===n)return t;f(".priority"!==Ql(e)||1===Yl(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(Jl(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,a=!0;if(this.forEachChild(Nu,(e,t)=>{r[e]=t.val(n),i++,a&&Fu.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):a=!1}),!n&&a&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+Tu(this.getPriority().val())+":"),this.forEachChild(Nu,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":Hc(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new du(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new du(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new du(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,du.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,du.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===qu?-1:0}withIndex(e){if(e===mu||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new Fu(this.children_,this.priorityNode_,t)}isIndexed(e){return e===mu||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(Nu),i=n.getIterator(Nu);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===mu?null:this.indexMap_.get(e.toString())}}Fu.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Uu extends Fu{constructor(){super(new _u(bu),Fu.EMPTY_NODE,Mu.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return Fu.EMPTY_NODE}isEmpty(){return!1}}const qu=new Uu;Object.defineProperties(du,{MIN:{value:new du(fl,Fu.EMPTY_NODE)},MAX:{value:new du(gl,qu)}}),gu.__EMPTY_NODE=Fu.EMPTY_NODE,Su.__childrenNodeConstructor=Fu,Bc=qu,Iu=Bc,jc=qu,Au=jc;const Vu=!0;function Bu(i,e=null){if(null===i)return Fu.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new Su(t,Bu(e))}if(i instanceof Array||!Vu){let r=Fu.EMPTY_NODE;return vl(i,(e,t)=>{if(L(i,e)&&"."!==e.substring(0,1)){const n=Bu(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(Bu(e))}{const s=[];let r=!1;if(vl(i,(e,t)=>{if("."!==e.substring(0,1)){const n=Bu(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new du(e,n)))}}),0===s.length)return Fu.EMPTY_NODE;var n=Du(s,wu,e=>e.name,bu);if(r){t=Du(s,Nu.getCompare());return new Fu(n,Bu(e),new Mu({".priority":t},{".priority":Nu}))}return new Fu(n,Bu(e),Mu.Default)}}Cu=Bu;class ju extends pu{constructor(e){super(),this.indexPath_=e,f(!nu(e)&&".priority"!==Ql(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){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?ml(e.name,t.name):r}makePost(e,t){var n=Bu(e),n=Fu.EMPTY_NODE.updateChild(this.indexPath_,n);return new du(t,n)}maxPost(){var e=Fu.EMPTY_NODE.updateChild(this.indexPath_,qu);return new du(gl,e)}toString(){return Zl(this.indexPath_,0).join("/")}}function Ku(e){if(e===""+Il)return Gu;var t=Tl(e);if(null!=t)return""+(t+1);const n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e.charAt(i);if(n.length<Qu)return n.push(Gu),n.join("");let r=n.length-1;for(;0<=r&&n[r]===Hu;)r--;return-1===r?gl:(t=n[r],t=zu.charAt(zu.indexOf(t)+1),n[r]=t,n.slice(0,r+1).join(""))}function $u(e){if(e===""+bl)return fl;var t=Tl(e);if(null!=t)return""+(t-1);const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e.charAt(r);return n[n.length-1]===Gu?1===n.length?""+Il:(delete n[n.length-1],n.join("")):(n[n.length-1]=zu.charAt(zu.indexOf(n[n.length-1])-1),n.join("")+Hu.repeat(Qu-n.length))}const Wu=new class extends pu{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?ml(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return du.MIN}maxPost(){return du.MAX}makePost(e,t){var n=Bu(e);return new du(t,n)}toString(){return".value"}},zu="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Gu="-",Hu="z",Qu=786,Yu=function(){let s=0;const a=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=zu.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===a[n];n--)a[n]=0;a[n]++}else for(n=0;n<12;n++)a[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=zu.charAt(a[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}}();function Ju(e){return{type:"value",snapshotNode:e}}function Xu(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function Zu(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function eh(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class th{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(r).equals(n.getChild(r))&&a.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(Zu(t,a)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(Xu(t,n)):s.trackChildChange(eh(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(Nu,(e,t)=>{n.hasChild(e)||i.trackChildChange(Zu(e,t))}),n.isLeafNode()||n.forEachChild(Nu,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(eh(e,t,n))}else i.trackChildChange(Xu(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?Fu.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class nh{constructor(e){this.indexedFilter_=new th(e.getIndex()),this.index_=e.getIndex(),this.startPost_=nh.getStartPost_(e),this.endPost_=nh.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0}updateChild(e,t,n,r,i,s){return this.matches(new du(t,n))||(n=Fu.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?Fu.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(Fu.EMPTY_NODE);const i=this;return t.forEachChild(Nu,(e,t)=>{i.matches(new du(e,t))||(r=r.updateImmediateChild(e,Fu.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class rh{constructor(e){this.rangedFilter_=new nh(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new du(t,n))||(n=Fu.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,a,t){let o;if(a.isLeafNode()||a.isEmpty())o=Fu.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<a.numChildren()&&a.isIndexed(this.index_)){o=Fu.EMPTY_NODE.withIndex(this.index_);let t;t=this.reverse_?a.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):a.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;t.hasNext()&&n<this.limit_;){var r=t.getNext();let e;if(e=this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),r)<=0:this.index_.compare(r,this.rangedFilter_.getEndPost())<=0,!e)break;o=o.updateImmediateChild(r.name,r.node),n++}}else{o=a.withIndex(this.index_),o=o.updatePriority(Fu.EMPTY_NODE);let e,t,n,r;if(this.reverse_){r=o.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),t=this.rangedFilter_.getStartPost();const l=this.index_.getCompare();n=(e,t)=>l(t,e)}else r=o.getIterator(this.index_),e=this.rangedFilter_.getStartPost(),t=this.rangedFilter_.getEndPost(),n=this.index_.getCompare();let i=0,s=!1;for(;r.hasNext();){var c=r.getNext();!s&&n(e,c)<=0&&(s=!0),s&&i<this.limit_&&n(c,t)<=0?i++:o=o.updateImmediateChild(c.name,Fu.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,o,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const a=e;f(a.numChildren()===this.limit_,"");var o=new du(t,n),c=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),l=this.rangedFilter_.matches(o);if(a.hasChild(t)){var u=a.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||a.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,o);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(eh(t,n,u)),a.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(Zu(t,u));const p=a.updateImmediateChild(t,Fu.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(Xu(e.name,e.node)),p.updateImmediateChild(e.name,e.node)):p}}return!n.isEmpty()&&l&&0<=s(c,o)?(null!=i&&(i.trackChildChange(Zu(c.name,c.node)),i.trackChildChange(Xu(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(c.name,Fu.EMPTY_NODE)):e}}class ih{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_=Nu}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:fl}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:gl}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===Nu}copy(){const e=new ih;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function sh(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function ah(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function oh(e,t){const n=e.copy();return n.index_=t,n}function ch(e){const t={};if(e.isDefault())return t;let n;return n=e.index_===Nu?"$priority":e.index_===Wu?"$value":e.index_===mu?"$key":(f(e.index_ instanceof ju,"Unrecognized index type!"),e.index_.toString()),t.orderBy=O(n),e.startSet_&&(t.startAt=O(e.indexStartValue_),e.startNameSet_&&(t.startAt+=","+O(e.indexStartName_))),e.endSet_&&(t.endAt=O(e.indexEndValue_),e.endNameSet_&&(t.endAt+=","+O(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function lh(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_)),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_)),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==Nu&&(n.i=t.index_.toString()),n}class uh extends $l{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=nl("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const a=uh.getListenId_(e,r),o={};this.listens_[a]=o;var n=ch(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),F(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=uh.getListenId_(e,t);delete this.listens_[n]}get(e){var t=ch(e._queryParams);const r=e._path.toString(),i=new A;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},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);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+j(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(a&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=P(r.responseText)}catch(e){hl("Failed to parse JSON response for "+n+": "+r.responseText)}a(null,e)}else 401!==r.status&&404!==r.status&&hl("Got unsuccessful REST response for "+n+" Status: "+r.status),a(r.status);a=null}},r.open("GET",n,!0),r.send()})}}class hh{constructor(){this.rootNode_=Fu.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function dh(){return{value:null,children:new Map}}function ph(e,t,n){var r;nu(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=Ql(t),e.children.has(r)||e.children.set(r,dh()),ph(e.children.get(r),t=Jl(t),n))}function fh(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{fh(t,new Gl(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class gh{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&vl(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class mh{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new gh(e);var n=1e4+2e4*Math.random();_l(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;vl(e,(e,t)=>{0<t&&L(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),_l(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function vh(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function yh(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function _h(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(KS=Kc=Kc||{})[KS.OVERWRITE=0]="OVERWRITE",KS[KS.MERGE=1]="MERGE",KS[KS.ACK_USER_WRITE=2]="ACK_USER_WRITE",KS[KS.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class wh{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Kc.ACK_USER_WRITE,this.source=vh()}operationForChild(e){if(nu(this.path)){if(null!=this.affectedTree.value)return f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new Gl(e));return new wh(Hl(),t,this.revert)}return f(Ql(this.path)===e,"operationForChild called for unrelated child."),new wh(Jl(this.path),this.affectedTree,this.revert)}}class bh{constructor(e,t){this.source=e,this.path=t,this.type=Kc.LISTEN_COMPLETE}operationForChild(e){return nu(this.path)?new bh(this.source,Hl()):new bh(this.source,Jl(this.path))}}class Ih{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Kc.OVERWRITE}operationForChild(e){return nu(this.path)?new Ih(this.source,Hl(),this.snap.getImmediateChild(e)):new Ih(this.source,Jl(this.path),this.snap)}}class Th{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Kc.MERGE}operationForChild(e){if(nu(this.path)){const t=this.children.subtree(new Gl(e));return t.isEmpty()?null:t.value?new Ih(this.source,Hl(),t.value):new Th(this.source,Hl(),t)}return f(Ql(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Th(this.source,Jl(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Eh{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(nu(e))return this.isFullyInitialized()&&!this.filtered_;var t=Ql(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class kh{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Sh(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),Ch(n,i,"child_removed",e,r,t),Ch(n,i,"child_added",e,r,t),Ch(n,i,"child_moved",s,r,t),Ch(n,i,"child_changed",e,r,t),Ch(n,i,"value",e,r,t),i}function Ch(s,a,t,e,o,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw u("Should only compare child_ events.");var r=new du(t.childName,t.snapshotNode),i=new du(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;o.forEach(e=>{e.respondsTo(t.type)&&a.push(e.createEvent(n,s.query_))})})}function Ah(e,t){return{eventCache:e,serverCache:t}}function Nh(e,t,n,r){return Ah(new Eh(t,n,r),e.serverCache)}function Rh(e,t,n,r){return Ah(e.eventCache,new Eh(t,n,r))}function xh(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Dh(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Ph;class Oh{constructor(e,t=(Ph=Ph||new _u(il),Ph)){this.value=e,this.children=t}static fromObject(e){let n=new Oh(null);return vl(e,(e,t)=>{n=n.set(new Gl(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:Hl(),value:this.value};if(nu(e))return null;{var n=Ql(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(Jl(e),t);return null==r?null:{path:tu(new Gl(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(nu(e))return this;{var t=Ql(e);const n=this.children.get(t);return null!==n?n.subtree(Jl(e)):new Oh(null)}}set(e,t){if(nu(e))return new Oh(t,this.children);{var n=Ql(e);const i=this.children.get(n)||new Oh(null);var r=i.set(Jl(e),t),r=this.children.insert(n,r);return new Oh(this.value,r)}}remove(t){if(nu(t))return this.children.isEmpty()?new Oh(null):new Oh(null,this.children);{var n=Ql(t);const r=this.children.get(n);if(r){const i=r.remove(Jl(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new Oh(null):new Oh(this.value,e)}return this}}get(e){if(nu(e))return this.value;{var t=Ql(e);const n=this.children.get(t);return n?n.get(Jl(e)):null}}setTree(t,n){if(nu(t))return n;{var r=Ql(t);const i=this.children.get(r)||new Oh(null),s=i.setTree(Jl(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new Oh(this.value,e)}}fold(e){return this.fold_(Hl(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(tu(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,Hl(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(nu(e))return null;{r=Ql(e);const i=this.children.get(r);return i?i.findOnPath_(Jl(e),tu(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,Hl(),t)}foreachOnPath_(e,t,n){if(nu(e))return this;{this.value&&n(t,this.value);var r=Ql(e);const i=this.children.get(r);return i?i.foreachOnPath_(Jl(e),tu(t,r),n):new Oh(null)}}foreach(e){this.foreach_(Hl(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(tu(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class Mh{constructor(e){this.writeTree_=e}static empty(){return new Mh(new Oh(null))}}function Lh(t,n,r){if(nu(n))return new Mh(new Oh(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=ru(s,n);return e=e.updateChild(i,r),new Mh(t.writeTree_.set(s,e))}s=new Oh(r),s=t.writeTree_.setTree(n,s);return new Mh(s)}function Fh(e,n,t){let r=e;return vl(t,(e,t)=>{r=Lh(r,tu(n,e),t)}),r}function Uh(e,t){if(nu(t))return Mh.empty();var n=e.writeTree_.setTree(t,new Oh(null));return new Mh(n)}function qh(e,t){return null!=Vh(e,t)}function Vh(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(ru(n.path,t)):null}function Bh(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(Nu,(e,t)=>{n.push(new du(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new du(e,t.value))}),n}function jh(e,t){if(nu(t))return e;var n=Vh(e,t);return null!=n?new Mh(new Oh(n)):new Mh(e.writeTree_.subtree(t))}function Kh(e){return e.writeTree_.isEmpty()}function $h(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(tu(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(tu(i,".priority"),n):s}}}(Hl(),e.writeTree_,t)}function Wh(e,t){return rd(t,e)}function zh(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,a=!1,o=t.allWrites.length-1;for(;s&&0<=o;){var c=t.allWrites[o];c.visible&&(o>=r&&function(e,t){{if(e.snap)return au(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&au(tu(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:au(i.path,c.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=Hh(e.allWrites,Gh,Hl()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=Uh(t.visibleWrites,i.path):vl(i.children,e=>{t.visibleWrites=Uh(t.visibleWrites,tu(i.path,e))}),!0)}function Gh(e){return e.visible}function Hh(e,t,n){let r=Mh.empty();for(let s=0;s<e.length;++s){const a=e[s];if(t(a)){var i=a.path;let e;if(a.snap)au(n,i)?(e=ru(n,i),r=Lh(r,e,a.snap)):au(i,n)&&(e=ru(i,n),r=Lh(r,Hl(),a.snap.getChild(e)));else{if(!a.children)throw u("WriteRecord should have .snap or .children");if(au(n,i))e=ru(n,i),r=Fh(r,e,a.children);else if(au(i,n))if(e=ru(i,n),nu(e))r=Fh(r,Hl(),a.children);else{const o=F(a.children,Ql(e));o&&(i=o.getChild(Jl(e)),r=Lh(r,Hl(),i))}}}}return r}function Qh(e,t,n,r,i){if(r||i){var s=jh(e.visibleWrites,t);if(!i&&Kh(s))return n;if(i||null!=n||qh(s,Hl()))return $h(Hh(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(au(e.path,t)||au(t,e.path))},t),n||Fu.EMPTY_NODE);return null}s=Vh(e.visibleWrites,t);if(null!=s)return s;s=jh(e.visibleWrites,t);return Kh(s)?n:null!=n||qh(s,Hl())?$h(s,n||Fu.EMPTY_NODE):null}function Yh(e,t,n,r){return Qh(e.writeTree,e.treePath,t,n,r)}function Jh(e,t){return function(e,t,n){let r=Fu.EMPTY_NODE;const i=Vh(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(Nu,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=jh(e.visibleWrites,t);return n.forEachChild(Nu,(e,t)=>{var n=$h(jh(s,new Gl(e)),t);r=r.updateImmediateChild(e,n)}),Bh(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return Bh(jh(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function Xh(e,t,n,r){return function(e,t,n,r,i){f(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=tu(t,n);return qh(e.visibleWrites,s)?null:Kh(s=jh(e.visibleWrites,s))?i.getChild(n):$h(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function Zh(e,t){return n=e.writeTree,t=tu(e.treePath,t),Vh(n.visibleWrites,t);var n}function ed(e,t,n,r,i,s){return function(e,t,n,r,i,s,a){let o;var c=jh(e.visibleWrites,t),l=Vh(c,Hl());if(null!=l)o=l;else{if(null==n)return[];o=$h(c,n)}if(o=o.withIndex(a),o.isEmpty()||o.isLeafNode())return[];{const u=[],h=a.getCompare(),d=s?o.getReverseIteratorFrom(r,a):o.getIteratorFrom(r,a);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function td(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=tu(e,t=t),null!=(s=Vh(r.visibleWrites,i))?s:n.isCompleteForChild(t)?$h(jh(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function nd(e,t){return rd(tu(e.treePath,t),e.writeTree)}function rd(e,t){return{treePath:e,writeTree:t}}class id{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,eh(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,Zu(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,Xu(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw u("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,eh(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const sd=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class ad{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new Eh(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return td(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Dh(this.viewCache_),r=ed(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function od(e,t,n,r,i){const s=new id;let a,o;if(n.type===Kc.OVERWRITE){var c=n;a=c.source.fromUser?ud(e,t,c.path,c.snap,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered()&&!nu(c.path),ld(e,t,c.path,c.snap,r,i,o,s))}else if(n.type===Kc.MERGE){c=n;a=c.source.fromUser?function(r,i,s,e,a,o,c){let l=i;return e.foreach((e,t)=>{var n=tu(s,e);hd(i,Ql(n))&&(l=ud(r,l,n,t,a,o,c))}),e.foreach((e,t)=>{var n=tu(s,e);hd(i,Ql(n))||(l=ud(r,l,n,t,a,o,c))}),l}(e,t,c.path,c.children,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered(),pd(e,t,c.path,c.children,r,i,o,s))}else if(n.type===Kc.ACK_USER_WRITE){var l=n;a=l.revert?function(n,r,i,s,e,a){let o;{if(null!=Zh(s,i))return r;{var c=new ad(s,r,e);const u=r.eventCache.getNode();let t;if(nu(i)||".priority"===Ql(i)){let e;e=r.serverCache.isFullyInitialized()?Yh(s,Dh(r)):(l=r.serverCache.getNode(),f(l instanceof Fu,"serverChildren would be complete if leaf node"),Jh(s,l)),e=e,t=n.filter.updateFullNode(u,e,a)}else{var l=Ql(i);let e=td(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,Jl(i),c,a):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,Fu.EMPTY_NODE,Jl(i),c,a):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(o=Yh(s,Dh(r)),o.isLeafNode()&&(t=n.filter.updateFullNode(t,o,a)))}return o=r.serverCache.isFullyInitialized()||null!=Zh(s,Hl()),Nh(r,t,o,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,a,o){if(null!=Zh(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(nu(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return ld(e,t,i,l.getNode().getChild(i),s,a,c,o);if(nu(i)){let n=new Oh(null);return l.getNode().forEachChild(mu,(e,t)=>{n=n.set(new Gl(e),t)}),pd(e,t,i,n,s,a,c,o)}return t}{let r=new Oh(null);return n.foreach((e,t)=>{var n=tu(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),pd(e,t,i,r,s,a,c,o)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==Kc.LISTEN_COMPLETE)throw u("Unknown operation type: "+n.type);a=function(e,t,n,r,i){const s=t.serverCache,a=Rh(t,s.getNode(),s.isFullyInitialized()||nu(n),s.isFiltered());return cd(e,a,n,r,sd,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=xh(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(Ju(xh(t)))}}(t,a,l),{viewCache:a,changes:l}}function cd(r,i,s,a,o,c){const l=i.eventCache;if(null!=Zh(a,s))return i;{let t,n;if(nu(s)){var e;f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=Jh(a,(e=Dh(i))instanceof Fu?e:Fu.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=Yh(a,Dh(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=Ql(s);if(".priority"===u){f(1===Yl(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=Xh(a,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=Jl(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=Xh(a,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):td(a,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,o,c):l.getNode()}}return Nh(i,t,l.isFullyInitialized()||nu(s),r.filter.filtersNodes())}}function ld(e,t,n,r,i,s,a,o){const c=t.serverCache;let l;const u=a?e.filter:e.filter.getIndexedFilter();if(nu(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=Ql(n);if(!c.isCompleteForPath(n)&&1<Yl(n))return t;var p=Jl(n);const f=c.getNode().getImmediateChild(d);h=f.updateChild(p,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,p,sd,null)}p=Rh(t,l,c.isFullyInitialized()||nu(n),u.filtersNodes());return cd(e,p,n,i,new ad(i,p,s),o)}function ud(t,n,r,i,e,s,a){const o=n.eventCache;let c,l;const u=new ad(e,n,s);if(nu(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,a),c=Nh(n,l,!0,t.filter.filtersNodes());else{var h=Ql(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=Nh(n,l,o.isFullyInitialized(),o.isFiltered());else{var d=Jl(r);const p=o.getNode().getImmediateChild(h);let e;if(nu(d))e=i;else{const f=u.getCompleteChild(h);e=null!=f?".priority"===Xl(d)&&f.getChild(eu(d)).isEmpty()?f:f.updateChild(d,i):Fu.EMPTY_NODE}c=p.equals(e)?n:Nh(n,t.filter.updateChild(o.getNode(),h,e,d,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return c}function hd(e,t){return e.eventCache.isCompleteForChild(t)}function dd(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function pd(r,i,e,t,s,a,o,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=nu(e)?t:new Oh(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=dd(0,i.serverCache.getNode().getImmediateChild(e),t),l=ld(r,l,new Gl(e),n,s,a,o,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;u.hasChild(e)||n||(n=dd(0,i.serverCache.getNode().getImmediateChild(e),t),l=ld(r,l,new Gl(e),n,s,a,o,c))}),l}class fd{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new th(n.getIndex()),i=(e=n).loadsAllData()?new th(e.getIndex()):new(e.hasLimit()?rh:nh)(e);this.processor_={filter:i};const s=t.serverCache,a=t.eventCache;var o=r.updateFullNode(Fu.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(Fu.EMPTY_NODE,a.getNode(),null),o=new Eh(o,s.isFullyInitialized(),r.filtersNodes()),c=new Eh(c,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=Ah(c,o),this.eventGenerator_=new kh(this.query_)}get query(){return this.query_}}function gd(e){return 0===e.eventRegistrations_.length}function md(n,r,i){const s=[];if(i){f(null==r,"A cancel should cancel all event registrations.");const a=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,a);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const o=n.eventRegistrations_[t];if(o.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(o)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function vd(e,t,n,r){t.type===Kc.MERGE&&null!==t.source.queryId&&(f(Dh(e.viewCache_),"We should always have a full cache before handling merges"),f(xh(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=od(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,f(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),f(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,yd(e,s.changes,s.viewCache.eventCache.getNode(),null)}function yd(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return Sh(e.eventGenerator_,t,n,i)}let _d;class wd{constructor(){this.views=new Map}}function bd(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return f(null!=e,"SyncTree gave us an op for an invalid query."),vd(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(vd(s,n,r,i));return e}}function Id(e,n,r,i,s){var a=n._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Yh(r,s?i:null),t=!1;t=!!e||(e=i instanceof Fu?Jh(r,i):Fu.EMPTY_NODE,!1);a=Ah(new Eh(e,t,!1),new Eh(i,s,!1));return new fd(n,a)}}function Td(e,t,n,r,i,s){var a=Id(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,a),a.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(Nu,(e,t)=>{r.push(Xu(e,t))})}return n.isFullyInitialized()&&r.push(Ju(n.getNode())),yd(e,r,n.getNode(),t)}(a,n)}function Ed(e,t,n,r){var i=t._queryIdentifier;const s=[];let a=[];var o=Nd(e);if("default"===i)for(var[c,l]of e.views.entries())a=a.concat(md(l,n,r)),gd(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(a=a.concat(md(u,n,r)),gd(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return o&&!Nd(e)&&s.push((f(_d,"Reference.ts has not been loaded"),new _d(t._repo,t._path))),{removed:s,events:a}}function kd(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Sd(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=Dh(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!nu(t)&&!n.getImmediateChild(Ql(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function Cd(e,t){const n=t._queryParams;if(n.loadsAllData())return Rd(e);var r=t._queryIdentifier;return e.views.get(r)}function Ad(e,t){return null!=Cd(e,t)}function Nd(e){return null!=Rd(e)}function Rd(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let xd;let Dd=1;class Pd{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Oh(null),this.pendingWriteTree_={visibleWrites:Mh.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Od(e,t,n,r,i){var s,a,o,c;return s=e.pendingWriteTree_,a=t,o=n,c=r,r=i,f(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:a,snap:o,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=Lh(s.visibleWrites,a,o)),s.lastWriteId=c,i?Kd(e,new Ih(vh(),t,n)):[]}function Md(e,t,n,r){var i,s,a;i=e.pendingWriteTree_,s=t,a=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:a,writeId:r,visible:!0}),i.visibleWrites=Fh(i.visibleWrites,s,a),i.lastWriteId=r;var o=Oh.fromObject(n);return Kd(e,new Th(vh(),t,o))}function Ld(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(zh(e.pendingWriteTree_,t)){let t=new Oh(null);return null!=r.snap?t=t.set(Hl(),!0):vl(r.children,e=>{t=t.set(new Gl(e),!0)}),Kd(e,new wh(r.path,t,n))}return[]}function Fd(e,t,n){return Kd(e,new Ih(yh(),t,n))}function Ud(n,e,t,r,i=!1){var s=e._path,a=n.syncPointTree_.get(s);let o=[];if(a&&("default"===e._queryIdentifier||Ad(a,e))){var c=Ed(a,e,t,r);0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(s));const d=c.removed;if(o=c.events,!i){a=-1!==d.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(s,(e,t)=>Nd(t));if(a&&!c){const p=n.syncPointTree_.subtree(s);if(!p.isEmpty()){var l=p.fold((e,t,r)=>{if(t&&Nd(t))return[Rd(t)];{let n=[];return t&&(n=kd(t)),vl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<l.length;++e){var u=l[e],h=u.query,u=Wd(n,u);n.listenProvider_.startListening(Jd(h),zd(n,h),u.hashFn,u.onComplete)}}}!c&&0<d.length&&!r&&(a?n.listenProvider_.stopListening(Jd(e),null):d.forEach(e=>{var t=n.queryToTagMap.get(Gd(e));n.listenProvider_.stopListening(Jd(e),t)}))}!function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=Gd(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,d)}return o}function qd(e,t,n,r){var i=Hd(e,r);if(null==i)return[];var s=Qd(i),a=s.path,i=s.queryId,s=ru(a,t);return Yd(e,a,new Ih(_h(i),s,n))}function Vd(e,t,n,r=!1){const i=t._path;let s=null,a=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=ru(e,i);s=s||Sd(t,n),a=a||Nd(t)});let o=e.syncPointTree_.get(i);o?(a=a||Nd(o),s=s||Sd(o,Hl())):(o=new wd,e.syncPointTree_=e.syncPointTree_.set(i,o));let c;if(null!=s)c=!0;else{c=!1,s=Fu.EMPTY_NODE;const p=e.syncPointTree_.subtree(i);p.foreachChild((e,t)=>{var n=Sd(t,Hl());n&&(s=s.updateImmediateChild(e,n))})}var l,u=Ad(o,t);u||t._queryParams.loadsAllData()||(h=Gd(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),l=Dd++,e.queryToTagMap.set(h,l),e.tagToQueryMap.set(l,h));var h=Wh(e.pendingWriteTree_,i);let d=Td(o,t,n,h,s,c);return u||a||r||(u=Cd(o,t),d=d.concat(function(t,e,n){const r=e._path,i=zd(t,e),s=Wd(t,n),a=t.listenProvider_.startListening(Jd(e),i,s.hashFn,s.onComplete),o=t.syncPointTree_.subtree(r);if(i)f(!Nd(o.value),"If we're adding a query, it shouldn't be shadowed");else{var c=o.fold((e,t,r)=>{if(!nu(e)&&t&&Nd(t))return[Rd(t).query];{let n=[];return t&&(n=n.concat(kd(t).map(e=>e.query))),vl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(Jd(l),zd(t,l))}}return a}(e,t,u))),d}function Bd(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Sd(t,ru(e,r));if(n)return n});return Qh(n,r,i,t,!0)}function jd(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=ru(e,r);i=i||Sd(t,n)});let n=e.syncPointTree_.get(r);n?i=i||Sd(n,Hl()):(n=new wd,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const a=s?new Eh(i,!0,!1):null;var o=Wh(e.pendingWriteTree_,t._path);return xh(Id(n,t,o,s?a.getNode():Fu.EMPTY_NODE,s).viewCache_)}function Kd(e,t){return function t(n,r,i,s){{if(nu(n.path))return $d(n,r,i,s);{const a=r.get(Hl());null==i&&null!=a&&(i=Sd(a,Hl()));let e=[];const o=Ql(n.path),c=n.operationForChild(o),l=r.children.get(o);if(l&&c){const u=i?i.getImmediateChild(o):null,h=nd(s,o);e=e.concat(t(c,l,u,h))}return a&&(e=e.concat(bd(a,n,s,i))),e}}}(t,e.syncPointTree_,null,Wh(e.pendingWriteTree_,Hl()))}function $d(s,e,a,o){var t=e.get(Hl());null==a&&null!=t&&(a=Sd(t,Hl()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=a?a.getImmediateChild(e):null,r=nd(o,e),i=s.operationForChild(e);i&&(c=c.concat($d(i,t,n,r)))}),t&&(c=c.concat(bd(t,s,o,a))),c}function Wd(i,t){const s=t.query,a=zd(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||Fu.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return a?function(e,t,n){if(s=Hd(e,n)){var r=Qd(s),i=r.path,s=r.queryId,r=ru(i,t);return Yd(e,i,new bh(_h(s),r))}return[]}(i,s._path,a):(t=i,n=s._path,Kd(t,new bh(yh(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return Ud(i,s,null,r)}}}function zd(e,t){var n=Gd(t);return e.queryToTagMap.get(n)}function Gd(e){return e._path.toString()+"$"+e._queryIdentifier}function Hd(e,t){return e.tagToQueryMap.get(t)}function Qd(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new Gl(e.substr(0,t))}}function Yd(e,t,n){var r=e.syncPointTree_.get(t);return f(r,"Missing sync point for query tag that we're tracking"),bd(r,n,Wh(e.pendingWriteTree_,t),null)}function Jd(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(xd,"Reference.ts has not been loaded"),new xd(e._repo,e._path)):e}class Xd{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new Xd(t)}node(){return this.node_}}class Zd{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=tu(this.path_,e);return new Zd(this.syncTree_,t)}node(){return Bd(this.syncTree_,this.path_)}}function ep(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function tp(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?np(e[".sv"],t,n):"object"==typeof e[".sv"]?rp(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const np=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},rp=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&f(!1,"Unexpected increment value: "+r);const i=t.node();if(f(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var a=s.getValue();return"number"!=typeof a?r:a+r},ip=function(e,t,n,r){return ap(t,new Zd(n,e),r)},sp=function(e,t,n){return ap(e,new Xd(t),n)};function ap(e,r,i){var t=e.getPriority().val(),n=tp(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const a=e;t=tp(a.getValue(),r,i);return t!==a.getValue()||n!==a.getPriority().val()?new Su(t,Bu(n)):e}{const o=e;return s=o,n!==o.getPriority().val()&&(s=s.updatePriority(new Su(n))),o.forEachChild(Nu,(e,t)=>{var n=ap(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class op{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function cp(e,t){let n=t instanceof Gl?t:new Gl(t),r=e,i=Ql(n);for(;null!==i;){var s=F(r.node.children,i)||{children:{},childCount:0};r=new op(i,r,s),n=Jl(n),i=Ql(n)}return r}function lp(e){return e.node.value}function up(e,t){e.node.value=t,fp(e)}function hp(e){return 0<e.node.childCount}function dp(n,r){vl(n.node.children,(e,t)=>{r(new op(e,n,t))})}function pp(e){return new Gl(null===e.parent?e.name:pp(e.parent)+"/"+e.name)}function fp(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===lp(e)&&!hp(e)}(e=e),i=L(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,fp(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,fp(t)))}function gp(e,t,n,r){r&&void 0===t||Ap(Y(e,"value"),t,n)}function mp(e,t,r,n){if(!n||void 0!==t){const i=Y(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];vl(t,(e,t)=>{const n=new Gl(e);if(Ap(i,t,tu(r,n)),".priority"===Xl(n)&&!Cp(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=Zl(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!Ep(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(iu);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&au(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function vp(e,t,n){if(!n||void 0!==t){if(pl(t))throw new Error(Y(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Cp(t))throw new Error(Y(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function yp(e,t,n,r){if(!(r&&void 0===n||Ep(n)))throw new Error(Y(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function _p(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Np(e,t,n,r)}function wp(e,t){if(".info"===Ql(t))throw new Error(e+" failed = Can't modify data under /.info/")}const bp=/[\[\].#$\/\u0000-\u001F\u007F]/,Ip=/[\[\].#$\u0000-\u001F\u007F]/,Tp=10485760,Ep=function(e){return"string"==typeof e&&0!==e.length&&!bp.test(e)},kp=function(e){return"string"==typeof e&&0!==e.length&&!Ip.test(e)},Sp=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),kp(e)},Cp=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!pl(e)||e&&"object"==typeof e&&L(e,".sv")},Ap=function(a,e,t){const o=t instanceof Gl?new ou(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+lu(o));if("function"==typeof e)throw new Error(a+"contains a function "+lu(o)+" with contents = "+e.toString());if(pl(e))throw new Error(a+"contains "+e.toString()+" "+lu(o));if("string"==typeof e&&e.length>Tp/3&&ee(e)>Tp)throw new Error(a+"contains a string greater than "+Tp+" utf8 bytes "+lu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(vl(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!Ep(e)))throw new Error(a+" contains an invalid key ("+e+") "+lu(o)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=o,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=ee(e),cu(n),Ap(a,t,o),t=o,r=t.parts_.pop(),t.byteLength_-=ee(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+lu(o)+" in addition to actual children.")}},Np=function(e,t,n,r){if(!(r&&void 0===n||kp(n)))throw new Error(Y(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Rp=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Ep(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Sp(n))throw new Error(Y(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class xp{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Dp(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||su(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function Pp(e,t,n){Dp(e,n),Mp(e,e=>su(e,t))}function Op(e,t,n){Dp(e,n),Mp(e,e=>au(e,t)||au(t,e))}function Mp(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),el&&ll("event: "+r.toString()),El(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const Lp="repo_interrupt",Fp=25;class Up{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new xp,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=dh(),this.transactionQueueTree_=new op,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function qp(a,e,t){if(a.stats_=Ll(a.repoInfo_),a.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())a.server_=new uh(a.repoInfo_,(e,t,n,r)=>{jp(a,e,t,n,r)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Kp(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{O(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new hu(a.repoInfo_,e,(e,t,n,r)=>{jp(a,e,t,n,r)},e=>{Kp(a,e)},e=>{var n;n=a,vl(e,(e,t)=>{$p(n,e,t)})},a.authTokenProvider_,a.appCheckProvider_,t),a.server_=a.persistentConnection_}var n;a.authTokenProvider_.addTokenChangeListener(e=>{a.server_.refreshAuthToken(e)}),a.appCheckProvider_.addTokenChangeListener(e=>{a.server_.refreshAppCheckToken(e.token)}),a.statsReporter_=(e=a.repoInfo_,t=()=>new mh(a.stats_,a.server_),n=e.toString(),Ml[n]||(Ml[n]=t()),Ml[n]),a.infoData_=new hh,a.infoSyncTree_=new Pd({startListening:(e,t,n,r)=>{let i=[];const s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=Fd(a.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),$p(a,"connected",!1),a.serverSyncTree_=new Pd({startListening:(r,e,t,i)=>(a.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);Op(a.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Vp(e){const t=e.infoData_.getNode(new Gl(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function Bp(e){return ep({timestamp:Vp(e)})}function jp(e,t,n,r,i){e.dataUpdateCount++;var s,a,o=new Gl(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=q(n,e=>Bu(e)),function(e,t,n,r){if(o=Hd(e,r)){var i=Qd(o),s=i.path,a=i.queryId,o=ru(s,t),i=Oh.fromObject(n);return Yd(e,s,new Th(_h(a),o,i))}return[]}(e.serverSyncTree_,o,s,i)):(s=Bu(n),qd(e.serverSyncTree_,o,s,i)):r?(a=q(n,e=>Bu(e)),t=e.serverSyncTree_,i=o,r=a,a=Oh.fromObject(r),Kd(t,new Th(yh(),i,a))):(a=Bu(n),Fd(e.serverSyncTree_,o,a));let l=o;0<c.length&&(l=tf(e,o)),Op(e.eventQueue_,l,c)}function Kp(e,t){$p(e,"connected",t),!1===t&&function(r){Jp(r,"onDisconnectEvents");const i=Bp(r),s=dh();fh(r.onDisconnect_,Hl(),(e,t)=>{var n=ip(e,t,r.serverSyncTree_,i);ph(s,e,n)});let a=[];fh(s,Hl(),(e,t)=>{a=a.concat(Fd(r.serverSyncTree_,e,t));var n=af(r,e);tf(r,n)}),r.onDisconnect_=dh(),Op(r.eventQueue_,Hl(),a)}(e)}function $p(e,t,n){var r=new Gl("/.info/"+t),i=Bu(n);e.infoData_.updateSnapshot(r,i);i=Fd(e.infoSyncTree_,r,i);Op(e.eventQueue_,r,i)}function Wp(e){return e.nextWriteId_++}function zp(r,i,e,t,s){Jp(r,"set",{path:i.toString(),value:e,priority:t});var n=Bp(r);const a=Bu(e,t);var o=Bd(r.serverSyncTree_,i),n=sp(a,o,n);const c=Wp(r);n=Od(r.serverSyncTree_,i,n,c,!0);Dp(r.eventQueue_,n),r.server_.put(i.toString(),a.val(!0),(e,t)=>{var n="ok"===e;n||hl("set at "+i+" failed: "+e);n=Ld(r.serverSyncTree_,c,!n);Op(r.eventQueue_,i,n),Xp(0,s,e,t)});n=af(r,i);tf(r,n),Op(r.eventQueue_,n,[])}function Gp(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(nu(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(Nu,(e,t)=>{ph(n,new Gl(e),t)}),e(n,t)}}if(0<n.children.size){var r=Ql(t);return t=Jl(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),Xp(0,i,e,t)})}function Hp(n,r,e,i){const s=Bu(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&ph(n.onDisconnect_,r,s),Xp(0,i,e,t)})}function Qp(e,t,n){let r;r=".info"===Ql(t._path)?Ud(e.infoSyncTree_,t,n):Ud(e.serverSyncTree_,t,n),Pp(e.eventQueue_,t._path,r)}function Yp(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Lp)}function Jp(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),ll(n,...t)}function Xp(e,r,i,s){r&&El(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function Zp(e,t,n){return Bd(e.serverSyncTree_,t,n)||Fu.EMPTY_NODE}function ef(t,e=t.transactionQueueTree_){if(e||sf(t,e),lp(e)){const n=rf(t,e);f(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,a){const e=a.map(e=>e.currentWriteId),t=Zp(i,s,e);let n=t;var r=t.hash();for(let u=0;u<a.length;u++){const h=a[u];f(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var o=ru(s,h.path);n=n.updateChild(o,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{Jp(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<a.length;e++)a[e].status=2,n=n.concat(Ld(i.serverSyncTree_,a[e].currentWriteId)),a[e].onComplete&&r.push(()=>a[e].onComplete(null,!0,a[e].currentOutputSnapshotResolved)),a[e].unwatcher();sf(i,cp(i.transactionQueueTree_,s)),ef(i,i.transactionQueueTree_),Op(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)El(r[t])}else{if("datastale"===t)for(let e=0;e<a.length;e++)3===a[e].status?a[e].status=4:a[e].status=0;else{hl("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<a.length;e++)a[e].status=4,a[e].abortReason=t}tf(i,s)}},r)}(t,pp(e),n)}else hp(e)&&dp(e,e=>{ef(t,e)})}function tf(e,t){var n=nf(e,t),r=pp(n);return function(i,s,a){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var o=ru(a,h.path);let e=!1,t;if(f(null!==o,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(Ld(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=Fp)e=!0,t="maxretry",n=n.concat(Ld(i.serverSyncTree_,h.currentWriteId,!0));else{const d=Zp(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){Ap("transaction failed: Data returned ",c,h.path);let e=Bu(c);"object"==typeof c&&null!=c&&L(c,".priority")||(e=e.updatePriority(d.getPriority()));o=h.currentWriteId,c=Bp(i),c=sp(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Wp(i),u.splice(u.indexOf(o),1),n=n.concat(Od(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(Ld(i.serverSyncTree_,o,!0))}else e=!0,t="nodata",n=n.concat(Ld(i.serverSyncTree_,h.currentWriteId,!0))}Op(i.eventQueue_,a,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}sf(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)El(l[e]);ef(i,i.transactionQueueTree_)}}(e,rf(e,n),r),r}function nf(e,t){let n,r=e.transactionQueueTree_;for(n=Ql(t);null!==n&&void 0===lp(r);)r=cp(r,n),t=Jl(t),n=Ql(t);return r}function rf(e,t){const n=[];return function t(n,e,r){const i=lp(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);dp(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function sf(t,n){const r=lp(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,up(n,0<r.length?r:void 0)}dp(n,e=>{sf(t,e)})}function af(t,e){var n=pp(nf(t,e)),r=cp(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{of(t,e)}),of(t,r),function t(e,n,r,i){r&&!i&&n(e),dp(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{of(t,e)}),n}function of(i,s){const a=lp(s);if(a){const o=[];let e=[],t=-1;for(let n=0;n<a.length;n++)3===a[n].status||(1===a[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),t=n,a[n].status=3,a[n].abortReason="set"):(f(0===a[n].status,"Unexpected transaction status in abort"),a[n].unwatcher(),e=e.concat(Ld(i.serverSyncTree_,a[n].currentWriteId,!0)),a[n].onComplete&&o.push(a[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?up(s,void 0):a.length=t+1,Op(i.eventQueue_,pp(s),e);for(let r=0;r<o.length;r++)El(o[r])}}const cf=function(e,t){var n=lf(e),r=n.namespace;"firebase.com"===n.domain&&ul(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||ul("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||dl();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new xl(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new Gl(n.pathString)}},lf=function(r){let i="",s="",a="",o="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(o=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,p=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):hl(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const f=i.slice(0,e);"localhost"===f.toLowerCase()?s="localhost":f.split(".").length<=2?s=f:(d=i.indexOf("."),a=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=a),"ns"in p&&(c=p.ns)}return{host:i,port:h,domain:s,subdomain:a,secure:l,scheme:u,pathString:o,namespace:c}};class uf{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+O(this.snapshot.exportVal())}}class hf{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class df{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class pf{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new A;return Gp(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){wp("OnDisconnect.remove",this._path);const e=new A;return Hp(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){wp("OnDisconnect.set",this._path),gp("OnDisconnect.set",e,this._path,!1);const t=new A;return Hp(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){wp("OnDisconnect.setWithPriority",this._path),gp("OnDisconnect.setWithPriority",e,this._path,!1),vp("OnDisconnect.setWithPriority",t,!1);const n=new A;return function(n,r,e,t,i){const s=Bu(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&ph(n.onDisconnect_,r,s),Xp(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){wp("OnDisconnect.update",this._path),mp("OnDisconnect.update",e,this._path,!1);const t=new A;return function(r,i,n,s){if(U(n))return ll("onDisconnect().update() called with empty data. Don't do anything."),Xp(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&vl(n,(e,t)=>{var n=Bu(t);ph(r.onDisconnect_,tu(i,e),n)}),Xp(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class ff{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return nu(this._path)?null:Xl(this._path)}get ref(){return new yf(this._repo,this._path)}get _queryIdentifier(){var e=lh(this._queryParams),e=al(e);return"{}"===e?"default":e}get _queryObject(){return lh(this._queryParams)}isEqual(e){if(!((e=ae(e))instanceof ff))return!1;var t=this._repo===e._repo,n=su(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function gf(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function mf(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===mu){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==fl)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==gl)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===Nu){if(null!=t&&!Cp(t)||null!=n&&!Cp(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(f(e.getIndex()instanceof ju||e.getIndex()===Wu,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function vf(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 yf extends ff{constructor(e,t){super(e,t,new ih,!1)}get parent(){var e=eu(this._path);return null===e?null:new yf(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class _f{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new Gl(e),n=If(this.ref,e);return new _f(this._node.getChild(t),n,Nu)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new _f(t,If(this.ref,e),Nu)))}hasChild(e){var t=new Gl(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 wf(e,t){return(e=ae(e))._checkNotDeleted("ref"),void 0!==t?If(e._root,t):e._root}function bf(e,t){(e=ae(e))._checkNotDeleted("refFromURL");const n=cf(t,e._repo.repoInfo_.nodeAdmin);Rp("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||ul("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),wf(e,n.path.toString())}function If(e,t){return(null===Ql((e=ae(e))._path)?_p:Np)("child","path",t,!1),new yf(e._repo,tu(e._path,t))}function Tf(e,t){e=ae(e),wp("set",e._path),gp("set",t,e._path,!1);const n=new A;return zp(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Ef(e,t){mp("update",t,e._path,!1);const n=new A;return function(i,s,e,a){Jp(i,"update",{path:s.toString(),value:e});let n=!0;const r=Bp(i),o={};if(vl(e,(e,t)=>{n=!1,o[e]=ip(tu(s,e),Bu(t),i.serverSyncTree_,r)}),n)ll("update() called with empty data. Don't do anything."),Xp(0,a,"ok",void 0);else{const c=Wp(i);var t=Md(i.serverSyncTree_,s,o,c);Dp(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||hl("update at "+s+" failed: "+e);var r=Ld(i.serverSyncTree_,c,!n),n=0<r.length?tf(i,s):s;Op(i.eventQueue_,n,r),Xp(0,a,e,t)}),vl(e,e=>{var t=af(i,tu(s,e));tf(i,t)}),Op(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function kf(t){t=ae(t);var i,s,a,e=new df(()=>{}),e=new Sf(e);return i=t._repo,s=t,a=e,(null!=(e=jd(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=Bu(e).withIndex(s._queryParams.getIndex());Vd(i.serverSyncTree_,s,a,!0);let r;return r=s._queryParams.loadsAllData()?Fd(i.serverSyncTree_,s._path,n):(t=zd(i.serverSyncTree_,s),qd(i.serverSyncTree_,s._path,n,t)),Op(i.eventQueue_,s._path,r),Ud(i.serverSyncTree_,s,a,null,!0),n},e=>(Jp(i,"get for query "+O(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new _f(e,new yf(t._repo,t._path),t._queryParams.getIndex()))}class Sf{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new uf("value",this,new _f(e.snapshotNode,new yf(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new hf(this,e,t):null}matches(e){return e instanceof Sf&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Cf{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new hf(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=If(new yf(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new uf(e.type,this,new _f(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Cf&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function Af(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var a=(e,t)=>{Qp(n._repo,n,o),c(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new df(t,s||void 0);const o="value"===e?new Sf(a):new Cf(e,a);return function(e,t,n){let r;r=".info"===Ql(t._path)?Vd(e.infoSyncTree_,t,n):Vd(e.serverSyncTree_,t,n),Pp(e.eventQueue_,t._path,r)}(n._repo,n,o),()=>Qp(n._repo,n,o)}function Nf(e,t,n,r){return Af(e,"value",t,n,r)}function Rf(e,t,n,r){return Af(e,"child_added",t,n,r)}function xf(e,t,n,r){return Af(e,"child_changed",t,n,r)}function Df(e,t,n,r){return Af(e,"child_moved",t,n,r)}function Pf(e,t,n,r){return Af(e,"child_removed",t,n,r)}function Of(e,t,n){let r=null;var i=n?new df(n):null;"value"===t?r=new Sf(i):t&&(r=new Cf(t,i)),Qp(e._repo,e,r)}class Mf{}class Lf extends Mf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){gp("endAt",this._value,e._path,!0);var t=ah(e._queryParams,this._value,this._key);if(vf(t),mf(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ff(e._repo,e._path,t,e._orderByCalled)}}class Ff extends Mf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){gp("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r,i;return i=e.index_===mu?ah(e,t="string"==typeof t?$u(t):t,n):(r=null==n?fl:$u(n),ah(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(vf(t),mf(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new ff(e._repo,e._path,t,e._orderByCalled)}}class Uf extends Mf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){gp("startAt",this._value,e._path,!0);var t=sh(e._queryParams,this._value,this._key);if(vf(t),mf(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new ff(e._repo,e._path,t,e._orderByCalled)}}class qf extends Mf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){gp("startAfter",this._value,e._path,!1);var t=function(t,n,r){let i;if(t.index_===mu)"string"==typeof n&&(n=Ku(n)),i=sh(t,n,r);else{let e;e=null==r?gl:Ku(r),i=sh(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(vf(t),mf(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new ff(e._repo,e._path,t,e._orderByCalled)}}class Vf extends Mf{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new ff(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class Bf extends Mf{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new ff(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class jf extends Mf{constructor(e){super(),this._path=e}_apply(e){gf(e,"orderByChild");var t=new Gl(this._path);if(nu(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new ju(t),t=oh(e._queryParams,t);return mf(t),new ff(e._repo,e._path,t,!0)}}class Kf extends Mf{_apply(e){gf(e,"orderByKey");var t=oh(e._queryParams,mu);return mf(t),new ff(e._repo,e._path,t,!0)}}class $f extends Mf{_apply(e){gf(e,"orderByPriority");var t=oh(e._queryParams,Nu);return mf(t),new ff(e._repo,e._path,t,!0)}}class Wf extends Mf{_apply(e){gf(e,"orderByValue");var t=oh(e._queryParams,Wu);return mf(t),new ff(e._repo,e._path,t,!0)}}class zf extends Mf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(gp("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 Lf(this._value,this._key)._apply(new Uf(this._value,this._key)._apply(e))}}function Gf(e,...t){let n=ae(e);for(const r of t)n=r._apply(n);return n}$c=yf,f(!_d,"__referenceConstructor has already been defined"),_d=$c,Wc=yf,f(!xd,"__referenceConstructor has already been defined"),xd=Wc;const Hf="FIREBASE_DATABASE_EMULATOR_HOST",Qf={};let Yf=!1;function Jf(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||ul("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),ll("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let a=cf(s,i),o=a.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[Hf]),l?(c=!0,s=`http://${l}?ns=${o.namespace}`,a=cf(s,i),o=a.repoInfo):c=!a.repoInfo.secure;var u=i&&c?new Cl(Cl.OWNER):new Sl(e.name,e.options,t);Rp("Invalid Firebase Database URL",a),nu(a.path)||ul("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=Qf[t.name];i||(i={},Qf[t.name]=i);var s=i[e.toURLString()];s&&ul("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new Up(e,Yf,n,r),i[e.toURLString()]=s}(o,e,u,new kl(e.name,n));return new Xf(u,e)}class Xf{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(qp(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new yf(this._repo,Hl())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=Qf[t];n&&n[e.key]===e||ul(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Yp(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&ul("Cannot call "+e+" on a deleted database.")}}function Zf(){jl.IS_TRANSPORT_INITIALIZED&&hl("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function eg(){Zf(),Ul.forceDisallow()}function tg(){Zf(),Bl.forceDisallow(),Ul.forceAllow()}function ng(e,t,n,r={}){(e=ae(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&ul("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&ul('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 Cl(Cl.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:N(r.mockUserToken,e.app.options.projectId),a=new Cl(i)),r=s,e=t,t=n,n=a,r.repoInfo_=new xl(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams),n&&(r.authTokenProvider_=n)}function rg(e){(e=ae(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Lp)}function ig(e,t){cl(e,t)}const sg={".sv":"timestamp"};class ag{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function og(i,e,t){if(i=ae(i),wp("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new A;var r=Nf(i,()=>{});return function(t,n,e,r,i,s){Jp(t,"transaction on "+n);const a={path:n,update:e,onComplete:r,status:null,order:Xc(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},o=Zp(t,n,void 0);a.currentInputSnapshot=o;var c=a.update(o.val());if(void 0===c)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Ap("transaction failed: Data returned ",c,a.path),a.status=0;var l=cp(t.transactionQueueTree_,n);const u=lp(l)||[];u.push(a),up(l,u);let e;if("object"==typeof c&&null!==c&&L(c,".priority"))e=F(c,".priority"),f(Cp(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=Bd(t.serverSyncTree_,n)||Fu.EMPTY_NODE;e=h.getPriority().val()}l=Bp(t),c=Bu(c,e),l=sp(c,o,l);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=l,a.currentWriteId=Wp(t);l=Od(t.serverSyncTree_,n,l,a.currentWriteId,a.applyLocally);Op(t.eventQueue_,n,l),ef(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new _f(n,new yf(i._repo,i._path),Nu),s.resolve(new ag(t,r)))},r,n),s.promise}hu.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},hu.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Uc(Ye),ze(new oe("database",(e,{instanceIdentifier:t})=>{return Jf(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),et(Mc,Lc,zc),et(Mc,Lc,"esm2017");function cg(e){var t="FIREBASE WARNING: "+e;lg.warn(t)}const lg=new me("@firebase/database-compat");class ug{constructor(e){this._delegate=e}cancel(t){Q("OnDisconnect.cancel",0,1,arguments.length),J("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Q("OnDisconnect.remove",0,1,arguments.length),J("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Q("OnDisconnect.set",1,2,arguments.length),J("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Q("OnDisconnect.setWithPriority",2,3,arguments.length),J("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Q("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,cg("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.")}J("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class hg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Q("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class dg{constructor(e,t){this._database=e,this._delegate=t}val(){return Q("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Q("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Q("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Q("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Q("DataSnapshot.child",0,1,arguments.length),e=String(e),Np("DataSnapshot.child","path",e,!1),new dg(this._database,this._delegate.child(e))}hasChild(e){return Q("DataSnapshot.hasChild",1,1,arguments.length),Np("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Q("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Q("DataSnapshot.forEach",1,1,arguments.length),J("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new dg(this._database,e)))}hasChildren(){return Q("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Q("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Q("DataSnapshot.ref",0,0,arguments.length),new fg(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class pg{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Q("Query.on",2,4,arguments.length),J("Query.on","callback",n,!1);const s=pg.getCancelAndContextArgs_("Query.on",t,r);var a=(e,t)=>{n.call(s.context,new dg(this.database,e),t)};a.userCallback=n,a.context=s.context;var o=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return Nf(this._delegate,a,o),n;case"child_added":return Rf(this._delegate,a,o),n;case"child_removed":return Pf(this._delegate,a,o),n;case"child_changed":return xf(this._delegate,a,o),n;case"child_moved":return Df(this._delegate,a,o),n;default:throw new Error(Y("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Q("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(Y(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),J("Query.off","callback",t,!0),X("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,Of(this._delegate,e,r)):Of(this._delegate,e)}get(){return kf(this._delegate).then(e=>new dg(this.database,e))}once(e,r,t,n){Q("Query.once",1,4,arguments.length),J("Query.once","callback",r,!0);const i=pg.getCancelAndContextArgs_("Query.once",t,n),s=new A;var a=(e,t)=>{var n=new dg(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};a.userCallback=r,a.context=i.context;var o=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":Nf(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":Rf(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Pf(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":xf(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":Df(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(Y("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 Q("Query.limitToFirst",1,1,arguments.length),new pg(this.database,Gf(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Vf(e)}(e)))}limitToLast(e){return Q("Query.limitToLast",1,1,arguments.length),new pg(this.database,Gf(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Bf(e)}(e)))}orderByChild(e){return Q("Query.orderByChild",1,1,arguments.length),new pg(this.database,Gf(this._delegate,function(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 Np("orderByChild","path",e,!1),new jf(e)}(e)))}orderByKey(){return Q("Query.orderByKey",0,0,arguments.length),new pg(this.database,Gf(this._delegate,new Kf))}orderByPriority(){return Q("Query.orderByPriority",0,0,arguments.length),new pg(this.database,Gf(this._delegate,new $f))}orderByValue(){return Q("Query.orderByValue",0,0,arguments.length),new pg(this.database,Gf(this._delegate,new Wf))}startAt(e=null,t){return Q("Query.startAt",0,2,arguments.length),new pg(this.database,Gf(this._delegate,([e=null,t]=[e,t],yp("startAt","key",t,!0),new Uf(e,t))))}startAfter(e=null,t){return Q("Query.startAfter",0,2,arguments.length),new pg(this.database,Gf(this._delegate,(e=e,t=t,yp("startAfter","key",t,!0),new qf(e,t))))}endAt(e=null,t){return Q("Query.endAt",0,2,arguments.length),new pg(this.database,Gf(this._delegate,(e=e,t=t,yp("endAt","key",t,!0),new Lf(e,t))))}endBefore(e=null,t){return Q("Query.endBefore",0,2,arguments.length),new pg(this.database,Gf(this._delegate,(e=e,t=t,yp("endBefore","key",t,!0),new Ff(e,t))))}equalTo(e,t){return Q("Query.equalTo",1,2,arguments.length),new pg(this.database,Gf(this._delegate,(e=e,t=t,yp("equalTo","key",t,!0),new zf(e,t))))}toString(){return Q("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Q("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Q("Query.isEqual",1,1,arguments.length),e instanceof pg)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,J(e,"cancel",r.cancel,!0),r.context=n,X(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(Y(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new fg(this.database,new yf(this._delegate._repo,this._delegate._path))}}class fg extends pg{constructor(e,t){super(e,new ff(t._repo,t._path,new ih,!1)),this.database=e,this._delegate=t}getKey(){return Q("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Q("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new fg(this.database,If(this._delegate,e))}getParent(){Q("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new fg(this.database,e):null}getRoot(){return Q("Reference.root",0,0,arguments.length),new fg(this.database,this._delegate.root)}set(e,t){Q("Reference.set",1,2,arguments.length),J("Reference.set","onComplete",t,!0);const n=Tf(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Q("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,cg("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.")}wp("Reference.update",this._delegate._path),J("Reference.update","onComplete",n,!0);const e=Ef(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Q("Reference.setWithPriority",2,3,arguments.length),J("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(wp("setWithPriority",e._path),gp("setWithPriority",t,e._path,!1),vp("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new A;return zp(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Q("Reference.remove",0,1,arguments.length),J("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,wp("remove",n._path),Tf(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Q("Reference.transaction",1,3,arguments.length),J("Reference.transaction","transactionUpdate",e,!1),J("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(Y(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=og(this._delegate,e,{applyLocally:n}).then(e=>new hg(e.committed,new dg(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Q("Reference.setPriority",1,2,arguments.length),J("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=ae(e),wp("setPriority",e._path),vp("setPriority",t,!1);const n=new A;return zp(e._repo,tu(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Q("Reference.push",0,2,arguments.length),J("Reference.push","onComplete",t,!0);const n=function(e,t){e=ae(e),wp("push",e._path),gp("push",t,e._path,!0);var n=Vp(e._repo),n=Yu(n);const r=If(e,n),i=If(e,n);let s;return s=null!=t?Tf(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new fg(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new fg(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return wp("Reference.onDisconnect",this._delegate._path),new ug(new pf(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class gg{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:eg,forceLongPolling:tg}}useEmulator(e,t,n={}){ng(this._delegate,e,t,n)}ref(e){if(Q("database.ref",0,1,arguments.length),e instanceof fg){var t=bf(this._delegate,e.toString());return new fg(this,t)}t=wf(this._delegate,e);return new fg(this,t)}refFromURL(e){Q("database.refFromURL",1,1,arguments.length);var t=bf(this._delegate,e);return new fg(this,t)}goOffline(){var e;Q("database.goOffline",0,0,arguments.length),(e=ae(e=this._delegate))._checkNotDeleted("goOffline"),Yp(e._repo)}goOnline(){return Q("database.goOnline",0,0,arguments.length),rg(this._delegate)}}gg.ServerValue={TIMESTAMP:sg,increment:e=>({".sv":{increment:e}})};var mg,vg=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){Uc(n);const a=new le("auth-internal",new ue("database-standalone"));return a.setComponent(new oe("auth-internal",()=>r,"PRIVATE")),{instance:new gg(Jf(e,a,void 0,t,s),e),namespace:i}}});const yg=gg.ServerValue;(mg=wt).INTERNAL.registerComponent(new oe("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new gg(r,n)},"PUBLIC").setServiceProps({Reference:fg,Query:pg,Database:gg,DataSnapshot:dg,enableLogging:ig,INTERNAL:vg,ServerValue:yg}).setMultipleInstances(!0)),mg.registerVersion("@firebase/database-compat","0.2.10");var yt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},_g={},wg=yt||self;function bg(){}function Ig(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 Tg(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Eg="closure_uid_"+(1e9*Math.random()>>>0),kg=0;function Sg(e,t,n){return e.call.apply(e.bind,arguments)}function Cg(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function Ag(e,t,n){return(Ag=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Sg:Cg).apply(null,arguments)}function Ng(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function Rg(e,s){function t(){}t.prototype=s.prototype,e.X=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Wb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function xg(){this.s=this.s,this.o=this.o}xg.prototype.s=!1,xg.prototype.na=function(){var e;!this.s&&(this.s=!0,this.M(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,Eg)&&e[Eg]||(e[Eg]=++kg))},xg.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Dg=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function Pg(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function Og(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(Ig(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function Mg(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}Mg.prototype.h=function(){this.defaultPrevented=!0};var Lg=function(){if(!wg.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{wg.addEventListener("test",bg,t),wg.removeEventListener("test",bg,t)}catch(e){}return e}();function Fg(e){return/^[\s\xa0]*$/.test(e)}var Ug=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function qg(e,t){return e<t?-1:t<e?1:0}function Vg(){var e=wg.navigator;return(e=e&&e.userAgent)?e:""}function Bg(e){return-1!=Vg().indexOf(e)}function jg(e){return jg[" "](e),e}jg[" "]=bg;var Kg,$g=Bg("Opera"),Wg=Bg("Trident")||Bg("MSIE"),zg=Bg("Edge"),Gg=zg||Wg,Hg=Bg("Gecko")&&!(-1!=Vg().toLowerCase().indexOf("webkit")&&!Bg("Edge"))&&!(Bg("Trident")||Bg("MSIE"))&&!Bg("Edge"),Qg=-1!=Vg().toLowerCase().indexOf("webkit")&&!Bg("Edge");function Yg(){var e=wg.document;return e?e.documentMode:void 0}e:{var Jg="",Xg=(Xg=Vg(),Hg?/rv:([^\);]+)(\)|;)/.exec(Xg):zg?/Edge\/([\d\.]+)/.exec(Xg):Wg?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Xg):Qg?/WebKit\/(\S+)/.exec(Xg):$g?/(?:Version)[ \/]?(\S+)/.exec(Xg):void 0);if(Xg&&(Jg=Xg?Xg[1]:""),Wg){Xg=Yg();if(null!=Xg&&Xg>parseFloat(Jg)){Kg=String(Xg);break e}}Kg=Jg}var Zg={};function em(){return e=function(){let e=0;var t=Ug(String(Kg)).split("."),n=Ug("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a<r;a++)for(var i=t[a]||"",s=n[a]||"";i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],(0!=i[0].length||0!=s[0].length)&&(e=qg(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||qg(0==i[2].length,0==s[2].length)||qg(i[2],s[2]),i=i[3],s=s[3],0==e););return 0<=e},t=Zg,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var tm=wg.document&&Wg&&(Yg()||parseInt(Kg,10))||void 0;function nm(e,t){if(Mg.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 n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(Hg){e:{try{jg(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.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:rm[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&nm.X.h.call(this)}}Rg(nm,Mg);var rm={2:"touch",3:"pen",4:"mouse"};nm.prototype.h=function(){nm.X.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var im="closure_listenable_"+(1e6*Math.random()|0),sm=0;function am(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++sm,this.ba=this.ea=!1}function om(e){e.ba=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function cm(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function lm(e){const t={};for(const n in e)t[n]=e[n];return t}const um="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function hm(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<um.length;e++)n=um[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function dm(e){this.src=e,this.g={},this.h=0}function pm(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Dg(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(om(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function fm(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.ba&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}dm.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=fm(e,t,r,i);return-1<a?(t=e[a],n||(t.ea=!1)):((t=new am(t,this.src,s,!!r,i)).ea=n,e.push(t)),t};var gm="closure_lm_"+(1e6*Math.random()|0),mm={};function vm(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Em(r);return t&&t[im]?t.O(n,r,Tg(i)?!!i.capture:!!i,s):ym(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)vm(e,t[s],n,r,i);return null}return n=Em(n),e&&e[im]?e.N(t,n,Tg(r)?!!r.capture:!!r,i):ym(e,t,n,!1,r,i)}function ym(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=Tg(i)?!!i.capture:!!i,o=Im(e);if(o||(e[gm]=o=new dm(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=bm;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!Lg?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(wm(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function _m(e){var t,n,r;"number"!=typeof e&&e&&!e.ba&&((t=e.src)&&t[im]?pm(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(wm(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Im(t))?(pm(n,e),0==n.h&&(n.src=null,t[gm]=null)):om(e)))}function wm(e){return e in mm?mm[e]:mm[e]="on"+e}function bm(e,t){var n,r;return e=!!e.ba||(t=new nm(t,this),n=e.listener,r=e.ha||e.src,e.ea&&_m(e),n.call(r,t))}function Im(e){return(e=e[gm])instanceof dm?e:null}var Tm="__closure_events_fn_"+(1e9*Math.random()>>>0);function Em(t){return"function"==typeof t?t:(t[Tm]||(t[Tm]=function(e){return t.handleEvent(e)}),t[Tm])}function km(){xg.call(this),this.i=new dm(this),(this.P=this).I=null}function Sm(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new Mg(t,e):t instanceof Mg?t.target=t.target||e:(a=t,hm(t=new Mg(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Cm(s,r,!0,t)&&a;if(a=Cm(s=t.g=e,r,!0,t)&&a,a=Cm(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Cm(s=t.g=n[i],r,!1,t)&&a}function Cm(e,t,n,r){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,c=t[s];c&&!c.ba&&c.capture==n&&(a=c.listener,o=c.ha||c.src,c.ea&&pm(e.i,c),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}Rg(km,xg),km.prototype[im]=!0,km.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=Tg(i)?!!i.capture:!!i,r=Em(r),t&&t[im]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=fm(a=t.g[n],r,i,s))&&(om(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Im(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?fm(n,r,i,s):t)?n[t]:null)&&_m(r))}(this,e,t,n,r)},km.prototype.M=function(){if(km.X.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)om(n[r]);delete t.g[e],t.h--}}this.I=null},km.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},km.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Am=wg.JSON.stringify;var Nm,Rm=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 xm,e=>e.reset());class xm{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}}function Dm(e,t){var n;Nm||(n=wg.Promise.resolve(void 0),Nm=function(){n.then(Mm)}),Pm||(Nm(),Pm=!0),Om.add(e,t)}var Pm=!1,Om=new class{constructor(){this.h=this.g=null}add(e,t){const n=Rm.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Mm(){for(var e;e=function(){var e=Om;let 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){!function(e){wg.setTimeout(()=>{throw e},0)}(e)}var t=Rm;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Pm=!1}function Lm(e,t){km.call(this),this.h=e||1,this.g=t||wg,this.j=Ag(this.lb,this),this.l=Date.now()}function Fm(e){e.ca=!1,e.R&&(e.g.clearTimeout(e.R),e.R=null)}function Um(e,t,n){if("function"==typeof e)n&&(e=Ag(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Ag(e.handleEvent,e)}return 2147483647<Number(t)?-1:wg.setTimeout(e,t||0)}Rg(Lm,km),(bt=Lm.prototype).ca=!1,bt.R=null,bt.lb=function(){var e;this.ca&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.R=this.g.setTimeout(this.j,this.h-e):(this.R&&(this.g.clearTimeout(this.R),this.R=null),Sm(this,"tick"),this.ca&&(Fm(this),this.start())))},bt.start=function(){this.ca=!0,this.R||(this.R=this.g.setTimeout(this.j,this.h),this.l=Date.now())},bt.M=function(){Lm.X.M.call(this),Fm(this),delete this.g};class qm extends xg{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Um(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(wg.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Vm(e){xg.call(this),this.h=e,this.g={}}Rg(Vm,xg);var Bm=[];function jm(e,t,n,r){Array.isArray(n)||(n&&(Bm[0]=n.toString()),n=Bm);for(var i=0;i<n.length;i++){var s=vm(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function Km(e){cm(e.g,function(e,t){this.g.hasOwnProperty(t)&&_m(e)},e),e.g={}}function $m(){this.g=!0}function Wm(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[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 Am(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Vm.prototype.M=function(){Vm.X.M.call(this),Km(this)},Vm.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},$m.prototype.Aa=function(){this.g=!1},$m.prototype.info=function(){};var zm={},Gm=null;function Hm(){return Gm=Gm||new km}function Qm(e){Mg.call(this,zm.Pa,e)}function Ym(){var e=Hm();Sm(e,new Qm(e))}function Jm(e,t){Mg.call(this,zm.STAT_EVENT,e),this.stat=t}function Xm(e){var t=Hm();Sm(t,new Jm(t,e))}function Zm(e,t){Mg.call(this,zm.Qa,e),this.size=t}function ev(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return wg.setTimeout(function(){e()},t)}zm.Pa="serverreachability",Rg(Qm,Mg),zm.STAT_EVENT="statevent",Rg(Jm,Mg),zm.Qa="timingevent",Rg(Zm,Mg);It={NO_ERROR:0,mb:1,zb:2,yb:3,tb:4,xb:5,Ab:6,Ma:7,TIMEOUT:8,Db:9},Gc={rb:"complete",Nb:"success",Na:"error",Ma:"abort",Fb:"ready",Gb:"readystatechange",TIMEOUT:"timeout",Bb:"incrementaldata",Eb:"progress",ub:"downloadprogress",Vb:"uploadprogress"};function tv(){}function nv(e){return e.h||(e.h=e.i())}function rv(){}tv.prototype.h=null;yt={OPEN:"a",qb:"b",Na:"c",Cb:"d"};function iv(){Mg.call(this,"d")}function sv(){Mg.call(this,"c")}function av(){}function ov(e,t,n,r){this.l=e,this.j=t,this.m=n,this.U=r||1,this.S=new Vm(this),this.O=uv,this.T=new Lm(e=Gg?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.V=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.Y=-1,this.I=!1,this.N=0,this.L=null,this.$=this.J=this.Z=this.P=!1,this.h=new cv}function cv(){this.i=null,this.g="",this.h=!1}Rg(iv,Mg),Rg(sv,Mg),Rg(av,tv),av.prototype.g=function(){return new XMLHttpRequest},av.prototype.i=function(){return{}};var lv=new av,uv=45e3,hv={},dv={};function pv(e,t,n){e.K=1,e.v=xv(Sv(t)),e.s=n,e.P=!0,fv(e,null)}function fv(e,t){e.F=Date.now(),vv(e),e.A=Sv(e.v);var a,o,c,l,u,h,n=e.A,r=e.U;Array.isArray(r)||(r=[String(r)]),$v(n.i,"t",r),e.C=0,n=e.l.H,e.h=new cv,e.g=Ky(e.l,n?t:null,!e.s),0<e.N&&(e.L=new qm(Ag(e.La,e,e.g),e.N)),jm(e.S,e.g,"readystatechange",e.ib),t=e.H?lm(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.da(e.A,e.u,e.s,t)):(e.u="GET",e.g.da(e.A,e.u,null,t)),Ym(),a=e.j,o=e.u,c=e.A,l=e.m,u=e.U,h=e.s,a.info(function(){if(a.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+o+"\n"+c+"\n"+e})}function gv(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Da)}function mv(e,t,n){let r=!0,i;for(;!e.I&&e.C<n.length;){if(i=(a=n,c=o=void 0,o=(s=e).C,-1==(c=a.indexOf("\n",o))?dv:(o=Number(a.substring(o,c)),isNaN(o)?hv:(c+=1)+o>a.length?dv:(a=a.substr(c,o),s.C=c+o,a))),i==dv){4==t&&(e.o=4,Xm(14),r=!1),Wm(e.j,e.m,null,"[Incomplete Response]");break}if(i==hv){e.o=4,Xm(15),Wm(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}Wm(e.j,e.m,i,null),Iv(e,i)}var s,a,o,c;gv(e)&&i!=dv&&i!=hv&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,Xm(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.$&&(e.$=!0,(t=e.l).g==e&&t.$&&!t.K&&(t.j.info("Great, no buffering proxy detected. Bytes received: "+n.length),My(t),t.K=!0,Xm(11))):(Wm(e.j,e.m,n,"[Invalid Chunked Response]"),bv(e),wv(e))}function vv(e){e.V=Date.now()+e.O,yv(e,e.O)}function yv(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=ev(Ag(e.gb,e),t)}function _v(e){e.B&&(wg.clearTimeout(e.B),e.B=null)}function wv(e){0==e.l.G||e.I||Uy(e.l,e)}function bv(e){_v(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,Fm(e.T),Km(e.S),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Iv(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||Jv(n.h,e)))if(!e.J&&Jv(n.h,e)&&3==n.G){try{var r=n.Fa.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Fy(n),Cy(n)}Oy(n),Xm(18)}}else n.Ba=i[1],0<n.Ba-n.T&&i[2]<37500&&n.L&&0==n.A&&!n.v&&(n.v=ev(Ag(n.cb,n),6e3));if(Yv(n.h)<=1&&n.ja){try{n.ja()}catch(e){}n.ja=void 0}}else Vy(n,11)}else if(!e.J&&n.g!=e||Fy(n),!Fg(t))for(i=n.Fa.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.T=s[0],s=s[1],2==n.G)if("c"==s[0]){n.I=s[1],n.ka=s[2];var a=s[3];null!=a&&(n.ma=a,n.j.info("VER="+n.ma));var o=s[4];null!=o&&(n.Ca=o,n.j.info("SVER="+n.Ca));var c,l,u=s[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,n.J=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const f=e.g;if(f){const g=f.g?f.g.getResponseHeader("X-Client-Wire-Protocol"):null;g&&((c=r.h).g||-1==g.indexOf("spdy")&&-1==g.indexOf("quic")&&-1==g.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(Xv(c,c.h),c.h=null))),!r.D||(l=f.g?f.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.za=l,Rv(r.F,r.D,l))}n.G=3,n.l&&n.l.xa(),n.$&&(n.P=Date.now()-e.F,n.j.info("Handshake RTT: "+n.P+"ms"));var h,d,p=e;(r=n).sa=jy(r,r.H?r.ka:null,r.V),p.J?(Zv(r.h,p),h=p,(d=r.J)&&h.setTimeout(d),h.B&&(_v(h),vv(h)),r.g=p):Py(r),0<n.i.length&&Ny(n)}else"stop"!=s[0]&&"close"!=s[0]||Vy(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?Vy(n,7):Sy(n):"noop"!=s[0]&&n.l&&n.l.wa(s),n.A=0)}Ym()}catch(e){}}function Tv(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Ig(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.oa&&"function"==typeof e.oa)return e.oa();if(!e.W||"function"!=typeof e.W){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(Ig(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.W&&"function"==typeof e.W)return e.W();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(Ig(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(bt=ov.prototype).setTimeout=function(e){this.O=e},bt.ib=function(e){e=e.target;const t=this.L;t&&3==wy(e)?t.l():this.La(e)},bt.La=function(e){try{if(e==this.g)e:{var t=wy(this.g),n=this.g.Ea();this.g.aa();if(!(t<3)&&(3!=t||Gg||this.g&&(this.h.h||this.g.fa()||by(this.g)))){this.I||4!=t||7==n||Ym(),_v(this);var r=this.g.aa();this.Y=r;t:if(gv(this)){var i=by(this.g);e="";var s=i.length,a=4==wy(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){bv(this),wv(this);var o="";break t}this.h.i=new wg.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:a&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.fa();if(this.i=200==r,h=this.j,d=this.u,p=this.A,f=this.m,g=this.U,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+f+") [ attempt "+g+"]: "+d+"\n"+p+"\n"+m+" "+v}),this.i){if(this.Z&&!this.J){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!Fg(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,Xm(12),bv(this),wv(this);break e}Wm(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Iv(this,r)}this.P?(mv(this,t,o),Gg&&this.i&&3==t&&(jm(this.S,this.T,"tick",this.hb),this.T.start())):(Wm(this.j,this.m,o,null),Iv(this,o)),4==t&&bv(this),this.i&&!this.I&&(4==t?Uy(this.l,this):(this.i=!1,vv(this)))}else 400==r&&0<o.indexOf("Unknown SID")?(this.o=3,Xm(12)):(this.o=0,Xm(13)),bv(this),wv(this)}}}catch(e){}var h,d,p,f,g,m,v},bt.hb=function(){var e,t;this.g&&(e=wy(this.g),t=this.g.fa(),this.C<t.length&&(_v(this),mv(this,e,t),this.i&&4!=e&&vv(this)))},bt.cancel=function(){this.I=!0,bv(this)},bt.gb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.V?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.K&&(Ym(),Xm(17)),bv(this),this.o=2,wv(this)):yv(this,this.V-n)};var Ev=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function kv(e,t){var n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof kv?(this.h=void 0!==t?t:e.h,Cv(this,e.j),this.s=e.s,this.g=e.g,Av(this,e.m),this.l=e.l,t=e.i,(n=new Vv).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Nv(this,n),this.o=e.o):e&&(n=String(e).match(Ev))?(this.h=!!t,Cv(this,n[1]||"",!0),this.s=Dv(n[2]||""),this.g=Dv(n[3]||"",!0),Av(this,n[4]),this.l=Dv(n[5]||"",!0),Nv(this,n[6]||"",!0),this.o=Dv(n[7]||"")):(this.h=!!t,this.i=new Vv(null,this.h))}function Sv(e){return new kv(e)}function Cv(e,t,n){e.j=n?Dv(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Av(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Nv(e,t,n){var r,i;t instanceof Vv?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(Bv(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(jv(this,t),$v(this,n,e))},r)),r.j=i):(n||(t=Pv(t,Uv)),e.i=new Vv(t,e.h))}function Rv(e,t,n){e.i.set(t,n)}function xv(e){return Rv(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Dv(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Pv(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Ov),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Ov(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}kv.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Pv(t,Mv,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Pv(t,Mv,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Pv(n,"/"==n.charAt(0)?Fv:Lv,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Pv(n,qv)),e.join("")};var Mv=/[#\/\?@]/g,Lv=/[#\?:]/g,Fv=/[#\?]/g,Uv=/[#\?@]/g,qv=/#/g;function Vv(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Bv(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function jv(e,t){Bv(e),t=Wv(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Kv(e,t){return Bv(e),t=Wv(e,t),e.g.has(t)}function $v(e,t,n){jv(e,t),0<n.length&&(e.i=null,e.g.set(Wv(e,t),Pg(n)),e.h+=n.length)}function Wv(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(bt=Vv.prototype).add=function(e,t){Bv(this),this.i=null,e=Wv(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},bt.forEach=function(n,r){Bv(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},bt.oa=function(){Bv(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},bt.W=function(t){Bv(this);let n=[];if("string"==typeof t)Kv(this,t)&&(n=n.concat(this.g.get(Wv(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},bt.set=function(e,t){return Bv(this),this.i=null,Kv(this,e=Wv(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},bt.get=function(e,t){return e&&0<(e=this.W(e)).length?String(e[0]):t},bt.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.W(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")};var zv=class{constructor(e,t){this.h=e,this.g=t}};function Gv(e){this.l=e||10,e=wg.PerformanceNavigationTiming?0<(e=wg.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(wg.g&&wg.g.Ga&&wg.g.Ga()&&wg.g.Ga().$b),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var Hv;function Qv(e){return e.h||e.g&&e.g.size>=e.j}function Yv(e){return e.h?1:e.g?e.g.size:0}function Jv(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Xv(e,t){e.g?e.g.add(t):e.h=t}function Zv(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function ey(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Pg(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function ty(){}function ny(){this.g=new ty}function ry(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function iy(e){this.l=e.ac||null,this.j=e.jb||!1}function sy(e,t){km.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=ay,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Gv.prototype.cancel=function(){if(this.i=ey(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},ty.prototype.stringify=function(e){return wg.JSON.stringify(e,void 0)},ty.prototype.parse=function(e){return wg.JSON.parse(e,void 0)},Rg(iy,tv),iy.prototype.g=function(){return new sy(this.l,this.j)},iy.prototype.i=(Hv={},function(){return Hv}),Rg(sy,km);var ay=0;function oy(e){e.j.read().then(e.Ta.bind(e)).catch(e.ga.bind(e))}function cy(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ly(e)}function ly(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(bt=sy.prototype).open=function(e,t){if(this.readyState!=ay)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ly(this)},bt.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||wg).fetch(new Request(this.B,t)).then(this.Wa.bind(this),this.ga.bind(this))},bt.abort=function(){this.response=this.responseText="",this.v=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,cy(this)),this.readyState=ay},bt.Wa=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,ly(this)),this.g&&(this.readyState=3,ly(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ua.bind(this),this.ga.bind(this));else if(void 0!==wg.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;oy(this)}else e.text().then(this.Va.bind(this),this.ga.bind(this))},bt.Ta=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?cy:ly)(this),3==this.readyState&&oy(this))},bt.Va=function(e){this.g&&(this.response=this.responseText=e,cy(this))},bt.Ua=function(e){this.g&&(this.response=e,cy(this))},bt.ga=function(){this.g&&cy(this)},bt.setRequestHeader=function(e,t){this.v.append(e,t)},bt.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},bt.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(sy.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var uy=wg.JSON.parse;function hy(e){km.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=dy,this.K=this.L=!1}Rg(hy,km);var dy="",py=/^https?$/i,fy=["POST","PUT"];function gy(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,my(e),yy(e)}function my(e){e.D||(e.D=!0,Sm(e,"complete"),Sm(e,"error"))}function vy(e){if(e.h&&void 0!==_g&&(!e.C[1]||4!=wy(e)||2!=e.aa()))if(e.v&&4==wy(e))Um(e.Ha,0,e);else if(Sm(e,"readystatechange"),4==wy(e)){e.h=!1;try{var t,n,r,i,s=e.aa();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var a=!0;break e;default:a=!1}if((t=a)||((n=0===s)&&(!(i=String(e.H).match(Ev)[1]||null)&&wg.self&&wg.self.location&&(i=(r=wg.self.location.protocol).substr(0,r.length-1)),n=!py.test(i?i.toLowerCase():"")),t=n),t)Sm(e,"complete"),Sm(e,"success");else{e.m=6;try{var o=2<wy(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.aa()+"]",my(e)}}finally{yy(e)}}}function yy(e,t){if(e.g){_y(e);const n=e.g,r=e.C[0]?bg:null;e.g=null,e.C=null,t||Sm(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function _y(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(wg.clearTimeout(e.A),e.A=null)}function wy(e){return e.g?e.g.readyState:0}function by(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case dy:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Iy(e){let n="";return cm(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Ty(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Iy(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Rv(e,t,n))}function Ey(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function ky(e){this.Ca=0,this.i=[],this.j=new $m,this.ka=this.sa=this.F=this.V=this.g=this.za=this.D=this.ia=this.o=this.S=this.s=null,this.ab=this.U=0,this.Za=Ey("failFast",!1,e),this.L=this.v=this.u=this.m=this.l=null,this.Y=!0,this.pa=this.Ba=this.T=-1,this.Z=this.A=this.C=0,this.Xa=Ey("baseRetryDelayMs",5e3,e),this.bb=Ey("retryDelaySeedMs",1e4,e),this.$a=Ey("forwardChannelMaxRetries",2,e),this.ta=Ey("forwardChannelRequestTimeoutMs",2e4,e),this.ra=e&&e.xmlHttpFactory||void 0,this.Da=e&&e.Zb||!1,this.J=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.I="",this.h=new Gv(e&&e.concurrentRequestLimit),this.Fa=new ny,this.O=e&&e.fastHandshake||!1,this.N=e&&e.encodeInitMessageHeaders||!1,this.O&&this.N&&(this.N=!1),this.Ya=e&&e.Xb||!1,e&&e.Aa&&this.j.Aa(),e&&e.forceLongPolling&&(this.Y=!1),this.$=!this.O&&this.Y&&e&&e.detectBufferingProxy||!1,this.ja=void 0,this.P=0,this.K=!1,this.la=this.B=null}function Sy(e){var t,n;Ay(e),3==e.G&&(t=e.U++,Rv(n=Sv(e.F),"SID",e.I),Rv(n,"RID",t),Rv(n,"TYPE","terminate"),xy(e,n),(t=new ov(e,e.j,t,void 0)).K=2,t.v=xv(Sv(n)),n=!1,!(n=wg.navigator&&wg.navigator.sendBeacon?wg.navigator.sendBeacon(t.v.toString(),""):n)&&wg.Image&&((new Image).src=t.v,n=!0),n||(t.g=Ky(t.l,null),t.g.da(t.v)),t.F=Date.now(),vv(t)),By(e)}function Cy(e){e.g&&(My(e),e.g.cancel(),e.g=null)}function Ay(e){Cy(e),e.u&&(wg.clearTimeout(e.u),e.u=null),Fy(e),e.h.cancel(),e.m&&("number"==typeof e.m&&wg.clearTimeout(e.m),e.m=null)}function Ny(e){Qv(e.h)||e.m||(e.m=!0,Dm(e.Ja,e),e.C=0)}function Ry(e,t){var n=t?t.m:e.U++,r=Sv(e.F);Rv(r,"SID",e.I),Rv(r,"RID",n),Rv(r,"AID",e.T),xy(e,r),e.o&&e.s&&Ty(r,e.o,e.s),n=new ov(e,e.j,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.i=t.D.concat(e.i)),t=Dy(e,n,1e3),n.setTimeout(Math.round(.5*e.ta)+Math.round(.5*e.ta*Math.random())),Xv(e.h,n),pv(n,r,t)}function xy(e,n){e.ia&&cm(e.ia,function(e,t){Rv(n,t,e)}),e.l&&Tv({},function(e,t){Rv(n,t,e)})}function Dy(e,t,r){r=Math.min(e.i.length,r);var i=e.l?Ag(e.l.Ra,e.l,e):null;e:{var s=e.i;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].h,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].h,o=s[t].g;if((a-=n)<0)n=Math.max(0,s[t].h-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Tv(e,function(e,t){let n=e;Tg(e)&&(n=Am(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,c,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=c.join("&");break e}}}return e=e.i.splice(0,r),t.D=e,i}function Py(e){e.g||e.u||(e.Z=1,Dm(e.Ia,e),e.A=0)}function Oy(e){return!(e.g||e.u||3<=e.A)&&(e.Z++,e.u=ev(Ag(e.Ia,e),qy(e,e.A)),e.A++,1)}function My(e){null!=e.B&&(wg.clearTimeout(e.B),e.B=null)}function Ly(e){e.g=new ov(e,e.j,"rpc",e.Z),null===e.o&&(e.g.H=e.s),e.g.N=0;var t=Sv(e.sa);Rv(t,"RID","rpc"),Rv(t,"SID",e.I),Rv(t,"CI",e.L?"0":"1"),Rv(t,"AID",e.T),Rv(t,"TYPE","xmlhttp"),xy(e,t),e.o&&e.s&&Ty(t,e.o,e.s),e.J&&e.g.setTimeout(e.J);var n=e.g;e=e.ka,n.K=1,n.v=xv(Sv(t)),n.s=null,n.P=!0,fv(n,e)}function Fy(e){null!=e.v&&(wg.clearTimeout(e.v),e.v=null)}function Uy(e,t){var n,r,i,s=null;if(e.g==t){Fy(e),My(e),e.g=null;var a=2}else{if(!Jv(e.h,t))return;s=t.D,Zv(e.h,t),a=1}if(0!=e.G)if(e.pa=t.Y,t.i)1==a?(s=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,Sm(a=Hm(),new Zm(a,s)),Ny(e)):Py(e);else if(3==(n=t.o)||0==n&&0<e.pa||(1!=a||(i=t,Yv((r=e).h)>=r.h.j-(r.m?1:0)||(r.m?(r.i=i.D.concat(r.i),0):1==r.G||2==r.G||r.C>=(r.Za?0:r.$a)||(r.m=ev(Ag(r.Ja,r,i),qy(r,r.C)),r.C++,0))))&&(2!=a||!Oy(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),n){case 1:Vy(e,5);break;case 4:Vy(e,10);break;case 3:Vy(e,6);break;default:Vy(e,2)}}function qy(e,t){let n=e.Xa+Math.floor(Math.random()*e.bb);return e.l||(n*=2),n*t}function Vy(e,t){var n,r;e.j.info("Error code "+t),2==t?(n=null,e.l&&(n=null),r=Ag(e.kb,e),n||(n=new kv("//www.google.com/images/cleardot.gif"),wg.location&&"http"==wg.location.protocol||Cv(n,"https"),xv(n)),function(e,t){var n=new $m;if(wg.Image){const r=new Image;r.onload=Ng(ry,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Ng(ry,n,r,"TestLoadImage: error",!1,t),r.onabort=Ng(ry,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Ng(ry,n,r,"TestLoadImage: timeout",!1,t),wg.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):Xm(2),e.G=0,e.l&&e.l.va(t),By(e),Ay(e)}function By(e){var t;e.G=0,e.la=[],e.l&&(0==(t=ey(e.h)).length&&0==e.i.length||(Og(e.la,t),Og(e.la,e.i),e.h.i.length=0,Pg(e.i),e.i.length=0),e.l.ua())}function jy(e,t,n){var r,i,s=n instanceof kv?Sv(n):new kv(n,void 0);return""!=s.g?(t&&(s.g=t+"."+s.g),Av(s,s.m)):(s=(r=wg.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new kv(null,void 0),s&&Cv(i,s),t&&(i.g=t),r&&Av(i,r),n&&(i.l=n),s=i),n=e.D,t=e.za,n&&t&&Rv(s,n,t),Rv(s,"VER",e.ma),xy(e,s),s}function Ky(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Da&&!e.ra?new hy(new iy({jb:!0})):new hy(e.ra)).Ka(e.H),t}function $y(){}function Wy(){if(Wg&&!(10<=Number(tm)))throw Error("Environmental error: no available transport.")}function zy(e,t){km.call(this),this.g=new ky(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.s=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.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.S=e,(e=t&&t.Yb)&&!Fg(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Fg(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Qy(this)}function Gy(e){iv.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;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 Hy(){sv.call(this),this.status=1}function Qy(e){this.g=e}(bt=hy.prototype).Ka=function(e){this.L=e},bt.da=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||lv).g(),this.C=this.u?nv(this.u):nv(lv),this.g.onreadystatechange=Ag(this.Ha,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void gy(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const c of r.keys())n.set(c,r.get(c))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=wg.FormData&&e instanceof wg.FormData,0<=Dg(fy,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{_y(this),0<this.B&&((this.K=(o=this.g,Wg&&em()&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=Ag(this.qa,this)):this.A=Um(this.qa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){gy(this,e)}var o},bt.qa=function(){void 0!==_g&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Sm(this,"timeout"),this.abort(8))},bt.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Sm(this,"complete"),Sm(this,"abort"),yy(this))},bt.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),yy(this,!0)),hy.X.M.call(this)},bt.Ha=function(){this.s||(this.F||this.v||this.l?vy(this):this.fb())},bt.fb=function(){vy(this)},bt.aa=function(){try{return 2<wy(this)?this.g.status:-1}catch(e){return-1}},bt.fa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},bt.Sa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),uy(t)}},bt.Ea=function(){return this.m},bt.Oa=function(){return"string"==typeof this.j?this.j:String(this.j)},(bt=ky.prototype).ma=8,bt.G=1,bt.Ja=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;const s=new ov(this,this.j,t,void 0);let e=this.s;if(this.S&&(e?(e=lm(e),hm(e,this.S)):e=this.S),null!==this.o||this.N||(s.H=e,e=null),this.O)e:{for(var n=0,r=0;r<this.i.length;r++){var i=this.i[r];if("__data__"in i.g&&"string"==typeof(i=i.g.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.i.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Dy(this,s,n),Rv(r=Sv(this.F),"RID",t),Rv(r,"CVER",22),this.D&&Rv(r,"X-HTTP-Session-Id",this.D),xy(this,r),e&&(this.N?n="headers="+encodeURIComponent(String(Iy(e)))+"&"+n:this.o&&Ty(r,this.o,e)),Xv(this.h,s),this.Ya&&Rv(r,"TYPE","init"),this.O?(Rv(r,"$req",n),Rv(r,"SID","null"),s.Z=!0,pv(s,r,null)):pv(s,r,n),this.G=2}}else 3==this.G&&(t?Ry(this,t):0==this.i.length||Qv(this.h)||Ry(this))},bt.Ia=function(){var e;this.u=null,Ly(this),this.$&&!(this.K||null==this.g||this.P<=0)&&(e=2*this.P,this.j.info("BP detection timer enabled: "+e),this.B=ev(Ag(this.eb,this),e))},bt.eb=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.L=!1,this.K=!0,Xm(10),Cy(this),Ly(this))},bt.cb=function(){null!=this.v&&(this.v=null,Cy(this),Oy(this),Xm(19))},bt.kb=function(e){e?(this.j.info("Successfully pinged google.com"),Xm(2)):(this.j.info("Failed to ping google.com"),Xm(1))},(bt=$y.prototype).xa=function(){},bt.wa=function(){},bt.va=function(){},bt.ua=function(){},bt.Ra=function(){},Wy.prototype.g=function(e,t){return new zy(e,t)},Rg(zy,km),zy.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;Xm(0),e.V=t,e.ia=n||{},e.L=e.Y,e.F=jy(e,null,e.V),Ny(e)},zy.prototype.close=function(){Sy(this.g)},zy.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Am(e),e=t),n.i.push(new zv(n.ab++,e)),3==n.G&&Ny(n)},zy.prototype.M=function(){this.g.l=null,delete this.j,Sy(this.g),delete this.g,zy.X.M.call(this)},Rg(Gy,iv),Rg(Hy,sv),Rg(Qy,$y),Qy.prototype.xa=function(){Sm(this.g,"a")},Qy.prototype.wa=function(e){Sm(this.g,new Gy(e))},Qy.prototype.va=function(e){Sm(this.g,new Hy)},Qy.prototype.ua=function(){Sm(this.g,"b")},Wy.prototype.createWebChannel=Wy.prototype.g,zy.prototype.send=zy.prototype.u,zy.prototype.open=zy.prototype.m,It.NO_ERROR=0,It.TIMEOUT=8,It.HTTP_ERROR=6,Gc.COMPLETE="complete",(rv.EventType=yt).OPEN="a",yt.CLOSE="b",yt.ERROR="c",yt.MESSAGE="d",km.prototype.listen=km.prototype.N,hy.prototype.listenOnce=hy.prototype.O,hy.prototype.getLastError=hy.prototype.Oa,hy.prototype.getLastErrorCode=hy.prototype.Ea,hy.prototype.getStatus=hy.prototype.aa,hy.prototype.getResponseJson=hy.prototype.Sa,hy.prototype.getResponseText=hy.prototype.fa,hy.prototype.send=hy.prototype.da,hy.prototype.setWithCredentials=hy.prototype.Ka;var Yy,Jy=Hm,Xy=It,Zy=Gc,e_=zm,t_=10,n_=11,r_=iy,i_=rv,s_=hy;const a_="@firebase/firestore";class o_{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}}o_.UNAUTHENTICATED=new o_(null),o_.GOOGLE_CREDENTIALS=new o_("google-credentials-uid"),o_.FIRST_PARTY=new o_("first-party-uid"),o_.MOCK_USER=new o_("mock-user");let c_="9.13.0";const l_=new me("@firebase/firestore");function u_(){return l_.logLevel}function h_(e,...t){var n;l_.logLevel<=k.DEBUG&&(n=t.map(f_),l_.debug(`Firestore (${c_}): ${e}`,...n))}function d_(e,...t){var n;l_.logLevel<=k.ERROR&&(n=t.map(f_),l_.error(`Firestore (${c_}): ${e}`,...n))}function p_(e,...t){var n;l_.logLevel<=k.WARN&&(n=t.map(f_),l_.warn(`Firestore (${c_}): ${e}`,...n))}function f_(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function g_(e="Unexpected state"){var t=`FIRESTORE (${c_}) INTERNAL ASSERTION FAILED: `+e;throw d_(t),new Error(t)}function m_(e){e||g_()}const v_={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 y_ extends R{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class w_{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class b_{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(o_.UNAUTHENTICATED))}shutdown(){}}class I_{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 T_{constructor(e){this.t=e,this.currentUser=o_.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new __;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new __,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{h_("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,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):(h_("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new __))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(h_("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(m_("string"==typeof e.accessToken),new w_(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return m_(null===e||"string"==typeof e),new o_(e)}}class E_{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r,this.type="FirstParty",this.user=o_.FIRST_PARTY,this.p=new Map}I(){return this.g?this.g():(m_(!("object"!=typeof this.h||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}get headers(){this.p.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}class k_{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r}getToken(){return Promise.resolve(new E_(this.h,this.l,this.m,this.g))}start(e,t){e.enqueueRetryable(()=>t(o_.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class S_{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 C_{constructor(e){this.T=e,this.forceRefresh=!1,this.appCheck=null,this.A=null}start(t,n){const r=e=>{null!=e.error&&h_("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.A;return this.A=e.token,h_("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{h_("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.T.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.T.getImmediate({optional:!0}))?i(e):h_("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(m_("string"==typeof e.token),this.A=e.token,new S_(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class A_{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function N_(e,t){return e<t?-1:t<e?1:0}function R_(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function x_(e){return e+"\0"}class D_{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new y_(v_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new y_(v_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new y_(v_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new y_(v_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return D_.fromMillis(Date.now())}static fromDate(e){return D_.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new D_(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?N_(this.nanoseconds,e.nanoseconds):N_(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class P_{constructor(e){this.timestamp=e}static fromTimestamp(e){return new P_(e)}static min(){return new P_(new D_(0,0))}static max(){return new P_(new D_(253402300799,999999999))}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}}class O_{constructor(e,t,n){void 0===t?t=0:t>e.length&&g_(),void 0===n?n=e.length-t:n>e.length-t&&g_(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===O_.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof O_?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,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class M_ extends O_{construct(e,t,n){return new M_(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new y_(v_.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new M_(t)}static emptyPath(){return new M_([])}}const L_=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class F_ extends O_{construct(e,t,n){return new F_(e,t,n)}static isValidIdentifier(e){return L_.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!F_.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new F_(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new y_(v_.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new y_(v_.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new y_(v_.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new y_(v_.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new F_(t)}static emptyPath(){return new F_([])}}class U_{constructor(e){this.path=e}static fromPath(e){return new U_(M_.fromString(e))}static fromName(e){return new U_(M_.fromString(e).popFirst(5))}static empty(){return new U_(M_.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===M_.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return M_.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new U_(new M_(e.slice()))}}class q_{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function V_(e){return e.fields.find(e=>2===e.kind)}function B_(e){return e.fields.filter(e=>2!==e.kind)}q_.UNKNOWN_ID=-1;class j_{constructor(e,t){this.fieldPath=e,this.kind=t}}class K_{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new K_(0,z_.min())}}function $_(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=P_.fromTimestamp(1e9===r?new D_(n+1,0):new D_(n,r));return new z_(r,U_.empty(),t)}function W_(e){return new z_(e.readTime,e.key,-1)}class z_{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new z_(P_.min(),U_.empty(),-1)}static max(){return new z_(P_.max(),U_.empty(),-1)}}function G_(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=U_.comparator(e.documentKey,t.documentKey),0!==n?n:N_(e.largestBatchId,t.largestBatchId))}const H_="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Q_{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Y_(e){if(e.code!==v_.FAILED_PRECONDITION||e.message!==H_)throw e;h_("LocalStore","Unexpectedly lost primary lease")}class J_{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(r,i){return this.callbackAttached&&g_(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new J_((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof J_?t:J_.resolve(t)}catch(e){return J_.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):J_.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):J_.reject(t)}static resolve(n){return new J_((e,t)=>{e(n)})}static reject(n){return new J_((e,t)=>{t(n)})}static waitFor(e){return new J_((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=J_.resolve(!1);for(const n of e)t=t.next(e=>e?J_.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,c){return new J_((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;c(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new J_((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class X_{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.P=new __,this.transaction.oncomplete=()=>{this.P.resolve()},this.transaction.onabort=()=>{e.error?this.P.reject(new tw(n,e.error)):this.P.resolve()},this.transaction.onerror=e=>{var t=aw(e.target.error);this.P.reject(new tw(n,t))}}static open(e,t,n,r){try{return new X_(t,e.transaction(r,n))}catch(e){throw new tw(t,e)}}get v(){return this.P.promise}abort(e){e&&this.P.reject(e),this.aborted||(h_("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}V(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new rw(t)}}class Z_{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===Z_.D(h())&&d_("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.")}static delete(e){return h_("SimpleDb","Removing database:",e),iw(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!v())return!1;if(Z_.N())return!0;const e=h(),t=Z_.D(e),n=0<t&&t<10,r=Z_.k(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static N(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.O)}static M(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static k(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async F(s){return this.db||(h_("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new tw(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?r(new y_(v_.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?r(new y_(v_.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)):r(new tw(s,t))},i.onupgradeneeded=e=>{h_("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.$(t,i.transaction,e.oldVersion,this.version).next(()=>{h_("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.B&&(this.db.onversionchange=e=>this.B(e)),this.db}L(t){this.B=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.F(e);const t=X_.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.V(),e)).catch(e=>(t.abort(e),J_.reject(e))).toPromise();return s.catch(()=>{}),await t.v,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(h_("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class ew{constructor(e){this.U=e,this.q=!1,this.K=null}get isDone(){return this.q}get G(){return this.K}set cursor(e){this.U=e}done(){this.q=!0}j(e){this.K=e}delete(){return iw(this.U.delete())}}class tw extends y_{constructor(e,t){super(v_.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function nw(e){return"IndexedDbTransactionError"===e.name}class rw{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(h_("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(h_("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),iw(n)}add(e){return h_("SimpleDb","ADD",this.store.name,e,e),iw(this.store.add(e))}get(t){return iw(this.store.get(t)).next(e=>(h_("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return h_("SimpleDb","DELETE",this.store.name,e),iw(this.store.delete(e))}count(){return h_("SimpleDb","COUNT",this.store.name),iw(this.store.count())}W(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.H(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new J_((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}J(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new J_((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Y(e,t){h_("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.X=!1;var r=this.cursor(n);return this.H(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.H(r,t)}tt(i){const e=this.cursor({});return new J_((n,r)=>{e.onerror=e=>{var t=aw(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}H(e,s){const a=[];return new J_((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new ew(t),r=s(t.primaryKey,t.value,n);if(r instanceof J_){const e=r.catch(e=>(n.done(),J_.reject(e)));a.push(e)}n.isDone?i():null===n.G?t.continue():t.continue(n.G)}else i()}}).next(()=>J_.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function iw(e){return new J_((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=aw(e.target.error);r(t)}})}let sw=!1;function aw(e){const t=Z_.D(h());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new y_("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 sw||(sw=!0,setTimeout(()=>{throw e},0)),e}}return e}class ow{constructor(e,t){this.asyncQueue=e,this.et=t,this.task=null}start(){this.nt(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}nt(e){h_("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{h_("IndexBackiller",`Documents written: ${await this.et.st()}`)}catch(e){nw(e)?h_("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await Y_(e)}await this.nt(6e4)})}}class cw{constructor(e,t){this.localStore=e,this.persistence=t}async st(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.it(e,t))}it(e,t){const n=new Set;let r=t,i=!0;return J_.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(h_("IndexBackiller",`Processing collection: ${t}`),this.rt(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}rt(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.ot(n,e)).next(e=>(h_("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}ot(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=W_(t);0<G_(n,r)&&(r=n)}),new z_(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class lw{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ut(e),this.ct=e=>t.writeSequenceNumber(e))}ut(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ct&&this.ct(e),e}}function uw(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function hw(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function dw(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}lw.at=-1;class pw{constructor(e,t){this.comparator=e,this.root=t||gw.EMPTY}insert(e,t){return new pw(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,gw.BLACK,null,null))}remove(e){return new pw(this.comparator,this.root.remove(e,this.comparator).copy(null,null,gw.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.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(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new fw(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new fw(this.root,e,this.comparator,!1)}getReverseIterator(){return new fw(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new fw(this.root,e,this.comparator,!0)}}class fw{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(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(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class gw{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:gw.RED,this.left=null!=r?r:gw.EMPTY,this.right=null!=i?i:gw.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new gw(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return gw.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return gw.EMPTY;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.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,gw.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,gw.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 g_();if(this.right.isRed())throw g_();var e=this.left.check();if(e!==this.right.check())throw g_();return e+(this.isRed()?0:1)}}gw.EMPTY=null,gw.RED=!0,gw.BLACK=!1,gw.EMPTY=new class{constructor(){this.size=0}get key(){throw g_()}get value(){throw g_()}get color(){throw g_()}get left(){throw g_()}get right(){throw g_()}copy(e,t,n,r,i){return this}insert(e,t,n){return new gw(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 mw{constructor(e){this.comparator=e,this.data=new pw(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(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new vw(this.data.getIterator())}getIteratorFrom(e){return new vw(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 mw))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new mw(this.comparator);return t.data=e,t}}class vw{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function yw(e){return e.hasNext()?e.getNext():void 0}class _w{constructor(e){(this.fields=e).sort(F_.comparator)}static empty(){return new _w([])}unionWith(e){let t=new mw(F_.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new _w(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return R_(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class ww{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new ww(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new ww(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(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return N_(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ww.EMPTY_BYTE_STRING=new ww("");const bw=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Iw(t){if(m_(!!t),"string"!=typeof t)return{seconds:Tw(t.seconds),nanos:Tw(t.nanos)};{let e=0;var n=bw.exec(t);m_(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Tw(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ew(e){return"string"==typeof e?ww.fromBase64String(e):ww.fromUint8Array(e)}function kw(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Sw(e){var t=Iw(e.mapValue.fields.__local_write_time__.timestampValue);return new D_(t.seconds,t.nanos)}class Cw{constructor(e,t,n,r,i,s,a,o){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.useFetchStreams=o}}class Aw{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Aw("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Aw&&e.projectId===this.projectId&&e.database===this.database}}function Nw(e){return null==e}function Rw(e){return 0===e&&1/e==-1/0}function xw(e){return"number"==typeof e&&Number.isInteger(e)&&!Rw(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}const Dw={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Pw={nullValue:"NULL_VALUE"};function Ow(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?kw(e)?4:Gw(e)?9007199254740991:10:g_()}function Mw(r,i){if(r===i)return!0;var e,t,n=Ow(r);if(n!==Ow(i))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return Sw(r).isEqual(Sw(i));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=Iw(r.timestampValue),n=Iw(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,Ew(r.bytesValue).isEqual(Ew(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,Tw((t=r).geoPointValue.latitude)===Tw(e.geoPointValue.latitude)&&Tw(t.geoPointValue.longitude)===Tw(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Tw(e.integerValue)===Tw(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Tw(e.doubleValue),r=Tw(t.doubleValue);return n===r?Rw(n)===Rw(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return R_(r.arrayValue.values||[],i.arrayValue.values||[],Mw);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(uw(t)!==uw(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!Mw(t[e],n[e])))return!1;return!0}(r);default:return g_()}}function Lw(e,t){return void 0!==(e.values||[]).find(e=>Mw(e,t))}function Fw(e,t){if(e===t)return 0;var n,r,i,s,a=Ow(e),o=Ow(t);if(a!==o)return N_(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return N_(e.booleanValue,t.booleanValue);case 2:return r=t,i=Tw(e.integerValue||e.doubleValue),s=Tw(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Uw(e.timestampValue,t.timestampValue);case 4:return Uw(Sw(e),Sw(t));case 5:return N_(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ew(e),r=Ew(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=N_(n[i],r[i]);if(0!==t)return t}return N_(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=N_(Tw(n.latitude),Tw(r.latitude)))?s:N_(Tw(n.longitude),Tw(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Fw(n[i],r[i]);if(t)return t}return N_(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Dw.mapValue&&t===Dw.mapValue)return 0;if(e===Dw.mapValue)return 1;if(t===Dw.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=N_(r[o],s[o]);if(0!==t)return t;var a=Fw(n[r[o]],i[s[o]]);if(0!==a)return a}return N_(r.length,s.length)}(e.mapValue,t.mapValue);default:throw g_()}}function Uw(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return N_(e,t);var n=Iw(e),r=Iw(t),i=N_(n.seconds,r.seconds);return 0!==i?i:N_(n.nanos,r.nanos)}function qw(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?function(e){const t=Iw(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?Ew(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,U_.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):g_();var t}(e)}function Vw(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Bw(e){return e&&"integerValue"in e}function jw(e){return!!e&&"arrayValue"in e}function Kw(e){return e&&"nullValue"in e}function $w(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Ww(e){return e&&"mapValue"in e}function zw(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){const n={mapValue:{fields:{}}};return hw(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=zw(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=zw(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Gw(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Hw(e,t){var n=Fw(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Qw(e,t){var n=Fw(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Yw{constructor(e){this.value=e}static empty(){return new Yw({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!Ww(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=zw(t)}setAll(e){let n=F_.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=zw(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Ww(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Mw(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];Ww(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){hw(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Yw(zw(this.value))}}class Jw{constructor(e,t,n,r,i,s){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=i,this.documentState=s}static newInvalidDocument(e){return new Jw(e,0,P_.min(),P_.min(),Yw.empty(),0)}static newFoundDocument(e,t,n){return new Jw(e,1,t,P_.min(),n,0)}static newNoDocument(e,t){return new Jw(e,2,t,P_.min(),Yw.empty(),0)}static newUnknownDocument(e,t){return new Jw(e,3,t,P_.min(),Yw.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Yw.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Yw.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 Jw&&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 Jw(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Xw{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ht=null}}function Zw(e,t=null,n=[],r=[],i=null,s=null,a=null){return new Xw(e,t,n,r,i,s,a)}function eb(e){const t=e;if(null===t.ht){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>{return(t=e).field.canonicalString()+t.op.toString()+qw(t.value);var t}).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),Nw(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>qw(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>qw(e)).join(",")),t.ht=e}return t.ht}function tb(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let a=0;a<e.orderBy.length;a++)if(n=e.orderBy[a],r=t.orderBy[a],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,i,s;if(e.filters.length!==t.filters.length)return!1;for(let o=0;o<e.filters.length;o++)if(i=e.filters[o],s=t.filters[o],i.op!==s.op||!i.field.isEqual(s.field)||!Mw(i.value,s.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!yb(e.startAt,t.startAt)&&yb(e.endAt,t.endAt)}function nb(e){return U_.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function rb(e,t){return e.filters.filter(e=>e instanceof ab&&e.field.isEqual(t))}function ib(t,n,r){let i=Pw,s=!0;for(const r of rb(t,n)){let e=Pw,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Pw:"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?Vw(Aw.empty(),U_.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:g_();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Pw}Hw({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Hw({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function sb(t,n,r){let i=Dw,s=!0;for(const r of rb(t,n)){let e=Dw,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.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?Vw(Aw.empty(),U_.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Dw:g_(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Dw}0<Qw({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Qw({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class ab extends class{}{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.lt(e,t,n):new ob(e,t,n):"array-contains"===t?new hb(e,n):"in"===t?new db(e,n):"not-in"===t?new pb(e,n):"array-contains-any"===t?new fb(e,n):new ab(e,t,n)}static lt(e,t,n){return new("in"===t?cb:lb)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.ft(Fw(t,this.value)):null!==t&&Ow(this.value)===Ow(t)&&this.ft(Fw(t,this.value))}ft(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 g_()}}dt(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class ob extends ab{constructor(e,t,n){super(e,t,n),this.key=U_.fromName(n.referenceValue)}matches(e){var t=U_.comparator(e.key,this.key);return this.ft(t)}}class cb extends ab{constructor(e,t){super(e,"in",t),this.keys=ub(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class lb extends ab{constructor(e,t){super(e,"not-in",t),this.keys=ub(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function ub(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>U_.fromName(e.referenceValue))}class hb extends ab{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return jw(t)&&Lw(t.arrayValue,this.value)}}class db extends ab{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Lw(this.value.arrayValue,t)}}class pb extends ab{constructor(e,t){super(e,"not-in",t)}matches(e){if(Lw(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Lw(this.value.arrayValue,t)}}class fb extends ab{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!jw(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Lw(this.value.arrayValue,e))}}class gb{constructor(e,t){this.position=e,this.inclusive=t}}class mb{constructor(e,t="asc"){this.field=e,this.dir=t}}function vb(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?U_.comparator(U_.fromName(a.referenceValue),n.key):Fw(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function yb(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 n=0;n<e.position.length;n++)if(!Mw(e.position[n],t.position[n]))return!1;return!0}class _b{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this._t=null,this.wt=null,this.startAt,this.endAt}}function wb(e,t,n,r,i,s,a,o){return new _b(e,t,n,r,i,s,a,o)}function bb(e){return new _b(e)}function Ib(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 Tb(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Eb(e){for(const t of e.filters)if(t.dt())return t.field;return null}function kb(e){return null!==e.collectionGroup}function Sb(t){const n=t;if(null===n._t){n._t=[];const t=Eb(n),e=Tb(n);if(null!==t&&null===e)t.isKeyField()||n._t.push(new mb(t)),n._t.push(new mb(F_.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n._t.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n._t.push(new mb(F_.keyField(),t))}}}return n._t}function Cb(e){const t=e;if(!t.wt)if("F"===t.limitType)t.wt=Zw(t.path,t.collectionGroup,Sb(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of Sb(t)){const t="desc"===i.dir?"asc":"desc";e.push(new mb(i.field,t))}var n=t.endAt?new gb(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new gb(t.startAt.position,t.startAt.inclusive):null;t.wt=Zw(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.wt}function Ab(e,t,n){return new _b(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Nb(e,t){return tb(Cb(e),Cb(t))&&e.limitType===t.limitType}function Rb(e){return`${eb(Cb(e))}|lt:${e.limitType}`}function xb(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>{return`${(t=e).field.canonicalString()} ${t.op} ${qw(t.value)}`;var t}).join(", ")}]`),Nw(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>qw(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>qw(e)).join(",")),`Target(${t})`}(Cb(e))}; limitType=${e.limitType})`}function Db(n,e){return e.isFoundDocument()&&(i=n,a=(s=e).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):U_.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(i=e,(!(e=n).startAt||(t=e.startAt,r=vb(t,Sb(e),i),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=vb(t,Sb(e),i),t.inclusive?0<=r:0<r)));var t,r,i,s,a}function Pb(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ob(i){return(e,t)=>{let n=!1;for(const r of Sb(i)){const i=function(e,i,t){var n=e.field.isKeyField()?U_.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?Fw(n,r):g_()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return g_()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}function Mb(e,t){if(e.gt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Rw(t)?"-0":t}}function Lb(e){return{integerValue:""+e}}function Fb(e,t){return xw(t)?Lb(t):Mb(e,t)}class Ub{constructor(){this._=void 0}}function qb(e,t){return e instanceof Wb?Bw(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class Vb extends Ub{}class Bb extends Ub{constructor(e){super(),this.elements=e}}function jb(e,t){const n=Gb(t);for(const t of e.elements)n.some(e=>Mw(e,t))||n.push(t);return{arrayValue:{values:n}}}class Kb extends Ub{constructor(e){super(),this.elements=e}}function $b(e,t){let n=Gb(t);for(const t of e.elements)n=n.filter(e=>!Mw(e,t));return{arrayValue:{values:n}}}class Wb extends Ub{constructor(e,t){super(),this.It=e,this.yt=t}}function zb(e){return Tw(e.integerValue||e.doubleValue)}function Gb(e){return jw(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Hb{constructor(e,t){this.field=e,this.transform=t}}class Qb{constructor(e,t){this.version=e,this.transformResults=t}}class Yb{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Yb}static exists(e){return new Yb(void 0,e)}static updateTime(e){return new Yb(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 Jb(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Xb{}function Zb(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new cI(e.key,Yb.none()):new rI(e.key,e.data,Yb.none());{const i=e.data,s=Yw.empty();let t=new mw(F_.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new iI(e.key,s,new _w(t.toArray()),Yb.none())}}function eI(e,t,n){e instanceof rI?function(e,t,n){const r=e.value.clone(),i=aI(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof iI?function(e,t,n){if(!Jb(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=aI(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(sI(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function tI(e,t,n,r){return e instanceof rI?function(e,t,n,r){if(!Jb(e.precondition,t))return n;const i=e.value.clone(),s=oI(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof iI?function(e,t,n,r){if(!Jb(e.precondition,t))return n;const i=oI(e.fieldTransforms,r,t),s=t.data;return s.setAll(sI(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,Jb(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function nI(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&R_(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof Bb&&t instanceof Bb||e instanceof Kb&&t instanceof Kb?R_(e.elements,t.elements,Mw):e instanceof Wb&&t instanceof Wb?Mw(e.yt,t.yt):e instanceof Vb&&t instanceof Vb)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class rI extends Xb{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class iI extends Xb{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function sI(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function aI(e,t,n){const r=new Map;m_(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,c=a,l=n[u],o instanceof Bb?jb(o,c):o instanceof Kb?$b(o,c):l))}var o,c,l;return r}function oI(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,a=t,c=o=void 0,i instanceof Vb?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:a.seconds,nanos:a.nanoseconds}}}};return s&&(e.fields.__previous_value__=s),{mapValue:e}}():i instanceof Bb?jb(i,s):i instanceof Kb?$b(i,s):(o=qb(i=i,s),c=zb(o)+zb(i.yt),Bw(o)&&Bw(i.yt)?Lb(c):Mb(i.It,c))))}var i,s,a,o,c;return r}class cI extends Xb{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class lI extends Xb{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class uI{constructor(e){this.count=e}}function hI(e){switch(e){default:return g_(),0;case v_.CANCELLED:case v_.UNKNOWN:case v_.DEADLINE_EXCEEDED:case v_.RESOURCE_EXHAUSTED:case v_.INTERNAL:case v_.UNAVAILABLE:case v_.UNAUTHENTICATED:return;case v_.INVALID_ARGUMENT:case v_.NOT_FOUND:case v_.ALREADY_EXISTS:case v_.PERMISSION_DENIED:case v_.FAILED_PRECONDITION:case v_.ABORTED:case v_.OUT_OF_RANGE:case v_.UNIMPLEMENTED:case v_.DATA_LOSS:return 1}}function dI(e){if(void 0===e)return d_("GRPC error has no .code"),v_.UNKNOWN;switch(e){case Yy.OK:return v_.OK;case Yy.CANCELLED:return v_.CANCELLED;case Yy.UNKNOWN:return v_.UNKNOWN;case Yy.DEADLINE_EXCEEDED:return v_.DEADLINE_EXCEEDED;case Yy.RESOURCE_EXHAUSTED:return v_.RESOURCE_EXHAUSTED;case Yy.INTERNAL:return v_.INTERNAL;case Yy.UNAVAILABLE:return v_.UNAVAILABLE;case Yy.UNAUTHENTICATED:return v_.UNAUTHENTICATED;case Yy.INVALID_ARGUMENT:return v_.INVALID_ARGUMENT;case Yy.NOT_FOUND:return v_.NOT_FOUND;case Yy.ALREADY_EXISTS:return v_.ALREADY_EXISTS;case Yy.PERMISSION_DENIED:return v_.PERMISSION_DENIED;case Yy.FAILED_PRECONDITION:return v_.FAILED_PRECONDITION;case Yy.ABORTED:return v_.ABORTED;case Yy.OUT_OF_RANGE:return v_.OUT_OF_RANGE;case Yy.UNIMPLEMENTED:return v_.UNIMPLEMENTED;case Yy.DATA_LOSS:return v_.DATA_LOSS;default:return g_()}}(It=Yy=Yy||{})[It.OK=0]="OK",It[It.CANCELLED=1]="CANCELLED",It[It.UNKNOWN=2]="UNKNOWN",It[It.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",It[It.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",It[It.NOT_FOUND=5]="NOT_FOUND",It[It.ALREADY_EXISTS=6]="ALREADY_EXISTS",It[It.PERMISSION_DENIED=7]="PERMISSION_DENIED",It[It.UNAUTHENTICATED=16]="UNAUTHENTICATED",It[It.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",It[It.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",It[It.ABORTED=10]="ABORTED",It[It.OUT_OF_RANGE=11]="OUT_OF_RANGE",It[It.UNIMPLEMENTED=12]="UNIMPLEMENTED",It[It.INTERNAL=13]="INTERNAL",It[It.UNAVAILABLE=14]="UNAVAILABLE",It[It.DATA_LOSS=15]="DATA_LOSS";class pI{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){hw(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return dw(this.inner)}size(){return this.innerSize}}const fI=new pw(U_.comparator);const gI=new pw(U_.comparator);function mI(...e){let t=gI;for(const n of e)t=t.insert(n.key,n);return t}function vI(e){let n=gI;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function yI(){return new pI(e=>e.toString(),(e,t)=>e.isEqual(t))}const _I=new pw(U_.comparator),wI=new mw(U_.comparator);function bI(...e){let t=wI;for(const n of e)t=t.add(n);return t}const II=new mw(N_);class TI{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,EI.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new TI(P_.min(),r,II,fI,bI())}}class EI{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new EI(n,t,bI(),bI(),bI())}}class kI{constructor(e,t,n,r){this.Tt=e,this.removedTargetIds=t,this.key=n,this.Et=r}}class SI{constructor(e,t){this.targetId=e,this.At=t}}class CI{constructor(e,t,n=ww.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class AI{constructor(){this.Rt=0,this.bt=xI(),this.Pt=ww.EMPTY_BYTE_STRING,this.vt=!1,this.Vt=!0}get current(){return this.vt}get resumeToken(){return this.Pt}get St(){return 0!==this.Rt}get Dt(){return this.Vt}Ct(e){0<e.approximateByteSize()&&(this.Vt=!0,this.Pt=e)}xt(){let n=bI(),r=bI(),i=bI();return this.bt.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:g_()}}),new EI(this.Pt,this.vt,n,r,i)}Nt(){this.Vt=!1,this.bt=xI()}kt(e,t){this.Vt=!0,this.bt=this.bt.insert(e,t)}Ot(e){this.Vt=!0,this.bt=this.bt.remove(e)}Mt(){this.Rt+=1}Ft(){--this.Rt}$t(){this.Vt=!0,this.vt=!0}}class NI{constructor(e){this.Bt=e,this.Lt=new Map,this.Ut=fI,this.qt=RI(),this.Kt=new mw(N_)}Gt(e){for(const t of e.Tt)e.Et&&e.Et.isFoundDocument()?this.Qt(t,e.Et):this.jt(t,e.key,e.Et);for(const n of e.removedTargetIds)this.jt(n,e.key,e.Et)}Wt(n){this.forEachTarget(n,e=>{const t=this.zt(e);switch(n.state){case 0:this.Ht(e)&&t.Ct(n.resumeToken);break;case 1:t.Ft(),t.St||t.Nt(),t.Ct(n.resumeToken);break;case 2:t.Ft(),t.St||this.removeTarget(e);break;case 3:this.Ht(e)&&(t.$t(),t.Ct(n.resumeToken));break;case 4:this.Ht(e)&&(this.Jt(e),t.Ct(n.resumeToken));break;default:g_()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Lt.forEach((e,t)=>{this.Ht(t)&&n(t)})}Yt(e){const t=e.targetId,n=e.At.count,r=this.Xt(t);if(r){const e=r.target;if(nb(e))if(0===n){const n=new U_(e.path);this.jt(t,n,Jw.newNoDocument(n,P_.min()))}else m_(1===n);else this.Zt(t)!==n&&(this.Jt(t),this.Kt=this.Kt.add(t))}}te(r){const i=new Map;this.Lt.forEach((e,t)=>{var n=this.Xt(t);if(n){if(e.current&&nb(n.target)){const i=new U_(n.target.path);null!==this.Ut.get(i)||this.ee(t,i)||this.jt(t,i,Jw.newNoDocument(i,r))}e.Dt&&(i.set(t,e.xt()),e.Nt())}});let s=bI();this.qt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Xt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.Ut.forEach((e,t)=>t.setReadTime(r));var e=new TI(r,i,this.Kt,this.Ut,s);return this.Ut=fI,this.qt=RI(),this.Kt=new mw(N_),e}Qt(e,t){var n;this.Ht(e)&&(n=this.ee(e,t.key)?2:0,this.zt(e).kt(t.key,n),this.Ut=this.Ut.insert(t.key,t),this.qt=this.qt.insert(t.key,this.ne(t.key).add(e)))}jt(e,t,n){if(this.Ht(e)){const r=this.zt(e);this.ee(e,t)?r.kt(t,1):r.Ot(t),this.qt=this.qt.insert(t,this.ne(t).delete(e)),n&&(this.Ut=this.Ut.insert(t,n))}}removeTarget(e){this.Lt.delete(e)}Zt(e){var t=this.zt(e).xt();return this.Bt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Mt(e){this.zt(e).Mt()}zt(e){let t=this.Lt.get(e);return t||(t=new AI,this.Lt.set(e,t)),t}ne(e){let t=this.qt.get(e);return t||(t=new mw(N_),this.qt=this.qt.insert(e,t)),t}Ht(e){var t=null!==this.Xt(e);return t||h_("WatchChangeAggregator","Detected inactive target",e),t}Xt(e){var t=this.Lt.get(e);return t&&t.St?null:this.Bt.se(e)}Jt(t){this.Lt.set(t,new AI),this.Bt.getRemoteKeysForTarget(t).forEach(e=>{this.jt(t,e,null)})}ee(e,t){return this.Bt.getRemoteKeysForTarget(e).has(t)}}function RI(){return new pw(U_.comparator)}function xI(){return new pw(U_.comparator)}const DI={asc:"ASCENDING",desc:"DESCENDING"},PI={"<":"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"};class OI{constructor(e,t){this.databaseId=e,this.gt=t}}function MI(e,t){return e.gt?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function LI(e,t){return e.gt?t.toBase64():t.toUint8Array()}function FI(e){return m_(!!e),P_.fromTimestamp((t=Iw(e),new D_(t.seconds,t.nanos)));var t}function UI(e,t){return e=e,new M_(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function qI(e){var t=M_.fromString(e);return m_(rT(t)),t}function VI(e,t){return UI(e.databaseId,t.path)}function BI(e,t){const n=qI(t);if(n.get(1)!==e.databaseId.projectId)throw new y_(v_.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new y_(v_.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new U_(WI(n))}function jI(e,t){return UI(e.databaseId,t)}function KI(e){var t=qI(e);return 4===t.length?M_.emptyPath():WI(t)}function $I(e){return new M_(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function WI(e){return m_(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function zI(e,t,n){return{name:VI(e,t),fields:n.value.mapValue.fields}}function GI(e,t,n){const r=BI(e,t.name),i=FI(t.updateTime),s=new Yw({mapValue:{fields:t.fields}}),a=Jw.newFoundDocument(r,i,s);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function HI(e,t){let n;if(t instanceof rI)n={update:zI(e,t.key,t.value)};else if(t instanceof cI)n={delete:VI(e,t.key)};else if(t instanceof iI)n={update:zI(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof lI))return g_();n={verify:VI(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof Vb)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof Bb)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Kb)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof Wb)return{fieldPath:e.field.canonicalString(),increment:t.yt};throw g_()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,MI(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:g_()),n;var r}function QI(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?Yb.updateTime(FI(i.updateTime)):void 0!==i.exists?Yb.exists(i.exists):Yb.none():Yb.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)m_("REQUEST_TIME"===t.setToServerValue),n=new Vb;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new Bb(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new Kb(e)}else"increment"in t?n=new Wb(e,t.increment):g_();var r=F_.fromServerFormat(t.fieldPath);return new Hb(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=BI(t,n.update.name),a=new Yw({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new _w(e.map(e=>F_.fromServerFormat(e)))}();return new iI(s,a,t,e,r)}return new rI(s,a,e,r)}if(n.delete){const r=BI(t,n.delete);return new cI(r,e)}if(n.verify){const r=BI(t,n.verify);return new lI(r,e)}return g_()}function YI(e,t){return{documents:[jI(e,t.path)]}}function JI(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=jI(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=jI(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if($w(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NAN"}};if(Kw(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NULL"}}}else if("!="===e.op){if($w(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NOT_NAN"}};if(Kw(e.value))return{unaryFilter:{field:ZI(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ZI(e.field),op:(t=e.op,PI[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:ZI(e.field),direction:(e=e.dir,DI[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.gt||Nw(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(i=t.startAt).inclusive,values:i.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function XI(e){let t=KI(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){m_(1===r);const f=n.from[0];f.allDescendants?i=f.collectionId:t=t.child(f.collectionId)}let s=[];n.where&&(s=function t(e){return e?void 0!==e.unaryFilter?[nT(e)]:void 0!==e.fieldFilter?[tT(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):g_():[]}(n.where));let a=[];n.orderBy&&(a=n.orderBy.map(e=>function(e){return new mb(eT(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var c,l,u,h;n.limit&&(o=(e=n.limit,Nw(c="object"==typeof e?e.value:e)?null:c));let d=null;n.startAt&&(d=(l=n.startAt,h=!!l.before,u=l.values||[],new gb(u,h)));let p=null;return n.endAt&&(p=(l=n.endAt,u=!l.before,h=l.values||[],new gb(h,u))),wb(t,i,a,s,o,"F",d,p)}function ZI(e){return{fieldPath:e.canonicalString()}}function eT(e){return F_.fromServerFormat(e.fieldPath)}function tT(e){return ab.create(eT(e.fieldFilter.field),function(){switch(e.fieldFilter.op){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 g_()}}(),e.fieldFilter.value)}function nT(e){switch(e.unaryFilter.op){case"IS_NAN":var t=eT(e.unaryFilter.field);return ab.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=eT(e.unaryFilter.field);return ab.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=eT(e.unaryFilter.field);return ab.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=eT(e.unaryFilter.field);return ab.create(n,"!=",{nullValue:"NULL_VALUE"});default:return g_()}}function rT(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function iT(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=sT(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return sT(t)}function sT(e){return e+""}function aT(t){const n=t.length;if(m_(2<=n),2===n)return m_(""===t.charAt(0)&&""===t.charAt(1)),M_.emptyPath();const r=n-2,i=[];let s="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>r)&&g_(),t.charAt(n+1)){case"":const r=t.substring(a,n);let e;0===s.length?e=r:(s+=r,e=s,s=""),i.push(e);break;case"":s+=t.substring(a,n),s+="\0";break;case"":s+=t.substring(a,n+1);break;default:g_()}a=n+2}return new M_(i)}const oT=["userId","batchId"];function cT(e,t){return[e,iT(t)]}function lT(e,t,n){return[e,iT(t),n]}const uT={},hT=["prefixPath","collectionGroup","readTime","documentId"],dT=["prefixPath","collectionGroup","documentId"],pT=["collectionGroup","readTime","prefixPath","documentId"],fT=["canonicalId","targetId"],gT=["targetId","path"],mT=["path","targetId"],vT=["collectionId","parent"],yT=["indexId","uid"],_T=["uid","sequenceNumber"],wT=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],bT=["indexId","uid","orderedDocumentKey"],IT=["userId","collectionPath","documentId"],TT=["userId","collectionPath","largestBatchId"],ET=["userId","collectionGroup","largestBatchId"],kT=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ST=[...kT,"documentOverlays"],CT=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],AT=CT,NT=[...AT,"indexConfiguration","indexState","indexEntries"];class RT extends Q_{constructor(e,t){super(),this.ie=e,this.currentSequenceNumber=t}}function xT(e,t){var n=e;return Z_.M(n.ie,t)}class DT{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&eI(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=tI(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=tI(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=yI();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=Zb(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(P_.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),bI())}isEqual(e){return this.batchId===e.batchId&&R_(this.mutations,e.mutations,(e,t)=>nI(e,t))&&R_(this.baseMutations,e.baseMutations,(e,t)=>nI(e,t))}}class PT{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){m_(e.mutations.length===n.length);let r=_I;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new PT(e,t,n,r)}}class OT{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{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class MT{constructor(e,t,n,r,i=P_.min(),s=P_.min(),a=ww.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a}withSequenceNumber(e){return new MT(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new MT(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new MT(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class LT{constructor(e){this.re=e}}function FT(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:UT(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:VI(i=e.re,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:MI(i,e.version.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:qT(t.version)};else{if(!t.isUnknownDocument())return g_();r.unknownDocument={path:n.path.toArray(),version:qT(t.version)}}var i;return r}function UT(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function qT(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function VT(e){var t=new D_(e.seconds,e.nanoseconds);return P_.fromTimestamp(t)}function BT(t,e){const n=(e.baseMutations||[]).map(e=>QI(t.re,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>QI(t.re,e)),i=D_.fromMillis(e.localWriteTimeMs);return new DT(e.batchId,i,n,r)}function jT(e){var t,n=VT(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?VT(e.lastLimboFreeSnapshotVersion):P_.min();let i;return i=void 0!==e.query.documents?(m_(1===(t=e.query).documents.length),Cb(bb(KI(t.documents[0])))):Cb(XI(e.query)),new MT(i,e.targetId,0,e.lastListenSequenceNumber,n,r,ww.fromBase64String(e.resumeToken))}function KT(e,t){var n=qT(t.snapshotVersion),r=qT(t.lastLimboFreeSnapshotVersion),i=(nb(t.target)?YI:JI)(e.re,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:eb(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function $T(e){var t=XI({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Ab(t,t.limit,"L"):t}function WT(e,t){return new OT(t.largestBatchId,QI(e.re,t.overlayMutation))}function zT(e,t){var n=t.path.lastSegment();return[e,iT(t.path.popLast()),n]}function GT(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:qT(r.readTime),documentKey:iT(r.documentKey.path),largestBatchId:r.largestBatchId}}class HT{getBundleMetadata(e,t){return QT(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:VT(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return QT(e).put({bundleId:(n=t).id,createTime:qT(FI(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return YT(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:$T(t.bundledQuery),readTime:VT(t.readTime)};var t})}saveNamedQuery(e,t){return YT(e).put({name:(t=t).name,readTime:qT(FI(t.readTime)),bundledQuery:t.bundledQuery})}}function QT(e){return xT(e,"bundles")}function YT(e){return xT(e,"namedQueries")}class JT{constructor(e,t){this.It=e,this.userId=t}static oe(e,t){var n=t.uid||"";return new JT(e,n)}getOverlay(e,t){return XT(e).get(zT(this.userId,t)).next(e=>e?WT(this.It,e):null)}getOverlays(e,t){const n=yI();return J_.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new OT(i,t);s.push(this.ue(r,n))}),J_.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(iT(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(XT(n).Y("collectionPathOverlayIndex",t))}),J_.waitFor(i)}getOverlaysForCollection(e,t,n){const r=yI(),i=iT(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return XT(e).W("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=WT(this.It,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=yI();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return XT(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=WT(this.It,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}ue(e,t){return XT(e).put(function(e,t,n){var[,r,i]=zT(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:HI(e.re,n.mutation)}}(this.It,this.userId,t))}}function XT(e){return xT(e,"documentOverlays")}class ZT{constructor(){}ce(e,t){this.ae(e,t),t.he()}ae(e,t){var n,r;"nullValue"in e?this.le(t,5):"booleanValue"in e?(this.le(t,10),t.fe(e.booleanValue?1:0)):"integerValue"in e?(this.le(t,15),t.fe(Tw(e.integerValue))):"doubleValue"in e?(n=Tw(e.doubleValue),isNaN(n)?this.le(t,13):(this.le(t,15),Rw(n)?t.fe(0):t.fe(n))):"timestampValue"in e?(r=e.timestampValue,this.le(t,20),"string"==typeof r?t.de(r):(t.de(`${r.seconds||""}`),t.fe(r.nanos||0))):"stringValue"in e?(this._e(e.stringValue,t),this.we(t)):"bytesValue"in e?(this.le(t,30),t.me(Ew(e.bytesValue)),this.we(t)):"referenceValue"in e?this.ge(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.le(t,45),t.fe(r.latitude||0),t.fe(r.longitude||0)):"mapValue"in e?Gw(e)?this.le(t,Number.MAX_SAFE_INTEGER):(this.ye(e.mapValue,t),this.we(t)):"arrayValue"in e?(this.pe(e.arrayValue,t),this.we(t)):g_()}_e(e,t){this.le(t,25),this.Ie(e,t)}Ie(e,t){t.de(e)}ye(e,t){var n=e.fields||{};this.le(t,55);for(const e of Object.keys(n))this._e(e,t),this.ae(n[e],t)}pe(e,t){var n=e.values||[];this.le(t,50);for(const e of n)this.ae(e,t)}ge(e,t){this.le(t,37),U_.fromName(e).path.forEach(e=>{this.le(t,60),this.Ie(e,t)})}le(e,t){e.fe(t)}we(e){e.fe(2)}}function e0(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}ZT.Te=new ZT;class t0{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ee(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ae(n.value),n=t.next();this.Re()}be(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Pe(n.value),n=t.next();this.ve()}Ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ae(e);else if(e<2048)this.Ae(960|e>>>6),this.Ae(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ae(480|e>>>12),this.Ae(128|63&e>>>6),this.Ae(128|63&e);else{const e=t.codePointAt(0);this.Ae(240|e>>>18),this.Ae(128|63&e>>>12),this.Ae(128|63&e>>>6),this.Ae(128|63&e)}}this.Re()}Se(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Pe(e);else if(e<2048)this.Pe(960|e>>>6),this.Pe(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Pe(480|e>>>12),this.Pe(128|63&e>>>6),this.Pe(128|63&e);else{const e=t.codePointAt(0);this.Pe(240|e>>>18),this.Pe(128|63&e>>>12),this.Pe(128|63&e>>>6),this.Pe(128|63&e)}}this.ve()}De(e){var t=this.Ce(e),n=e0(t);this.xe(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Ne(e){var t=this.Ce(e),n=e0(t);this.xe(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}ke(){this.Oe(255),this.Oe(255)}Me(){this.Fe(255),this.Fe(255)}reset(){this.position=0}seed(e){this.xe(e.length),this.buffer.set(e,this.position),this.position+=e.length}$e(){return this.buffer.slice(0,this.position)}Ce(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ae(e){var t=255&e;0==t?(this.Oe(0),this.Oe(255)):255==t?(this.Oe(255),this.Oe(0)):this.Oe(t)}Pe(e){var t=255&e;0==t?(this.Fe(0),this.Fe(255)):255==t?(this.Fe(255),this.Fe(0)):this.Fe(e)}Re(){this.Oe(0),this.Oe(1)}ve(){this.Fe(0),this.Fe(1)}Oe(e){this.xe(1),this.buffer[this.position++]=e}Fe(e){this.xe(1),this.buffer[this.position++]=~e}xe(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class n0{constructor(e){this.Be=e}me(e){this.Be.Ee(e)}de(e){this.Be.Ve(e)}fe(e){this.Be.De(e)}he(){this.Be.ke()}}class r0{constructor(e){this.Be=e}me(e){this.Be.be(e)}de(e){this.Be.Se(e)}fe(e){this.Be.Ne(e)}he(){this.Be.Me()}}class i0{constructor(){this.Be=new t0,this.Le=new n0(this.Be),this.Ue=new r0(this.Be)}seed(e){this.Be.seed(e)}qe(e){return 0===e?this.Le:this.Ue}$e(){return this.Be.$e()}reset(){this.Be.reset()}}class s0{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Ke(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new s0(this.indexId,this.documentKey,this.arrayValue,n)}}function a0(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=o0(e.arrayValue,t.arrayValue),0!==n?n:(n=o0(e.directionalValue,t.directionalValue),0!==n?n:U_.comparator(e.documentKey,t.documentKey)))}function o0(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class c0{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ge=e.orderBy,this.Qe=[];for(const t of e.filters){const e=t;e.dt()?this.je=e:this.Qe.push(e)}}We(e){var t=V_(e);if(void 0!==t&&!this.ze(t))return!1;var n=B_(e);let r=0,i=0;for(;r<n.length&&this.ze(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.je){const e=n[r];if(!this.He(this.je,e)||!this.Je(this.Ge[i++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(i>=this.Ge.length||!this.Je(this.Ge[i++],e))return!1}return!0}ze(e){for(const t of this.Qe)if(this.He(t,e))return!0;return!1}He(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}Je(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}class l0{constructor(){this.Ye=new u0}addToCollectionParentIndex(e,t){return this.Ye.add(t),J_.resolve()}getCollectionParents(e,t){return J_.resolve(this.Ye.getEntries(t))}addFieldIndex(e,t){return J_.resolve()}deleteFieldIndex(e,t){return J_.resolve()}getDocumentsMatchingTarget(e,t){return J_.resolve(null)}getIndexType(e,t){return J_.resolve(0)}getFieldIndexes(e,t){return J_.resolve([])}getNextCollectionGroupToUpdate(e){return J_.resolve(null)}getMinOffset(e,t){return J_.resolve(z_.min())}getMinOffsetFromCollectionGroup(e,t){return J_.resolve(z_.min())}updateCollectionGroup(e,t,n){return J_.resolve()}updateIndexEntries(e,t){return J_.resolve()}}class u0{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new mw(M_.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new mw(M_.comparator)).toArray()}}const h0=new Uint8Array(0);class d0{constructor(e,t){this.user=e,this.databaseId=t,this.Xe=new u0,this.Ze=new pI(e=>eb(e),(e,t)=>tb(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Xe.has(t))return J_.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Xe.add(t)});r={collectionId:n,parent:iT(r)};return p0(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[x_(n),""],!1,!0);return p0(e).W(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(aT(t.parent))}return r})}addFieldIndex(e,t){const n=g0(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=m0(e);return i.next(e=>{n.put(GT(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=g0(e),r=m0(e),i=f0(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,l){const u=f0(e);let h=!0;const n=new Map;return J_.forEach(this.tn(l),t=>this.en(e,t).next(e=>{h=h&&!!e,n.set(t,e)})).next(()=>{if(h){let c=bI();const h=[];return J_.forEach(n,(e,t)=>{h_("IndexedDbIndexManager",`Using index ${o=e,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${eb(l)}`);var n=function(e,t){var n=V_(t);if(void 0===n)return null;for(const t of rb(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of B_(t))for(const t of rb(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),i=function(e,t){const n=[];let r=!0;for(const i of B_(t)){const t=(0===i.kind?ib:sb)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new gb(n,r)}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of B_(t)){const t=(0===i.kind?sb:ib)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new gb(n,r)}(t,e),a=this.nn(e,t,i),o=this.nn(e,t,s),r=this.sn(e,t,r),r=this.rn(e.indexId,n,a,i.inclusive,o,s.inclusive,r);return J_.forEach(r,e=>u.J(e,l.limit).next(e=>{e.forEach(e=>{var t=U_.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),h.push(t))})}))}).next(()=>h)}return J_.resolve(null)})}tn(e){var t;return(t=this.Ze.get(e))||(this.Ze.set(e,t=[e]),t)}rn(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),c=o/(null!=e?e.length:1),l=[];for(let u=0;u<o;++u){const o=e?this.on(e[u/c]):h0,h=this.un(t,o,n[u%c],r),d=this.cn(t,o,i[u%c],s),p=a.map(e=>this.un(t,o,e,!0));l.push(...this.createRange(h,d,p))}return l}un(e,t,n,r){const i=new s0(e,U_.empty(),t,n);return r?i:i.Ke()}cn(e,t,n,r){const i=new s0(e,U_.empty(),t,n);return r?i.Ke():i}en(e,t){const r=new c0(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.We(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;return J_.forEach(this.tn(t),t=>this.en(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new mw(F_.comparator),n=!1;for(const r of e.filters){const e=r;e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field))}for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>n)}an(e,t){const n=new i0;for(const i of B_(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.qe(i.kind);ZT.Te.ce(e,r)}return n.$e()}on(e){const t=new i0;return ZT.Te.ce(e,t.qe(0)),t.$e()}hn(e,t){const n=new i0;return ZT.Te.ce(Vw(this.databaseId,t),n.qe(0===(r=B_(e)).length?0:r[r.length-1].kind)),n.$e();var r}sn(e,t,n){if(null===n)return[];let r=[];r.push(new i0);let i=0;for(const s of B_(e)){const e=n[i++];for(const n of r)if(this.ln(t,s.fieldPath)&&jw(e))r=this.fn(r,s,e);else{const t=n.qe(s.kind);ZT.Te.ce(e,t)}}return this.dn(r)}nn(e,t,n){return this.sn(e,t,n.position)}dn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].$e();return t}fn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new i0;r.seed(n.$e()),ZT.Te.ce(e,r.qe(t.kind)),i.push(r)}return i}ln(e,t){return!!e.filters.find(e=>e instanceof ab&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=g0(e),r=m0(e);return(t?n.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.W()).next(e=>{const s=[];return J_.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new K_(e.sequenceNumber,new z_(VT(e.readTime),new U_(aT(e.documentKey)),e.largestBatchId)):K_.empty(),r=t.fields.map(([e,t])=>new j_(F_.fromServerFormat(e),t)),new q_(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:N_(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=g0(e),s=m0(e);return this._n(e).next(t=>i.W("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>J_.forEach(e,e=>s.put(GT(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return J_.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?J_.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),J_.forEach(e,n=>this.wn(i,t,n).next(e=>{var t=this.mn(r,n);return e.isEqual(t)?J_.resolve():this.gn(i,r,n,e,t)}))))})}yn(e,t,n,r){return f0(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.hn(n,t.key),documentKey:t.key.path.toArray()})}pn(e,t,n,r){return f0(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.hn(n,t.key),t.key.path.toArray()])}wn(e,n,r){const t=f0(e);let i=new mw(a0);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.hn(r,n)])},(e,t)=>{i=i.add(new s0(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}mn(e,t){let n=new mw(a0);var r=this.an(t,e);if(null==r)return n;const i=V_(t);if(null!=i){var s=e.data.field(i.fieldPath);if(jw(s))for(const i of s.arrayValue.values||[])n=n.add(new s0(t.indexId,e.key,this.on(i),r))}else n=n.add(new s0(t.indexId,e.key,h0,r));return n}gn(t,n,r,l,e){h_("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const i=[];return function(e,n,r,i){var s=l.getIterator(),a=e.getIterator();let o=yw(s),c=yw(a);for(;o||c;){let e=!1,t=!1;if(o&&c){const r=n(o,c);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(c),c=yw(a)):t?(i(o),o=yw(s)):(o=yw(s),c=yw(a))}}(e,a0,e=>{i.push(this.yn(t,n,r,e))},e=>{i.push(this.pn(t,n,r,e))}),J_.waitFor(i)}_n(e){let r=1;return m0(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>a0(e,t)).filter((e,t,n)=>!t||0!==a0(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=a0(i,e),s=a0(i,t);if(0===n)r[0]=e.Ke();else if(0<n&&s<0)r.push(i),r.push(i.Ke());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2)i.push(IDBKeyRange.bound([r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,h0,[]],[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,h0,[]]));return i}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(v0)}getMinOffset(t,e){return J_.mapArray(this.tn(e),e=>this.en(t,e).next(e=>e||g_())).next(v0)}}function p0(e){return xT(e,"collectionParents")}function f0(e){return xT(e,"indexEntries")}function g0(e){return xT(e,"indexConfiguration")}function m0(e){return xT(e,"indexState")}function v0(e){m_(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;G_(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new z_(t.readTime,t.documentKey,n)}const y0={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class _0{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new _0(e,_0.DEFAULT_COLLECTION_PERCENTILE,_0.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function w0(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const c=r.Z({range:a},(e,t,n)=>(o++,n.delete()));s.push(c.next(()=>{m_(1===o)}));const l=[];for(const e of n.mutations){const r=lT(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return J_.waitFor(s).next(()=>l)}function b0(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 g_();t=e.noDocument}return JSON.stringify(t).length}_0.DEFAULT_COLLECTION_PERCENTILE=10,_0.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,_0.DEFAULT=new _0(41943040,_0.DEFAULT_COLLECTION_PERCENTILE,_0.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),_0.DISABLED=new _0(-1,0,0);class I0{constructor(e,t,n,r){this.userId=e,this.It=t,this.indexManager=n,this.referenceDelegate=r,this.In={}}static oe(e,t,n,r){m_(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new I0(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return E0(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,p){const f=k0(u),g=E0(u);return g.add({}).next(e=>{m_("number"==typeof e);const t=new DT(e,h,d,p),n=(i=this.It,s=this.userId,a=t,o=a.baseMutations.map(e=>HI(i.re,e)),c=a.mutations.map(e=>HI(i.re,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:c}),r=[];var i,s,a,o,c;let l=new mw((e,t)=>N_(e.canonicalString(),t.canonicalString()));for(const u of p){const h=lT(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(f.put(h,uT))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.In[e]=t.keys()}),J_.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return E0(e).get(t).next(e=>e?(m_(e.userId===this.userId),BT(this.It,e)):null)}Tn(e,n){return this.In[n]?J_.resolve(this.In[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.In[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return E0(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(m_(t.batchId>=r),i=BT(this.It,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return E0(e).Z({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return E0(e).W("userMutationsIndex",t).next(e=>e.map(e=>BT(this.It,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=cT(this.userId,o.path),t=IDBKeyRange.lowerBound(e),c=[];return k0(a).Z({range:t},(e,t,n)=>{var[r,i,s]=e,i=aT(i);if(r===this.userId&&o.path.isEqual(i))return E0(a).get(s).next(e=>{if(!e)throw g_();m_(e.userId===this.userId),c.push(BT(this.It,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new mw(N_);const n=[];return e.forEach(a=>{var e=cT(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=k0(t).Z({range:e},(e,t,n)=>{var[r,i,s]=e,i=aT(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),J_.waitFor(n).next(()=>this.En(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=cT(this.userId,a),r=IDBKeyRange.lowerBound(n);let c=new mw(N_);return k0(e).Z({range:r},(e,t,n)=>{var[r,i,s]=e,i=aT(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(c=c.add(s)):n.done()}).next(()=>this.En(e,c))}En(t,e){const n=[],r=[];return e.forEach(e=>{r.push(E0(t).get(e).next(e=>{if(null===e)throw g_();m_(e.userId===this.userId),n.push(BT(this.It,e))}))}),J_.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return w0(t.ie,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.An(n.batchId)}),J_.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}An(e){delete this.In[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return J_.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return k0(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=aT(e[1]);r.push(t)}else n.done()}).next(()=>{m_(0===r.length)})})}containsKey(e,t){return T0(e,this.userId,t)}Rn(e){return S0(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function T0(e,s,t){const n=cT(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return k0(e).Z({range:r,X:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function E0(e){return xT(e,"mutations")}function k0(e){return xT(e,"documentMutations")}function S0(e){return xT(e,"mutationQueues")}class C0{constructor(e){this.bn=e}next(){return this.bn+=2,this.bn}static Pn(){return new C0(0)}static vn(){return new C0(-1)}}class A0{constructor(e,t){this.referenceDelegate=e,this.It=t}allocateTargetId(n){return this.Vn(n).next(e=>{const t=new C0(e.highestTargetId);return e.highestTargetId=t.next(),this.Sn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Vn(e).next(e=>P_.fromTimestamp(new D_(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Vn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Vn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.Sn(t,e)))}addTargetData(t,n){return this.Dn(t,n).next(()=>this.Vn(t).next(e=>(e.targetCount+=1,this.Cn(n,e),this.Sn(t,e))))}updateTargetData(e,t){return this.Dn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>N0(t).delete(e.targetId)).next(()=>this.Vn(t)).next(e=>(m_(0<e.targetCount),--e.targetCount,this.Sn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return N0(r).Z((e,t)=>{var n=jT(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>J_.waitFor(o)).next(()=>a)}forEachTarget(e,r){return N0(e).Z((e,t)=>{var n=jT(t);r(n)})}Vn(e){return R0(e).get("targetGlobalKey").next(e=>(m_(null!==e),e))}Sn(e,t){return R0(e).put("targetGlobalKey",t)}Dn(e,t){return N0(e).put(KT(this.It,t))}Cn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Vn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=eb(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return N0(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=jT(t);tb(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=x0(n);return e.forEach(e=>{var t=iT(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),J_.waitFor(i)}removeMatchingKeys(n,e,r){const i=x0(n);return J_.forEach(e,e=>{var t=iT(e.path);return J_.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=x0(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=x0(e);let i=bI();return r.Z({range:n,X:!0},(e,t,n)=>{var r=aT(e[1]),r=new U_(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=iT(t.path),n=IDBKeyRange.bound([n],[x_(n)],!1,!0);let r=0;return x0(e).Z({index:"documentTargetsIndex",X:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}se(e,t){return N0(e).get(t).next(e=>e?jT(e):null)}}function N0(e){return xT(e,"targets")}function R0(e){return xT(e,"targetGlobal")}function x0(e){return xT(e,"targetDocuments")}function D0([e,t],[n,r]){var i=N_(e,n);return 0===i?N_(t,r):i}class P0{constructor(e){this.xn=e,this.buffer=new mw(D0),this.Nn=0}kn(){return++this.Nn}On(e){var t=[e,this.kn()];if(this.buffer.size<this.xn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();D0(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class O0{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Mn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Fn(6e4)}stop(){this.Mn&&(this.Mn.cancel(),this.Mn=null)}get started(){return null!==this.Mn}Fn(e){h_("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Mn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Mn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){nw(e)?h_("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Y_(e)}await this.Fn(3e5)})}}class M0{constructor(e,t){this.$n=e,this.params=t}calculateTargetCount(e,t){return this.$n.Bn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return J_.resolve(lw.at);const n=new P0(t);return this.$n.forEachTarget(e,e=>n.On(e.sequenceNumber)).next(()=>this.$n.Ln(e,e=>n.On(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.$n.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.$n.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(h_("LruGarbageCollector","Garbage collection skipped; disabled"),J_.resolve(y0)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(h_("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),y0):this.Un(t,n))}getCacheSize(e){return this.$n.getCacheSize(e)}Un(t,n){let r,i,s,a,o,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(h_("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=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),u_()<=k.DEBUG&&h_("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-u}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(c-o)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),J_.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class L0{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new M0(e,t))}Bn(e){const n=this.qn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}qn(e){let t=0;return this.Ln(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Ln(e,n){return this.Kn(e,(e,t)=>n(t))}addReference(e,t,n){return F0(e,n)}removeReference(e,t,n){return F0(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return F0(e,t)}Gn(t,n){let r=!1;return S0(t).tt(e=>T0(t,e,n).next(e=>(e&&(r=!0),J_.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Kn(n,(t,e)=>{if(e<=r){const r=this.Gn(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,P_.min()),x0(n).delete([0,iT(t.path)])))});s.push(r)}}).next(()=>J_.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return F0(e,t)}Kn(e,r){const t=x0(e);let i,s=lw.at;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==lw.at&&r(new U_(aT(i)),s),s=n,i=t):s=lw.at}).next(()=>{s!==lw.at&&r(new U_(aT(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function F0(e,t){return x0(e).put((e=e.currentSequenceNumber,{targetId:0,path:iT(t.path),sequenceNumber:e}))}class U0{constructor(){this.changes=new pI(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,Jw.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?J_.resolve(n):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 q0{constructor(e){this.It=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return K0(e).put(n)}removeEntry(e,n,t){return K0(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],UT(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Qn(t,e)))}getEntry(e,n){let r=Jw.newInvalidDocument(n);return K0(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only($0(n))},(e,t)=>{r=this.jn(n,t)}).next(()=>r)}Wn(e,n){let r={size:0,document:Jw.newInvalidDocument(n)};return K0(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only($0(n))},(e,t)=>{r={document:this.jn(n,t),size:b0(t)}}).next(()=>r)}getEntries(e,t){let r=fI;return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n)}).next(()=>r)}Hn(e,t){let r=fI,i=new pw(U_.comparator);return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n),i=i.insert(e,b0(t))}).next(()=>({documents:r,Jn:i}))}zn(e,t,i){if(t.isEmpty())return J_.resolve();let n=new mw(z0);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound($0(n.first()),$0(n.last())),s=n.getIterator();let a=s.getNext();return K0(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=U_.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&z0(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.j($0(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),UT(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],i=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return K0(e).W(IDBKeyRange.bound(r,i,!0)).next(e=>{let t=fI;for(const n of e){const e=this.jn(U_.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,i){let s=fI;var r=W0(t,n),a=W0(t,z_.max());return K0(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.jn(U_.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new B0(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return j0(e).get("remoteDocumentGlobalKey").next(e=>(m_(!!e),e))}Qn(e,t){return j0(e).put("remoteDocumentGlobalKey",t)}jn(e,t){if(t){const e=function(e,t){let n;if(t.document)n=GI(e.re,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=U_.fromSegments(t.noDocument.path),i=VT(t.noDocument.readTime);n=Jw.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return g_();{const e=U_.fromSegments(t.unknownDocument.path),s=VT(t.unknownDocument.version);n=Jw.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new D_(t[0],t[1]),P_.fromTimestamp(r))),n;var r}(this.It,t);if(!e.isNoDocument()||!e.version.isEqual(P_.min()))return e}return Jw.newInvalidDocument(e)}}function V0(e){return new q0(e)}class B0 extends U0{constructor(e,t){super(),this.Yn=e,this.trackRemovals=t,this.Xn=new pI(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,c=new mw((e,t)=>N_(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Xn.get(e);if(a.push(this.Yn.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=FT(this.Yn.It,t);c=c.add(e.path.popLast());var i=b0(r);o+=i-n.size,a.push(this.Yn.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=FT(this.Yn.It,t.convertToNoDocument(P_.min()));a.push(this.Yn.addEntry(s,e,o))}}),c.forEach(e=>{a.push(this.Yn.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.Yn.updateMetadata(s,o)),J_.waitFor(a)}getFromCache(e,t){return this.Yn.Wn(e,t).next(e=>(this.Xn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Yn.Hn(e,t).next(({documents:n,Jn:e})=>(e.forEach((e,t)=>{this.Xn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function j0(e){return xT(e,"remoteDocumentGlobal")}function K0(e){return xT(e,"remoteDocumentsV14")}function $0(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function W0(e,t){const n=t.documentKey.path.toArray();return[e,UT(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function z0(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=N_(n[s],r[s]),i)return i;return i=N_(n.length,r.length),i||(i=N_(n[n.length-2],r[r.length-2]),i||N_(n[n.length-1],r[r.length-1]))}class G0{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class H0{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.getBaseDocument(t,n,r))).next(e=>(null!==r&&tI(r.mutation,e,_w.empty(),D_.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,bI()).next(()=>e))}getLocalViewOfDocuments(e,t,n=bI()){const r=yI();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=mI();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=yI();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,bI()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=fI;const a=yI(),o=yI();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof iI)?s=s.insert(t.key,t):void 0!==n&&(a.set(t.key,n.mutation.getFieldMask()),tI(n.mutation,t,n.mutation.getFieldMask(),D_.now()))}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new G0(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=yI();let c=new pw((e,t)=>e-t),l=bI();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||_w.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(c.get(r.batchId)||bI()).add(e),c=c.insert(r.batchId,t))})}).next(()=>{const e=[],t=c.getReverseIterator();for(;t.hasNext();){const c=t.getNext(),n=c.key,r=c.value,i=yI();r.forEach(e=>{var t;l.has(e)||(null!==(t=Zb(a.get(e),o.get(e)))&&i.set(e,t),l=l.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return J_.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,U_.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):kb(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):J_.resolve(yI());let r=-1,i=n;return e.next(e=>J_.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?J_.resolve():this.getBaseDocument(s,t,e).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,bI())).next(e=>({batchId:r,changes:vI(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new U_(t)).next(e=>{let t=mI();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s){const a=i.collectionGroup;let o=mI();return this.indexManager.getCollectionParents(r,a).next(e=>J_.forEach(e,e=>{var t,n=(t=i,e=e.child(a),new _b(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(t,s,n){let a;return this.remoteDocumentCache.getAllFromCollection(t,s.path,n).next(e=>(a=e,this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId))).next(r=>{r.forEach((e,t)=>{var n=t.getKey();null===a.get(n)&&(a=a.insert(n,Jw.newInvalidDocument(n)))});let i=mI();return a.forEach((e,t)=>{var n=r.get(e);void 0!==n&&tI(n.mutation,t,_w.empty(),D_.now()),Db(s,t)&&(i=i.insert(e,t))}),i})}getBaseDocument(e,t,n){return null===n||1===n.mutation.type?this.remoteDocumentCache.getEntry(e,t):J_.resolve(Jw.newInvalidDocument(t))}}class Q0{constructor(e){this.It=e,this.Zn=new Map,this.ts=new Map}getBundleMetadata(e,t){return J_.resolve(this.Zn.get(t))}saveBundleMetadata(e,t){return this.Zn.set(t.id,{id:t.id,version:t.version,createTime:FI(t.createTime)}),J_.resolve()}getNamedQuery(e,t){return J_.resolve(this.ts.get(t))}saveNamedQuery(e,t){return this.ts.set(t.name,{name:(t=t).name,query:$T(t.bundledQuery),readTime:FI(t.readTime)}),J_.resolve()}}class Y0{constructor(){this.overlays=new pw(U_.comparator),this.es=new Map}getOverlay(e,t){return J_.resolve(this.overlays.get(t))}getOverlays(e,t){const n=yI();return J_.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.ue(n,r,t)}),J_.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.es.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.es.delete(n)),J_.resolve()}getOverlaysForCollection(e,t,n){const r=yI(),i=t.length+1,s=new U_(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return J_.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new pw((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=yI(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=yI(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return J_.resolve(a)}ue(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.es.get(r.largestBatchId).delete(n.key);this.es.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new OT(t,n));let i=this.es.get(t);void 0===i&&(i=bI(),this.es.set(t,i)),this.es.set(t,i.add(n.key))}}class J0{constructor(){this.ns=new mw(X0.ss),this.rs=new mw(X0.os)}isEmpty(){return this.ns.isEmpty()}addReference(e,t){var n=new X0(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}us(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.cs(new X0(e,t))}hs(e,t){e.forEach(e=>this.removeReference(e,t))}ls(e){const t=new U_(new M_([])),n=new X0(t,e),r=new X0(t,e+1),i=[];return this.rs.forEachInRange([n,r],e=>{this.cs(e),i.push(e.key)}),i}fs(){this.ns.forEach(e=>this.cs(e))}cs(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}ds(e){var t=new U_(new M_([])),n=new X0(t,e),t=new X0(t,e+1);let r=bI();return this.rs.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new X0(e,0),t=this.ns.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class X0{constructor(e,t){this.key=e,this._s=t}static ss(e,t){return U_.comparator(e.key,t.key)||N_(e._s,t._s)}static os(e,t){return N_(e._s,t._s)||U_.comparator(e.key,t.key)}}class Z0{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.ws=1,this.gs=new mw(X0.ss)}checkEmpty(e){return J_.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.ws;this.ws++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new DT(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.gs=this.gs.add(new X0(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return J_.resolve(s)}lookupMutationBatch(e,t){return J_.resolve(this.ys(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.ps(t+1),n=n<0?0:n;return J_.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return J_.resolve(0===this.mutationQueue.length?-1:this.ws-1)}getAllMutationBatches(e){return J_.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new X0(t,0),r=new X0(t,Number.POSITIVE_INFINITY),i=[];return this.gs.forEachInRange([n,r],e=>{var t=this.ys(e._s);i.push(t)}),J_.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new mw(N_);return t.forEach(e=>{var t=new X0(e,0),n=new X0(e,Number.POSITIVE_INFINITY);this.gs.forEachInRange([t,n],e=>{r=r.add(e._s)})}),J_.resolve(this.Is(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;U_.isDocumentKey(i)||(i=i.child(""));var s=new X0(new U_(i),0);let a=new mw(N_);return this.gs.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e._s)),!0)},s),J_.resolve(this.Is(a))}Is(e){const n=[];return e.forEach(e=>{var t=this.ys(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){m_(0===this.Ts(r.batchId,"removed")),this.mutationQueue.shift();let i=this.gs;return J_.forEach(r.mutations,e=>{var t=new X0(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.gs=i})}An(e){}containsKey(e,t){var n=new X0(t,0),n=this.gs.firstAfterOrEqual(n);return J_.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,J_.resolve()}Ts(e,t){return this.ps(e)}ps(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ys(e){var t=this.ps(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class eE{constructor(e){this.Es=e,this.docs=new pw(U_.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Es(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return J_.resolve(n?n.document.mutableCopy():Jw.newInvalidDocument(t))}getEntries(e,t){let n=fI;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Jw.newInvalidDocument(e))}),J_.resolve(n)}getAllFromCollection(e,t,n){let r=fI;const i=new U_(t.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i}}=s.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||G_(W_(i),n)<=0||(r=r.insert(i.key,i.mutableCopy()))}return J_.resolve(r)}getAllFromCollectionGroup(e,t,n,r){g_()}As(e,t){return J_.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new tE(this)}getSize(e){return J_.resolve(this.size)}}class tE extends U0{constructor(e){super(),this.Yn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Yn.addEntry(n,t)):this.Yn.removeEntry(e)}),J_.waitFor(r)}getFromCache(e,t){return this.Yn.getEntry(e,t)}getAllFromCache(e,t){return this.Yn.getEntries(e,t)}}class nE{constructor(e){this.persistence=e,this.Rs=new pI(e=>eb(e),tb),this.lastRemoteSnapshotVersion=P_.min(),this.highestTargetId=0,this.bs=0,this.Ps=new J0,this.targetCount=0,this.vs=C0.Pn()}forEachTarget(e,n){return this.Rs.forEach((e,t)=>n(t)),J_.resolve()}getLastRemoteSnapshotVersion(e){return J_.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return J_.resolve(this.bs)}allocateTargetId(e){return this.highestTargetId=this.vs.next(),J_.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),J_.resolve()}Dn(e){this.Rs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.vs=new C0(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}addTargetData(e,t){return this.Dn(t),this.targetCount+=1,J_.resolve()}updateTargetData(e,t){return this.Dn(t),J_.resolve()}removeTargetData(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),--this.targetCount,J_.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Rs.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Rs.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),J_.waitFor(a).next(()=>s)}getTargetCount(e){return J_.resolve(this.targetCount)}getTargetData(e,t){var n=this.Rs.get(t)||null;return J_.resolve(n)}addMatchingKeys(e,t,n){return this.Ps.us(t,n),J_.resolve()}removeMatchingKeys(t,e,n){this.Ps.hs(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),J_.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Ps.ls(t),J_.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Ps.ds(t);return J_.resolve(n)}containsKey(e,t){return J_.resolve(this.Ps.containsKey(t))}}class rE{constructor(e,t){this.Vs={},this.overlays={},this.Ss=new lw(0),this.Ds=!1,this.Ds=!0,this.referenceDelegate=e(this),this.Cs=new nE(this),this.indexManager=new l0,this.remoteDocumentCache=(e=e=>this.referenceDelegate.xs(e),new eE(e)),this.It=new LT(t),this.Ns=new Q0(this.It)}start(){return Promise.resolve()}shutdown(){return this.Ds=!1,Promise.resolve()}get started(){return this.Ds}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Y0,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Vs[e.toKey()];return n||(n=new Z0(t,this.referenceDelegate),this.Vs[e.toKey()]=n),n}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ns}runTransaction(e,t,n){h_("MemoryPersistence","Starting transaction:",e);const r=new iE(this.Ss.next());return this.referenceDelegate.ks(),n(r).next(e=>this.referenceDelegate.Os(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ms(t,n){return J_.or(Object.values(this.Vs).map(e=>()=>e.containsKey(t,n)))}}class iE extends Q_{constructor(e){super(),this.currentSequenceNumber=e}}class sE{constructor(e){this.persistence=e,this.Fs=new J0,this.$s=null}static Bs(e){return new sE(e)}get Ls(){if(this.$s)return this.$s;throw g_()}addReference(e,t,n){return this.Fs.addReference(n,t),this.Ls.delete(n.toString()),J_.resolve()}removeReference(e,t,n){return this.Fs.removeReference(n,t),this.Ls.add(n.toString()),J_.resolve()}markPotentiallyOrphaned(e,t){return this.Ls.add(t.toString()),J_.resolve()}removeTarget(e,t){this.Fs.ls(t.targetId).forEach(e=>this.Ls.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Ls.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}ks(){this.$s=new Set}Os(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return J_.forEach(this.Ls,e=>{const t=U_.fromPath(e);return this.Us(n,t).next(e=>{e||r.removeEntry(t,P_.min())})}).next(()=>(this.$s=null,r.apply(n)))}updateLimboDocument(e,t){return this.Us(e,t).next(e=>{e?this.Ls.delete(t.toString()):this.Ls.add(t.toString())})}xs(e){return 0}Us(e,t){return J_.or([()=>J_.resolve(this.Fs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ms(e,t)])}}class aE{constructor(e){this.It=e}$(t,e,n,r){const i=new X_("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",oT,{unique:!0}),s.createObjectStore("documentMutations"),oE(t),t.createObjectStore("remoteDocuments"));let a=J_.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),oE(t)),a=a.next(()=>function(){const e=i.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:P_.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").W().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",oT,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return J_.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.qs(i))),n<6&&6<=r&&(a=a.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.Ks(i)))),n<7&&7<=r&&(a=a.next(()=>this.Gs(i))),n<8&&8<=r&&(a=a.next(()=>this.Qs(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.js(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:IT});e.createIndex("collectionPathOverlayIndex",TT,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",ET,{unique:!1})}()})),n<13&&13<=r&&(a=a.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:hT});e.createIndex("documentKeyIndex",dT),e.createIndex("collectionGroupIndex",pT)}()).next(()=>this.Ws(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.zs(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:yT}).createIndex("sequenceNumberIndex",_T,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:wT}).createIndex("documentKeyIndex",bT,{unique:!1})}(t))),a}Ks(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=b0(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}qs(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.W().next(e=>J_.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.W("userMutationsIndex",e).next(e=>J_.forEach(e,e=>{m_(e.userId===n.userId);var t=BT(this.It,e);return w0(r,n.userId,t).next(()=>{})}))}))}Gs(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Z((e,t)=>{const n=new M_(e),r=[0,iT(n)];s.push(a.get(r).next(e=>e?J_.resolve():(e=>a.put({targetId:0,path:iT(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>J_.waitFor(s))})}Qs(e,t){e.createObjectStore("collectionParents",{keyPath:vT});const n=t.store("collectionParents"),r=new u0,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:iT(r)})}};return t.store("remoteDocuments").Z({X:!0},(e,t)=>{const n=new M_(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Z({X:!0},([,e],t)=>{const n=aT(e);return i(n.popLast())}))}js(e){const r=e.store("targets");return r.Z((e,t)=>{var n=jT(t),n=KT(this.It,n);return r.put(n)})}Ws(e,s){const t=s.store("remoteDocuments"),a=[];return t.Z((e,t)=>{const n=s.store("remoteDocumentsV14"),r=((i=t).document?new U_(M_.fromString(i.document.name).popFirst(5)):i.noDocument?U_.fromSegments(i.noDocument.path):i.unknownDocument?U_.fromSegments(i.unknownDocument.path):g_()).path.toArray();var i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.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(()=>J_.waitFor(a))}zs(e,s){const t=s.store("mutations"),a=V0(this.It),o=new rE(sE.Bs,this.It.re);return t.W().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:bI();BT(this.It,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),J_.forEach(r,(e,t)=>{var n=new o_(t),r=JT.oe(this.It,n),i=o.getIndexManager(n),n=I0.oe(n,this.It,i,o.referenceDelegate);return new H0(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new RT(s,lw.at),e).next()})})}}function oE(e){e.createObjectStore("targetDocuments",{keyPath:gT}).createIndex("documentTargetsIndex",mT,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",fT,{unique:!0}),e.createObjectStore("targetGlobal")}const cE="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 lE{constructor(e,t,n,r,i,s,a,o,c,l,u=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Hs=i,this.window=s,this.document=a,this.Js=c,this.Ys=l,this.Xs=u,this.Ss=null,this.Ds=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Zs=null,this.inForeground=!1,this.ti=null,this.ei=null,this.ni=Number.NEGATIVE_INFINITY,this.si=e=>Promise.resolve(),!lE.C())throw new y_(v_.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new L0(this,r),this.ii=t+"main",this.It=new LT(o),this.ri=new Z_(this.ii,this.Xs,new aE(this.It)),this.Cs=new A0(this.referenceDelegate,this.It),this.remoteDocumentCache=V0(this.It),this.Ns=new HT,this.window&&this.window.localStorage?this.oi=this.window.localStorage:(this.oi=null,!1===l&&d_("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.ui().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new y_(v_.FAILED_PRECONDITION,cE);return this.ci(),this.ai(),this.hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Cs.getHighestSequenceNumber(e))}).then(e=>{this.Ss=new lw(e,this.Js)}).then(()=>{this.Ds=!0}).catch(e=>(this.ri&&this.ri.close(),Promise.reject(e)))}li(t){return this.si=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ri.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Hs.enqueueAndForget(async()=>{this.started&&await this.ui()}))}ui(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>hE(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.Hs.enqueueRetryable(()=>this.si(!1)))})}).next(()=>this.di(t)).next(e=>this.isPrimary&&!e?this._i(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(nw(e))return h_("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return h_("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Hs.enqueueRetryable(()=>this.si(e)),this.isPrimary=e})}fi(e){return uE(e).get("owner").next(e=>J_.resolve(this.mi(e)))}gi(e){return hE(e).delete(this.clientId)}async yi(){if(this.isPrimary&&!this.pi(this.ni,18e5)){this.ni=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=xT(e,"clientMetadata");return r.W().next(e=>{const t=this.Ii(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return J_.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.oi)for(const t of e)this.oi.removeItem(this.Ti(t.clientId))}}hi(){this.ei=this.Hs.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.ui().then(()=>this.yi()).then(()=>this.hi()))}mi(e){return!!e&&e.ownerId===this.clientId}di(t){return this.Ys?J_.resolve(!0):uE(t).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)){if(this.mi(e)&&this.networkEnabled)return!0;if(!this.mi(e)){if(!e.allowTabSynchronization)throw new y_(v_.FAILED_PRECONDITION,cE);return!1}}return!(!this.networkEnabled||!this.inForeground)||hE(t).W().next(e=>void 0===this.Ii(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&h_("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Ds=!1,this.Ai(),this.ei&&(this.ei.cancel(),this.ei=null),this.Ri(),this.bi(),await this.ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new RT(e,lw.at);return this._i(t).next(()=>this.gi(t))}),this.ri.close(),this.Pi()}Ii(e,t){return e.filter(e=>this.pi(e.updateTimeMs,t)&&!this.Ei(e.clientId))}vi(){return this.runTransaction("getActiveClients","readonly",e=>hE(e).W().next(e=>this.Ii(e,18e5).map(e=>e.clientId)))}get started(){return this.Ds}getMutationQueue(e,t){return I0.oe(e,this.It,t,this.referenceDelegate)}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new d0(e,this.It.re.databaseId)}getDocumentOverlayCache(e){return JT.oe(this.It,e)}getBundleCache(){return this.Ns}runTransaction(t,n,r){h_("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",e=15===(e=this.Xs)?NT:14===e?AT:13===e?CT:12===e?ST:11===e?kT:void g_();let s;return this.ri.runTransaction(t,i,e,e=>(s=new RT(e,this.Ss?this.Ss.next():lw.at),"readwrite-primary"===n?this.fi(s).next(e=>!!e||this.di(s)).next(e=>{if(!e)throw d_(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Hs.enqueueRetryable(()=>this.si(!1)),new y_(v_.FAILED_PRECONDITION,H_);return r(s)}).next(e=>this.wi(s).next(()=>e)):this.Vi(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}Vi(e){return uE(e).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)&&!this.mi(e)&&!(this.Ys||this.allowTabSynchronization&&e.allowTabSynchronization))throw new y_(v_.FAILED_PRECONDITION,cE)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return uE(e).put("owner",t)}static C(){return Z_.C()}_i(e){const t=uE(e);return t.get("owner").next(e=>this.mi(e)?(h_("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):J_.resolve())}pi(e,t){var n=Date.now();return!(e<n-t||n<e&&(d_(`Detected an update time that is in the future: ${e} > ${n}`),1))}ci(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ti=()=>{this.Hs.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.ui()))},this.document.addEventListener("visibilitychange",this.ti),this.inForeground="visible"===this.document.visibilityState)}Ri(){this.ti&&(this.document.removeEventListener("visibilitychange",this.ti),this.ti=null)}ai(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Zs=()=>{this.Ai(),!l()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match(/Version\/1[45]/)&&this.Hs.enterRestrictedMode(!0),this.Hs.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Zs))}bi(){this.Zs&&(this.window.removeEventListener("pagehide",this.Zs),this.Zs=null)}Ei(e){var t;try{var n=null!==(null===(t=this.oi)||void 0===t?void 0:t.getItem(this.Ti(e)));return h_("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return d_("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ai(){if(this.oi)try{this.oi.setItem(this.Ti(this.clientId),String(Date.now()))}catch(e){d_("Failed to set zombie client id.",e)}}Pi(){if(this.oi)try{this.oi.removeItem(this.Ti(this.clientId))}catch(e){}}Ti(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function uE(e){return xT(e,"owner")}function hE(e){return xT(e,"clientMetadata")}function dE(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class pE{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Si=n,this.Di=r}static Ci(e,t){let n=bI(),r=bI();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new pE(e,t.fromCache,n,r)}}class fE{constructor(){this.xi=!1}initialize(e,t){this.Ni=e,this.indexManager=t,this.xi=!0}getDocumentsMatchingQuery(t,n,r,i){return this.ki(t,n).next(e=>e||this.Oi(t,n,i,r)).next(e=>e||this.Mi(t,n))}ki(i,s){if(Ib(s))return J_.resolve(null);let t=Cb(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Ab(s,null,"F"),t=Cb(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=bI(...e);return this.Ni.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Fi(s,n);return this.$i(s,t,r,e.readTime)?this.ki(i,Ab(s,null,"F")):this.Bi(i,t,s,e)}))})))}Oi(n,r,i,s){return Ib(r)||s.isEqual(P_.min())?this.Mi(n,r):this.Ni.getDocuments(n,i).next(e=>{var t=this.Fi(r,e);return this.$i(r,t,i,s)?this.Mi(n,r):(u_()<=k.DEBUG&&h_("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),xb(r)),this.Bi(n,t,r,$_(s,-1)))})}Fi(n,e){let r=new mw(Ob(n));return e.forEach((e,t)=>{Db(n,t)&&(r=r.add(t))}),r}$i(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Mi(e,t){return u_()<=k.DEBUG&&h_("QueryEngine","Using full collection scan to execute query:",xb(t)),this.Ni.getDocumentsMatchingQuery(e,t,z_.min())}Bi(e,n,t,r){return this.Ni.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class gE{constructor(e,t,n,r){this.persistence=e,this.Li=t,this.It=r,this.Ui=new pw(N_),this.qi=new pI(e=>eb(e),tb),this.Ki=new Map,this.Gi=e.getRemoteDocumentCache(),this.Cs=e.getTargetCache(),this.Ns=e.getBundleCache(),this.Qi(n)}Qi(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new H0(this.Gi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Gi.setIndexManager(this.indexManager),this.Li.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Ui))}}function mE(e,t,n,r){return new gE(e,t,n,r)}async function vE(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a.Qi(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=bI();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({ji:e,removedBatchIds:t,addedBatchIds:n}))})})}function yE(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Cs.getLastRemoteSnapshotVersion(e))}function _E(e,l){const u=e,h=l.snapshotVersion;let d=u.Ui;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=u.Gi.newChangeBuffer({trackRemovals:!0});d=u.Ui;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.Cs.removeMatchingKeys(o,t.removedDocuments,n).next(()=>u.Cs.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;l.targetMismatches.has(n)?e=e.withResumeToken(ww.EMPTY_BYTE_STRING,P_.min()).withLastLimboFreeSnapshotVersion(P_.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||c.push(u.Cs.updateTargetData(o,e))}});let t=fI,n=bI();if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),c.push(wE(o,e,l.documentUpdates).next(e=>{t=e.Wi,n=e.zi})),!h.isEqual(P_.min())){const l=u.Cs.getLastRemoteSnapshotVersion(o).next(e=>u.Cs.setTargetsMetadata(o,o.currentSequenceNumber,h));c.push(l)}return J_.waitFor(c).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(u.Ui=d,e))}function wE(e,s,t){let n=bI(),a=bI();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=fI;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(P_.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):h_("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{Wi:i,zi:a}})}function bE(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Cs.getTargetData(t,r).next(e=>e?(n=e,J_.resolve(n)):i.Cs.allocateTargetId(t).next(e=>(n=new MT(r,e,0,t.currentSequenceNumber),i.Cs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Ui.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Ui=i.Ui.insert(e.targetId,e),i.qi.set(r,e.targetId)),e})}async function IE(e,t,n){const r=e,i=r.Ui.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!nw(e))throw e;h_("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Ui=r.Ui.remove(t),r.qi.delete(i.target)}function TE(e,n,r){const i=e;let s=P_.min(),a=bI();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.qi.get(n);return void 0!==i?J_.resolve(r.Ui.get(i)):r.Cs.getTargetData(t,n)}(i,t,Cb(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Cs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.Li.getDocumentsMatchingQuery(t,n,r?s:P_.min(),r?a:bI())).next(e=>(SE(i,Pb(n),e),{documents:e,Hi:a})))}function EE(e,t){const n=e,r=n.Cs,i=n.Ui.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.se(e,t).next(e=>e?e.target:null))}function kE(e,t){const n=e,r=n.Ki.get(t)||P_.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.Gi.getAllFromCollectionGroup(e,t,$_(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(SE(n,t,e),e))}function SE(e,t,n){let r=e.Ki.get(t)||P_.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.Ki.set(t,r)}function CE(e,t){return`firestore_clients_${e}_${t}`}function AE(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function NE(e,t){return`firestore_targets_${e}_${t}`}class RE{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Zi(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new y_(r.error.code,r.error.message))),s?new RE(e,t,r.state,i):(d_("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class xE{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Zi(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new y_(n.error.code,n.error.message))),i?new xE(e,n.state,r):(d_("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class DE{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Zi(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=II;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=xw(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new DE(e,i):(d_("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class PE{constructor(e,t){this.clientId=e,this.onlineState=t}static Zi(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new PE(t.clientId,t.onlineState):(d_("SharedClientState",`Failed to parse online state: ${e}`),null)}}class OE{constructor(){this.activeTargetIds=II}er(e){this.activeTargetIds=this.activeTargetIds.add(e)}nr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}tr(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class ME{constructor(e,t,n,r,i){this.window=e,this.Hs=t,this.persistenceKey=n,this.sr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ir=this.rr.bind(this),this.ur=new pw(N_),this.started=!1,this.cr=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.ar=CE(this.persistenceKey,this.sr),this.hr=`firestore_sequence_number_${this.persistenceKey}`,this.ur=this.ur.insert(this.sr,new OE),this.lr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.dr=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this._r=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.wr=`firestore_online_state_${this.persistenceKey}`,this.mr=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.ir)}static C(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.vi();for(const n of e)if(n!==this.sr){const e=this.getItem(CE(this.persistenceKey,n));var t;!e||(t=DE.Zi(n,e))&&(this.ur=this.ur.insert(t.clientId,t))}this.gr();const n=this.storage.getItem(this.wr);if(n){const e=this.yr(n);e&&this.pr(e)}for(const e of this.cr)this.rr(e);this.cr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.hr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ir(this.ur)}isActiveQueryTarget(n){let r=!1;return this.ur.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Tr(e,"pending")}updateMutationState(e,t,n){this.Tr(e,t,n),this.Er(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(NE(this.persistenceKey,e)))||(n=xE.Zi(e,n))&&(t=n.state)),this.Ar.er(e),this.gr(),t}removeLocalQueryTarget(e){this.Ar.nr(e),this.gr()}isLocalQueryTarget(e){return this.Ar.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(NE(this.persistenceKey,e))}updateQueryState(e,t,n){this.Rr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Er(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Pr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ir),this.removeItem(this.ar),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return h_("SharedClientState","READ",e,t),t}setItem(e,t){h_("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){h_("SharedClientState","REMOVE",e),this.storage.removeItem(e)}rr(e){const i=e;i.storageArea===this.storage&&(h_("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.ar?this.Hs.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.lr.test(i.key)){if(null==i.newValue){var e=this.vr(i.key);return this.Vr(e,null)}e=this.Sr(i.key,i.newValue);if(e)return this.Vr(e.clientId,e)}else if(this.dr.test(i.key)){if(null!==i.newValue){var t=this.Dr(i.key,i.newValue);if(t)return this.Cr(t)}}else if(this._r.test(i.key)){if(null!==i.newValue){t=this.Nr(i.key,i.newValue);if(t)return this.kr(t)}}else if(i.key===this.wr){if(null!==i.newValue){var n=this.yr(i.newValue);if(n)return this.pr(n)}}else if(i.key===this.hr){n=function(e){let t=lw.at;if(null!=e)try{var n=JSON.parse(e);m_("number"==typeof n),t=n}catch(e){d_("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==lw.at&&this.sequenceNumberHandler(n)}else if(i.key===this.mr){const r=this.Or(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Mr(e)))}}else this.cr.push(i)}):d_("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Ar(){return this.ur.get(this.sr)}gr(){this.setItem(this.ar,this.Ar.tr())}Tr(e,t,n){const r=new RE(this.currentUser,e,t,n),i=AE(this.persistenceKey,this.currentUser,e);this.setItem(i,r.tr())}Er(e){var t=AE(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){var t={clientId:this.sr,onlineState:e};this.storage.setItem(this.wr,JSON.stringify(t))}Rr(e,t,n){const r=NE(this.persistenceKey,e),i=new xE(e,t,n);this.setItem(r,i.tr())}Pr(e){var t=JSON.stringify(Array.from(e));this.setItem(this.mr,t)}vr(e){var t=this.lr.exec(e);return t?t[1]:null}Sr(e,t){var n=this.vr(e);return DE.Zi(n,t)}Dr(e,t){var n=this.dr.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return RE.Zi(new o_(n),r,t)}Nr(e,t){var n=this._r.exec(e),n=Number(n[1]);return xE.Zi(n,t)}yr(e){return PE.Zi(e)}Or(e){return JSON.parse(e)}async Cr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Fr(e.batchId,e.state,e.error);h_("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}kr(e){return this.syncEngine.$r(e.targetId,e.state,e.error)}Vr(e,t){const n=t?this.ur.insert(e,t):this.ur.remove(e),r=this.Ir(this.ur),i=this.Ir(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Br(s,a).then(()=>{this.ur=n})}pr(e){this.ur.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ir(e){let n=II;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class LE{constructor(){this.Lr=new OE,this.Ur={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Lr.er(e),this.Ur[e]||"not-current"}updateQueryState(e,t,n){this.Ur[e]=t}removeLocalQueryTarget(e){this.Lr.nr(e)}isLocalQueryTarget(e){return this.Lr.activeTargetIds.has(e)}clearQueryState(e){delete this.Ur[e]}getAllActiveQueryTargets(){return this.Lr.activeTargetIds}isActiveQueryTarget(e){return this.Lr.activeTargetIds.has(e)}start(){return this.Lr=new OE,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class FE{qr(e){}shutdown(){}}class UE{constructor(){this.Kr=()=>this.Gr(),this.Qr=()=>this.jr(),this.Wr=[],this.zr()}qr(e){this.Wr.push(e)}shutdown(){window.removeEventListener("online",this.Kr),window.removeEventListener("offline",this.Qr)}zr(){window.addEventListener("online",this.Kr),window.addEventListener("offline",this.Qr)}Gr(){h_("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Wr)e(0)}jr(){h_("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Wr)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const qE={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class VE{constructor(e){this.Hr=e.Hr,this.Jr=e.Jr}Yr(e){this.Xr=e}Zr(e){this.eo=e}onMessage(e){this.no=e}close(){this.Jr()}send(e){this.Hr(e)}so(){this.Xr()}io(e){this.eo(e)}ro(e){this.no(e)}}class BE extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.oo=t+"://"+e.host,this.uo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get co(){return!1}ao(t,e,n,r,i){const s=this.ho(t,e);h_("RestConnection","Sending: ",s,n);var a={};return this.lo(a,r,i),this.fo(t,s,a,n).then(e=>(h_("RestConnection","Received: ",e),e),e=>{throw p_("RestConnection",`${t} failed with error: `,e,"url: ",s,"request:",n),e})}_o(e,t,n,r,i,s){return this.ao(e,t,n,r,i)}lo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+c_,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}ho(e,t){var n=qE[e];return`${this.oo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(o,t,n,r){return new Promise((i,s)=>{const a=new s_;a.setWithCredentials(!0),a.listenOnce(Zy.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case Xy.NO_ERROR:var e=a.getResponseJson();h_("Connection","XHR received:",JSON.stringify(e)),i(e);break;case Xy.TIMEOUT:h_("Connection",'RPC "'+o+'" timed out'),s(new y_(v_.DEADLINE_EXCEEDED,"Request time out"));break;case Xy.HTTP_ERROR:var t,n=a.getStatus();if(h_("Connection",'RPC "'+o+'" failed with status:',n,"response text:",a.getResponseText()),0<n){const o=a.getResponseJson().error;o&&o.status&&o.message?(r=o.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(v_).indexOf(r)?r:v_.UNKNOWN,s(new y_(t,o.message))):s(new y_(v_.UNKNOWN,"Server responded with status "+a.getStatus()))}else s(new y_(v_.UNAVAILABLE,"Connection failed."));break;default:g_()}}finally{h_("Connection",'RPC "'+o+'" completed.')}var r});var e=JSON.stringify(r);a.send(t,"POST",e,n,15)})}wo(e,t,n){const r=[this.oo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=new Wy,s=Jy(),a={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};this.useFetchStreams&&(a.xmlHttpFactory=new r_({})),this.lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;var o=r.join("");h_("Connection","Creating WebChannel: "+o,a);const c=i.createWebChannel(o,a);let l=!1,u=!1;const h=new VE({Hr:e=>{u?h_("Connection","Not sending because WebChannel is closed:",e):(l||(h_("Connection","Opening WebChannel transport."),c.open(),l=!0),h_("Connection","WebChannel sending:",e),c.send(e))},Jr:()=>c.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(c,i_.EventType.OPEN,()=>{u||h_("Connection","WebChannel transport opened.")}),d(c,i_.EventType.CLOSE,()=>{u||(u=!0,h_("Connection","WebChannel transport closed"),h.io())}),d(c,i_.EventType.ERROR,e=>{u||(u=!0,p_("Connection","WebChannel transport errored:",e),h.io(new y_(v_.UNAVAILABLE,"The operation could not be completed")))}),d(c,i_.EventType.MESSAGE,n=>{if(!u){var e=n.data[0];m_(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){h_("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=Yy[e];if(void 0!==t)return dI(t)}(n),t=r.message;void 0===e&&(e=v_.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),u=!0,h.io(new y_(e,t)),c.close()}else h_("Connection","WebChannel received:",e),h.ro(e)}}),d(s,e_.STAT_EVENT,e=>{e.stat===t_?h_("Connection","Detected buffering proxy"):e.stat===n_&&h_("Connection","Detected no buffering proxy")}),setTimeout(()=>{h.so()},0),h}}function jE(){return"undefined"!=typeof window?window:null}function KE(){return"undefined"!=typeof document?document:null}function $E(e){return new OI(e,!0)}class WE{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Hs=e,this.timerId=t,this.mo=n,this.yo=r,this.po=i,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();var t=Math.floor(this.Io+this.bo()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);0<r&&h_("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Io} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.To=this.Hs.enqueueAfterDelay(this.timerId,r,()=>(this.Eo=Date.now(),e())),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}Po(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}bo(){return(Math.random()-.5)*this.Io}}class zE{constructor(e,t,n,r,i,s,a,o){this.Hs=e,this.vo=n,this.Vo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.So=0,this.Do=null,this.Co=null,this.stream=null,this.xo=new WE(e,t)}No(){return 1===this.state||5===this.state||this.ko()}ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Oo()}async stop(){this.No()&&await this.close(0)}Mo(){this.state=0,this.xo.reset()}Fo(){this.ko()&&null===this.Do&&(this.Do=this.Hs.enqueueAfterDelay(this.vo,6e4,()=>this.$o()))}Bo(e){this.Lo(),this.stream.send(e)}async $o(){if(this.ko())return this.close(0)}Lo(){this.Do&&(this.Do.cancel(),this.Do=null)}Uo(){this.Co&&(this.Co.cancel(),this.Co=null)}async close(e,t){this.Lo(),this.Uo(),this.xo.cancel(),this.So++,4!==e?this.xo.reset():t&&t.code===v_.RESOURCE_EXHAUSTED?(d_(t.toString()),d_("Using maximum backoff delay to prevent overloading the backend."),this.xo.Ao()):t&&t.code===v_.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.qo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Zr(t)}qo(){}auth(){this.state=1;const e=this.Ko(this.So),n=this.So;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.So===n&&this.Go(e,t)},t=>{e(()=>{var e=new y_(v_.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Qo(e)})})}Go(e,t){const n=this.Ko(this.So);this.stream=this.jo(e,t),this.stream.Yr(()=>{n(()=>(this.state=2,this.Co=this.Hs.enqueueAfterDelay(this.Vo,1e4,()=>(this.ko()&&(this.state=3),Promise.resolve())),this.listener.Yr()))}),this.stream.Zr(e=>{n(()=>this.Qo(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Oo(){this.state=5,this.xo.Ro(async()=>{this.state=0,this.start()})}Qo(e){return h_("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Ko(t){return e=>{this.Hs.enqueueAndForget(()=>this.So===t?e():(h_("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class GE extends zE{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.It=i}jo(e,t){return this.connection.wo("Listen",e,t)}onMessage(e){this.xo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(p=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===p?1:"REMOVE"===p?2:"CURRENT"===p?3:"RESET"===p?4:g_(),i=t.targetChange.targetIds||[],s=(p=t.targetChange.resumeToken,e.gt?(m_(void 0===p||"string"==typeof p),ww.fromBase64String(p||"")):(m_(void 0===p||p instanceof Uint8Array),ww.fromUint8Array(p||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(p=a).code?v_.UNKNOWN:dI(p.code),new y_(o,p.message||""));n=new CI(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var o=BI(e,c.document.name),l=FI(c.document.updateTime),u=new Yw({mapValue:{fields:c.document.fields}}),l=Jw.newFoundDocument(o,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new kI(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=BI(e,u.document),l=u.readTime?FI(u.readTime):P_.min(),l=Jw.newNoDocument(c,l),u=u.removedTargetIds||[];n=new kI([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=BI(e,h.document),h=h.removedTargetIds||[];n=new kI([],h,d,null)}else{if(!("filter"in t))return g_();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new uI(h),h=e.targetId;n=new SI(h,d)}}var o,p;return n}(this.It,e),n=function(e){if(!("targetChange"in e))return P_.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?FI(t.readTime):P_.min()}(e);return this.listener.Wo(t,n)}zo(e){const t={};t.database=$I(this.It),t.addTarget=function(e,t){let n;var r=t.target;return n=nb(r)?{documents:YI(e,r)}:{query:JI(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=LI(e,t.resumeToken):0<t.snapshotVersion.compareTo(P_.min())&&(n.readTime=MI(e,t.snapshotVersion.toTimestamp())),n}(this.It,e);var n,r,r=(this.It,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return g_()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Bo(t)}Ho(e){const t={};t.database=$I(this.It),t.removeTarget=e,this.Bo(t)}}class HE extends zE{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.It=i,this.Jo=!1}get Yo(){return this.Jo}start(){this.Jo=!1,this.lastStreamToken=void 0,super.start()}qo(){this.Jo&&this.Xo([])}jo(e,t){return this.connection.wo("Write",e,t)}onMessage(e){if(m_(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Jo){this.xo.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(m_(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?FI(e.updateTime):FI(t);return n.isEqual(P_.min())&&(n=FI(t)),new Qb(n,e.transformResults||[])}(e,i))):[]),n=FI(e.commitTime);return this.listener.Zo(n,t)}var r,i;return m_(!e.writeResults||0===e.writeResults.length),this.Jo=!0,this.listener.tu()}eu(){const e={};e.database=$I(this.It),this.Bo(e)}Xo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>HI(this.It,e))};this.Bo(t)}}class QE extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.It=r,this.nu=!1}su(){if(this.nu)throw new y_(v_.FAILED_PRECONDITION,"The client has already been terminated.")}ao(n,r,i){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.ao(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===v_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new y_(v_.UNKNOWN,e.toString())})}_o(n,r,i,s){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection._o(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===v_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new y_(v_.UNKNOWN,e.toString())})}terminate(){this.nu=!0}}class YE{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.iu=0,this.ru=null,this.ou=!0}uu(){0===this.iu&&(this.cu("Unknown"),this.ru=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.ru=null,this.au("Backend didn't respond within 10 seconds."),this.cu("Offline"),Promise.resolve())))}hu(e){"Online"===this.state?this.cu("Unknown"):(this.iu++,1<=this.iu&&(this.lu(),this.au(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.cu("Offline")))}set(e){this.lu(),this.iu=0,"Online"===e&&(this.ou=!1),this.cu(e)}cu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}au(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis 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.ou?(d_(t),this.ou=!1):h_("OnlineStateTracker",t)}lu(){null!==this.ru&&(this.ru.cancel(),this.ru=null)}}class JE{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.fu=[],this.du=new Map,this._u=new Set,this.wu=[],this.mu=i,this.mu.qr(e=>{n.enqueueAndForget(async()=>{ak(this)&&(h_("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t._u.add(4),await ZE(t),t.gu.set("Unknown"),t._u.delete(4),await XE(t)}(this))})}),this.gu=new YE(n,r)}}async function XE(e){if(ak(e))for(const t of e.wu)await t(!0)}async function ZE(e){for(const t of e.wu)await t(!1)}function ek(e,t){const n=e;n.du.has(t.targetId)||(n.du.set(t.targetId,t),sk(n)?ik(n):gk(n).ko()&&nk(n,t))}function tk(e,t){const n=e,r=gk(n);n.du.delete(t),r.ko()&&rk(n,t),0===n.du.size&&(r.ko()?r.Fo():ak(n)&&n.gu.set("Unknown"))}function nk(e,t){e.yu.Mt(t.targetId),gk(e).zo(t)}function rk(e,t){e.yu.Mt(t),gk(e).Ho(t)}function ik(t){t.yu=new NI({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),se:e=>t.du.get(e)||null}),gk(t).start(),t.gu.uu()}function sk(e){return ak(e)&&!gk(e).No()&&0<e.du.size}function ak(e){return 0===e._u.size}function ok(e){e.yu=void 0}async function ck(e,t,n){if(!nw(t))throw t;e._u.add(1),await ZE(e),e.gu.set("Offline"),n=n||(()=>yE(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{h_("RemoteStore","Retrying IndexedDB access"),await n(),e._u.delete(1),await XE(e)})}function lk(t,n){return n().catch(e=>ck(t,e,n))}async function uk(e){const t=e,n=mk(t);let r=0<t.fu.length?t.fu[t.fu.length-1].batchId:-1;for(;ak(i=t)&&i.fu.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.fu.length&&n.Fo();break}r=e.batchId,function(e,t){e.fu.push(t);const n=mk(e);n.ko()&&n.Yo&&n.Xo(t.mutations)}(t,e)}catch(e){await ck(t,e)}var i;hk(t)&&dk(t)}function hk(e){return ak(e)&&!mk(e).No()&&0<e.fu.length}function dk(e){mk(e).start()}async function pk(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),h_("RemoteStore","RemoteStore received new credentials");var r=ak(n);n._u.add(3),await ZE(n),r&&n.gu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n._u.delete(3),await XE(n)}async function fk(e,t){const n=e;t?(n._u.delete(2),await XE(n)):(n._u.add(2),await ZE(n),n.gu.set("Unknown"))}function gk(t){return t.pu||(t.pu=function(e,t,n){const r=e;return r.su(),new GE(t,r.connection,r.authCredentials,r.appCheckCredentials,r.It,n)}(t.datastore,t.asyncQueue,{Yr:(async function(n){n.du.forEach((e,t)=>{nk(n,e)})}).bind(null,t),Zr:(async function(e,t){ok(e),sk(e)?(e.gu.hu(t),ik(e)):e.gu.set("Unknown")}).bind(null,t),Wo:(async function(e,r,t){if(e.gu.set("Online"),r instanceof CI&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.du.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.du.delete(n),e.yu.removeTarget(n))}(e)}catch(t){h_("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await ck(e,t)}else if(r instanceof kI?e.yu.Gt(r):r instanceof SI?e.yu.Yt(r):e.yu.Wt(r),!t.isEqual(P_.min()))try{const r=await yE(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.yu.te(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.du.get(t);n&&r.du.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r.du.get(e);var n;t&&(r.du.set(e,t.withResumeToken(ww.EMPTY_BYTE_STRING,t.snapshotVersion)),rk(r,e),n=new MT(t.target,e,1,t.sequenceNumber),nk(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){h_("RemoteStore","Failed to raise snapshot:",r),await ck(e,r)}}).bind(null,t)}),t.wu.push(async e=>{e?(t.pu.Mo(),sk(t)?ik(t):t.gu.set("Unknown")):(await t.pu.stop(),ok(t))})),t.pu}function mk(t){return t.Iu||(t.Iu=function(e,t,n){const r=e;return r.su(),new HE(t,r.connection,r.authCredentials,r.appCheckCredentials,r.It,n)}(t.datastore,t.asyncQueue,{Yr:(async function(e){mk(e).eu()}).bind(null,t),Zr:(async function(e,t){t&&mk(e).Yo&&await async function(e,t){if(hI(n=t.code)&&n!==v_.ABORTED){const n=e.fu.shift();mk(e).Mo(),await lk(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await uk(e)}var n}(e,t),hk(e)&&dk(e)}).bind(null,t),tu:(async function(e){const t=mk(e);for(const n of e.fu)t.Xo(n.mutations)}).bind(null,t),Zo:(async function(e,t,n){const r=e.fu.shift(),i=PT.from(r,t,n);await lk(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await uk(e)}).bind(null,t)}),t.wu.push(async e=>{e?(t.Iu.Mo(),await uk(t)):(await t.Iu.stop(),0<t.fu.length&&(h_("RemoteStore",`Stopping write stream with ${t.fu.length} pending writes`),t.fu=[]))})),t.Iu}class vk{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new __,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new vk(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new y_(v_.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 yk(e,t){if(d_("AsyncQueue",`${t}: ${e}`),nw(e))return new y_(v_.UNAVAILABLE,`${t}: ${e}`);throw e}class _k{constructor(n){this.comparator=n?(e,t)=>n(e,t)||U_.comparator(e.key,t.key):(e,t)=>U_.comparator(e.key,t.key),this.keyedMap=mI(),this.sortedSet=new pw(this.comparator)}static emptySet(e){return new _k(e.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(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const 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 _k))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new _k;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class wk{constructor(){this.Tu=new pw(U_.comparator)}track(e){var t=e.doc.key,n=this.Tu.get(t);!n||0!==e.type&&3===n.type?this.Tu=this.Tu.insert(t,e):3===e.type&&1!==n.type?this.Tu=this.Tu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Tu=this.Tu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Tu=this.Tu.remove(t):1===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):g_()}Eu(){const n=[];return this.Tu.inorderTraversal((e,t)=>{n.push(t)}),n}}class bk{constructor(e,t,n,r,i,s,a,o,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new bk(e,t,_k.emptySet(t),s,n,r,!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)&&Nb(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Ik{constructor(){this.Au=void 0,this.listeners=[]}}class Tk{constructor(){this.queries=new pI(e=>Rb(e),Nb),this.onlineState="Unknown",this.Ru=new Set}}async function Ek(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new Ik),i)try{s.Au=await n.onListen(r)}catch(e){const n=yk(e,`Initialization of query '${xb(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.bu(n.onlineState),!s.Au||t.Pu(s.Au)&&Sk(n)}async function kk(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Sk(e){e.Ru.forEach(e=>{e.next()})}class Ck{constructor(e,t,n){this.query=e,this.vu=t,this.Vu=!1,this.Su=null,this.onlineState="Unknown",this.options=n||{}}Pu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new bk(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Vu?this.Du(e)&&(this.vu.next(e),t=!0):this.Cu(e,this.onlineState)&&(this.xu(e),t=!0),this.Su=e,t}onError(e){this.vu.error(e)}bu(e){this.onlineState=e;let t=!1;return this.Su&&!this.Vu&&this.Cu(this.Su,e)&&(this.xu(this.Su),t=!0),t}Cu(e,t){return!e.fromCache||(!this.options.Nu||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Du(e){if(0<e.docChanges.length)return!0;var t=this.Su&&this.Su.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}xu(e){e=bk.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Vu=!0,this.vu.next(e)}}class Ak{constructor(e,t){this.ku=e,this.byteLength=t}Ou(){return"metadata"in this.ku}}class Nk{constructor(e){this.It=e}Ji(e){return BI(this.It,e)}Yi(e){return e.metadata.exists?GI(this.It,e.document,!1):Jw.newNoDocument(this.Ji(e.metadata.name),this.Xi(e.metadata.readTime))}Xi(e){return FI(e)}}class Rk{constructor(e,t,n){this.Mu=e,this.localStore=t,this.It=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=xk(e)}Fu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ku.namedQuery)this.queries.push(e.ku.namedQuery);else if(e.ku.documentMetadata){this.documents.push({metadata:e.ku.documentMetadata}),e.ku.documentMetadata.exists||++t;const n=M_.fromString(e.ku.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ku.document&&(this.documents[this.documents.length-1].document=e.ku.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}$u(e){const t=new Map,n=new Nk(this.It);for(const i of e)if(i.metadata.queries){const e=n.Ji(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||bI()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=bI(),a=fI;for(const e of n){const n=t.Ji(e.metadata.name);e.document&&(s=s.add(n));const l=t.Yi(e);l.setReadTime(t.Xi(e.metadata.readTime)),a=a.insert(n,l)}const o=i.Gi.newChangeBuffer({trackRemovals:!0}),c=await bE(i,(r=r,Cb(bb(M_.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>wE(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Cs.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.Cs.addMatchingKeys(t,s,c.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.Wi,e.zi)).next(()=>e.Wi)))}(this.localStore,new Nk(this.It),this.documents,this.Mu.id),t=this.$u(this.documents);for(const e of this.queries)await async function(e,n,r=bI()){const i=await bE(e,Cb($T(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=FI(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Ns.saveNamedQuery(e,n);t=i.withResumeToken(ww.EMPTY_BYTE_STRING,t);return s.Ui=s.Ui.insert(t.targetId,t),s.Cs.updateTargetData(e,t).next(()=>s.Cs.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Cs.addMatchingKeys(e,r,i.targetId)).next(()=>s.Ns.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function xk(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Dk{constructor(e){this.key=e}}class Pk{constructor(e){this.key=e}}class Ok{constructor(e,t){this.query=e,this.Uu=t,this.qu=null,this.hasCachedResults=!1,this.current=!1,this.Ku=bI(),this.mutatedKeys=bI(),this.Gu=Ob(e),this.Qu=new _k(this.Gu)}get ju(){return this.Uu}Wu(e,t){const o=t?t.zu:new wk,c=(t||this).Qu;let l=(t||this).mutatedKeys,u=c,h=!1;const d="F"===this.query.limitType&&c.size===this.query.limit?c.last():null,p="L"===this.query.limitType&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=Db(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Hu(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Gu(r,d)||p&&this.Gu(r,p)<0)&&(h=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||p)&&(h=!0)),a&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){const e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),o.track({type:1,doc:e})}return{Qu:u,zu:o,$i:h,mutatedKeys:l}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const i=e.zu.Eu();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return g_()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc)),this.Ju(n);var s=t?this.Yu():[],a=0===this.Ku.size&&this.current?1:0,o=a!==this.qu;return this.qu=a,0!==i.length||o?{snapshot:new bk(this.query,e.Qu,r,i,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),Xu:s}:{Xu:s}}bu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new wk,mutatedKeys:this.mutatedKeys,$i:!1},!1)):{Xu:[]}}Zu(e){return!this.Uu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}Ju(e){e&&(e.addedDocuments.forEach(e=>this.Uu=this.Uu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Uu=this.Uu.delete(e)),this.current=e.current)}Yu(){if(!this.current)return[];const t=this.Ku;this.Ku=bI(),this.Qu.forEach(e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))});const n=[];return t.forEach(e=>{this.Ku.has(e)||n.push(new Pk(e))}),this.Ku.forEach(e=>{t.has(e)||n.push(new Dk(e))}),n}tc(e){this.Uu=e.Hi,this.Ku=bI();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}ec(){return bk.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.qu,this.hasCachedResults)}}class Mk{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Lk{constructor(e){this.key=e,this.nc=!1}}class Fk{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.sc={},this.ic=new pI(e=>Rb(e),Nb),this.rc=new Map,this.oc=new Set,this.uc=new pw(U_.comparator),this.cc=new Map,this.ac=new J0,this.hc={},this.lc=new Map,this.fc=C0.vn(),this.onlineState="Unknown",this.dc=void 0}get isPrimaryClient(){return!0===this.dc}}async function Uk(n,e,t,r,i){n._c=(e,s,t)=>async function(e,t,n){let r=t.view.Wu(s);r.$i&&(r=await TE(e.localStore,t.query,!1).then(({documents:e})=>t.view.Wu(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return Gk(e,t.targetId,i.Xu),i.snapshot}(n,e,t);const s=await TE(n.localStore,e,!0),a=new Ok(e,s.Hi),o=a.Wu(s.documents),c=EI.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,i),l=a.applyChanges(o,n.isPrimaryClient,c);Gk(n,t,l.Xu);var u=new Mk(e,t,a);return n.ic.set(e,u),n.rc.has(t)?n.rc.get(t).push(e):n.rc.set(t,[e]),l.snapshot}async function qk(e,t,n){const r=eS(e);try{const e=await function(e,i){const s=e,a=D_.now(),o=i.reduce((e,t)=>e.add(t.key),bI());let c,l;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=fI,r=bI();return s.Gi.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{c=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=qb(r.transform,e||null);null!=i&&(null===n&&(n=Yw.empty()),n.set(r.field,i))}return n||null}(n,c.get(n.key).overlayedDocument);null!=i&&t.push(new iI(n.key,i,function r(e){const i=[];return hw(e.fields,(e,t)=>{const n=new F_([e]);if(Ww(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new _w(i)}(i.value.mapValue),Yb.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(l=e).applyToLocalDocumentSet(c,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:l.batchId,changes:vI(c)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.hc[e.currentUser.toKey()];r=r||new pw(N_),r=r.insert(t,n),e.hc[e.currentUser.toKey()]=r}(r,e.batchId,n),await Qk(r,e.changes),await uk(r.remoteStore)}catch(e){const t=yk(e,"Failed to persist write");n.reject(t)}}async function Vk(e,t){const r=e;try{const e=await _E(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.cc.get(t);n&&(m_(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.nc=!0:0<e.modifiedDocuments.size?m_(n.nc):0<e.removedDocuments.size&&(m_(n.nc),n.nc=!1))}),await Qk(r,e,t)}catch(e){await Y_(e)}}function Bk(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ic.forEach((e,t)=>{var n=t.view.bu(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.bu(n)&&(r=!0)}),r&&Sk(t)}(t.eventManager,i),r.length&&t.sc.Wo(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function jk(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.Gi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=J_.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);m_(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=bI();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);$k(n,r,null),Kk(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Qk(n,e)}catch(e){await Y_(e)}}function Kk(e,t){(e.lc.get(t)||[]).forEach(e=>{e.resolve()}),e.lc.delete(t)}function $k(e,t,n){const r=e;let i=r.hc[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.hc[r.currentUser.toKey()]=i}}function Wk(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.rc.get(e))t.ic.delete(r),n&&t.sc.wc(r,n);t.rc.delete(e),t.isPrimaryClient&&t.ac.ls(e).forEach(e=>{t.ac.containsKey(e)||zk(t,e)})}function zk(e,t){e.oc.delete(t.path.canonicalString());var n=e.uc.get(t);null!==n&&(tk(e.remoteStore,n),e.uc=e.uc.remove(t),e.cc.delete(n),Hk(e))}function Gk(e,t,n){for(const r of n)r instanceof Dk?(e.ac.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.uc.get(n)||e.oc.has(r)||(h_("SyncEngine","New document in limbo: "+n),e.oc.add(r),Hk(e))}(e,r)):r instanceof Pk?(h_("SyncEngine","Document no longer in limbo: "+r.key),e.ac.removeReference(r.key,t),e.ac.containsKey(r.key)||zk(e,r.key)):g_()}function Hk(e){for(;0<e.oc.size&&e.uc.size<e.maxConcurrentLimboResolutions;){var t=e.oc.values().next().value;e.oc.delete(t);var n=new U_(M_.fromString(t)),t=e.fc.next();e.cc.set(t,new Lk(n)),e.uc=e.uc.insert(n,t),ek(e.remoteStore,new MT(Cb(bb(n.path)),t,2,lw.at))}}async function Qk(e,t,r){const i=e,s=[],a=[],o=[];i.ic.isEmpty()||(i.ic.forEach((e,n)=>{o.push(i._c(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=pE.Ci(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.sc.Wo(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>J_.forEach(t,t=>J_.forEach(t.Si,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>J_.forEach(t.Di,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!nw(e))throw e;h_("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Ui.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Ui=r.Ui.insert(t,i)}}}(i.localStore,a))}async function Yk(r,e){const i=r;if(Zk(i),eS(i),!0===e&&!0!==i.dc){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Jk(i,r.toArray());i.dc=!0,await fk(i.remoteStore,!0);for(const r of e)ek(i.remoteStore,r)}else if(!1===e&&!1!==i.dc){const r=[];let n=Promise.resolve();i.rc.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(Wk(i,t),IE(i.localStore,t,!0))),tk(i.remoteStore,t)}),await n,await Jk(i,r),function(){const n=i;n.cc.forEach((e,t)=>{tk(n.remoteStore,t)}),n.ac.fs(),n.cc=new Map,n.uc=new pw(U_.comparator)}(),i.dc=!1,await fk(i.remoteStore,!1)}}async function Jk(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.rc.get(t);if(u&&0!==u.length){e=await bE(r.localStore,Cb(u[0]));for(const t of u){const n=r.ic.get(t),u=(a=r,o=n,l=c=void 0,l=await TE((c=a).localStore,o.query,!0),l=o.view.tc(l),c.isPrimaryClient&&Gk(c,o.targetId,l.Xu),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await EE(r.localStore,t);e=await bE(r.localStore,u),await Uk(r,Xk(u),t,!1,e.resumeToken)}i.push(e)}var a,o,c,l;return r.sc.Wo(s),i}function Xk(e){return wb(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zk(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Vk.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.cc.get(t);if(r&&r.nc)return bI().add(r.key);{let e=bI();const r=n.rc.get(t);if(!r)return e;for(const t of r){const r=n.ic.get(t);e=e.unionWith(r.view.ju)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.cc.get(t),s=i&&i.key;if(s){let e=new pw(U_.comparator);e=e.insert(s,Jw.newNoDocument(s,P_.min()));const n=bI().add(s),i=new TI(P_.min(),new Map,new mw(N_),e,n);await Vk(r,i),r.uc=r.uc.remove(s),r.cc.delete(t),Hk(r)}else await IE(r.localStore,t,!1).then(()=>Wk(r,t,n)).catch(Y_)}).bind(null,t),t.sc.Wo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.Pu(e)&&(r=!0);i.Au=e}}r&&Sk(n)}).bind(null,t.eventManager),t.sc.wc=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function eS(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=jk.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(m_(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);$k(r,t,n),Kk(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Qk(r,e)}catch(n){await Y_(n)}}).bind(null,t),t}class tS{constructor(){this.synchronizeTabs=!1}async initialize(e){this.It=$E(e.databaseInfo.databaseId),this.sharedClientState=this.gc(e),this.persistence=this.yc(e),await this.persistence.start(),this.localStore=this.Ic(e),this.gcScheduler=this.Tc(e,this.localStore),this.indexBackfillerScheduler=this.Ec(e,this.localStore)}Tc(e,t){return null}Ec(e,t){return null}Ic(e){return mE(this.persistence,new fE,e.initialUser,this.It)}yc(e){return new rE(sE.Bs,this.It)}gc(e){return new LE}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class nS extends tS{constructor(e,t,n){super(),this.Ac=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ac.initialize(this,e),await eS(this.Ac.syncEngine),await uk(this.Ac.remoteStore),await this.persistence.li(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Ic(e){return mE(this.persistence,new fE,e.initialUser,this.It)}Tc(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new O0(n,e.asyncQueue,t)}Ec(e,t){var n=new cw(t,this.persistence);return new ow(e.asyncQueue,n)}yc(e){var t=dE(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?_0.withCacheSize(this.cacheSizeBytes):_0.DEFAULT;return new lE(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,jE(),KE(),this.It,this.sharedClientState,!!this.forceOwnership)}gc(e){return new LE}}class rS extends nS{constructor(e,t){super(e,t,!1),this.Ac=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ac.syncEngine;this.sharedClientState instanceof ME&&(this.sharedClientState.syncEngine={Fr:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Tn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):J_.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await uk(i.remoteStore):"acknowledged"===n||"rejected"===n?($k(i,t,r||null),Kk(i,t),i.localStore.mutationQueue.An(t)):g_(),await Qk(i,s)):h_("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),$r:(async function(e,t,n,r){const i=e;if(i.dc)h_("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.rc.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await kE(i.localStore,Pb(s[0])),r=TI.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,ww.EMPTY_BYTE_STRING);await Qk(i,e,r);break}case"rejected":await IE(i.localStore,t,!0),Wk(i,t,r);break;default:g_()}}}).bind(null,t),Br:(async function(e,t,n){const r=Zk(e);if(r.dc){for(const e of t)if(r.rc.has(e))h_("SyncEngine","Adding an already active target "+e);else{const t=await EE(r.localStore,e),n=await bE(r.localStore,t);await Uk(r,Xk(t),n.targetId,!1,n.resumeToken),ek(r.remoteStore,n)}for(const e of n)r.rc.has(e)&&await IE(r.localStore,e,!1).then(()=>{tk(r.remoteStore,e),Wk(r,e)}).catch(Y_)}}).bind(null,t),vi:(function(e){return e.localStore.persistence.vi()}).bind(null,t),Mr:(async function(e,t){const n=e;return kE(n.localStore,t).then(e=>Qk(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.li(async e=>{await Yk(this.Ac.syncEngine,e),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())})}gc(e){var t=jE();if(!ME.C(t))throw new y_(v_.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=dE(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ME(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class iS{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=>Bk(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){h_("SyncEngine","User change. New user:",t.toKey());const r=await vE(n.localStore,t);n.currentUser=t,(e=n).lc.forEach(e=>{e.forEach(e=>{e.reject(new y_(v_.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.lc.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await Qk(n,r.ji)}}).bind(null,this.syncEngine),await fk(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Tk}createDatastore(e){var t,n,r,i,s=$E(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new BE(t));return n=e.authCredentials,r=e.appCheckCredentials,i=t,e=s,new QE(n,r,i,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>Bk(this.syncEngine,e,0),s=new(UE.C()?UE:FE),new JE(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Fk(e,t,n,r,i,s);return a&&(o.dc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;h_("RemoteStore","RemoteStore shutting down."),t._u.add(5),await ZE(t),t.mu.shutdown(),t.gu.set("Unknown")}(this.remoteStore)}}function sS(e,t,n){if(!n)throw new y_(v_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function aS(e,t,n,r){if(!0===t&&!0===r)throw new y_(v_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function oS(e){if(!U_.isDocumentKey(e))throw new y_(v_.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function cS(e){if(U_.isDocumentKey(e))throw new y_(v_.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function lS(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":g_();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function uS(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new y_(v_.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=lS(e);throw new y_(v_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function hS(e,t){if(t<=0)throw new y_(v_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}const dS=new Map;class pS{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new y_(v_.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new y_(v_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,aS("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}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&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class fS{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new pS({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new y_(v_.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new y_(v_.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 pS(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new b_;switch(e.type){case"gapi":var t=e.client;return new k_(t,e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new y_(v_.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=dS.get(e);t&&(h_("ComponentProvider","Removing Datastore"),dS.delete(e),t.terminate())}(this),Promise.resolve()}}class gS{constructor(e,t,n){this.converter=t,this._key=n,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 vS(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new gS(this.firestore,e,this._key)}}class mS{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new mS(this.firestore,e,this._query)}}class vS extends mS{constructor(e,t,n){super(e,t,bb(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new gS(this.firestore,null,new U_(e))}withConverter(e){return new vS(this.firestore,e,this._path)}}function yS(e,t,...n){if(e=ae(e),sS("collection","path",t),e instanceof fS){var r=M_.fromString(t,...n);return cS(r),new vS(e,null,r)}if(!(e instanceof gS||e instanceof vS))throw new y_(v_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(M_.fromString(t,...n));return cS(r),new vS(e.firestore,null,r)}function _S(e,t,...n){if(e=ae(e),sS("doc","path",t=1===arguments.length?A_.R():t),e instanceof fS){var r=M_.fromString(t,...n);return oS(r),new gS(e,null,new U_(r))}if(!(e instanceof gS||e instanceof vS))throw new y_(v_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(M_.fromString(t,...n));return oS(r),new gS(e.firestore,e instanceof vS?e.converter:null,new U_(r))}function wS(e,t){return e=ae(e),t=ae(t),(e instanceof gS||e instanceof vS)&&(t instanceof gS||t instanceof vS)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function bS(e,t){return e=ae(e),t=ae(t),e instanceof mS&&t instanceof mS&&e.firestore===t.firestore&&Nb(e._query,t._query)&&e.converter===t.converter}function IS(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class TS{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Rc(this.observer.next,e)}error(e){this.observer.error?this.Rc(this.observer.error,e):d_("Uncaught Error in snapshot listener:",e)}bc(){this.muted=!0}Rc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class ES{constructor(e,t){this.Pc=e,this.It=t,this.metadata=new __,this.buffer=new Uint8Array,this.vc=new TextDecoder("utf-8"),this.Vc().then(e=>{e&&e.Ou()?this.metadata.resolve(e.ku.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ku)}`))},e=>this.metadata.reject(e))}close(){return this.Pc.cancel()}async getMetadata(){return this.metadata.promise}async mc(){return await this.getMetadata(),this.Vc()}async Vc(){var e=await this.Sc();if(null===e)return null;var t=this.vc.decode(e),n=Number(t);isNaN(n)&&this.Dc(`length string (${t}) is not valid number`);t=await this.Cc(n);return new Ak(JSON.parse(t),e.length+n)}xc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Sc(){for(;this.xc()<0&&!await this.Nc(););if(0===this.buffer.length)return null;var e=this.xc();e<0&&this.Dc("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Cc(e){for(;this.buffer.length<e;)await this.Nc()&&this.Dc("Reached the end of bundle when more is expected.");var t=this.vc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Dc(e){throw this.Pc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Nc(){var e=await this.Pc.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class kS{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new y_(v_.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=$I(r.It)+"/documents",i={documents:t.map(e=>VI(r.It,e))},s=await r._o("BatchGetDocuments",n,i,t.length),a=new Map;s.forEach(e=>{const t=(n=r.It,"found"in(e=e)?function(e,t){m_(!!t.found),t.found.name,t.found.updateTime;var n=BI(e,t.found.name),r=FI(t.found.updateTime),i=new Yw({mapValue:{fields:t.found.fields}});return Jw.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){m_(!!t.missing),m_(!!t.readTime);var n=BI(e,t.missing),r=FI(t.readTime);return Jw.newNoDocument(n,r)}(n,e):g_());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());m_(!!t),o.push(t)}),o}(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.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new cI(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=U_.fromPath(t);this.mutations.push(new lI(n,this.precondition(n)))}),await async function(e,t){const n=e,r=$I(n.It)+"/documents",i={writes:t.map(e=>HI(n.It,e))};await n.ao("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw g_();t=P_.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new y_(v_.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(P_.min())?Yb.exists(!1):Yb.updateTime(t):Yb.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Yb.exists(!0);if(t.isEqual(P_.min()))throw new y_(v_.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Yb.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class SS{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.kc=n.maxAttempts,this.xo=new WE(this.asyncQueue,"transaction_retry")}run(){--this.kc,this.Oc()}Oc(){this.xo.Ro(async()=>{const t=new kS(this.datastore),e=this.Mc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Fc(e)}))}).catch(e=>{this.Fc(e)})})}Mc(e){try{var t=this.updateFunction(e);return!Nw(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}}Fc(e){0<this.kc&&this.$c(e)?(--this.kc,this.asyncQueue.enqueueAndForget(()=>(this.Oc(),Promise.resolve()))):this.deferred.reject(e)}$c(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!hI(t)}}class CS{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=o_.UNAUTHENTICATED,this.clientId=A_.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{h_("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(h_("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new y_(v_.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new __;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=yk(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function AS(e,t){e.asyncQueue.verifyOperationInProgress(),h_("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await vE(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function NS(e,n){e.asyncQueue.verifyOperationInProgress();var t=await RS(e);h_("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>pk(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>pk(n.remoteStore,t)),e.onlineComponents=n}async function RS(e){return e.offlineComponents||(h_("FirestoreClient","Using default OfflineComponentProvider"),await AS(e,new tS)),e.offlineComponents}async function xS(e){return e.onlineComponents||(h_("FirestoreClient","Using default OnlineComponentProvider"),await NS(e,new iS)),e.onlineComponents}function DS(e){return RS(e).then(e=>e.persistence)}function PS(e){return RS(e).then(e=>e.localStore)}function OS(e){return xS(e).then(e=>e.remoteStore)}function MS(e){return xS(e).then(e=>e.syncEngine)}async function LS(e){const t=await xS(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Zk(e);let r,i;const s=n.ic.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.ec();else{const e=await bE(n.localStore,Cb(t));n.isPrimaryClient&&ek(n.remoteStore,e);const s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Uk(n,t,r,"current"===s,e.resumeToken)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ic.get(t),i=n.rc.get(r.targetId);if(1<i.length)return n.rc.set(r.targetId,i.filter(e=>!Nb(e,t))),void n.ic.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await IE(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),tk(n.remoteStore,r.targetId),Wk(n,r.targetId)}).catch(Y_)):(Wk(n,r.targetId),await IE(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function FS(e,t,n={}){const r=new __;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new TS({next:e=>{r.enqueueAndForget(()=>kk(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new y_(v_.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new y_(v_.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.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new Ck(bb(i.path),e,{includeMetadataChanges:!0,Nu:!0});return Ek(n,o)}(await LS(e),e.asyncQueue,t,n,r)),r.promise}function US(e,t,n={}){const r=new __;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new TS({next:e=>{n.enqueueAndForget(()=>kk(t,a)),e.fromCache&&"server"===r.source?i.reject(new y_(v_.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.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new Ck(e,s,{includeMetadataChanges:!0,Nu:!0});return Ek(t,a)}(await LS(e),e.asyncQueue,t,n,r)),r.promise}function qS(e,t,n,r){const i=(n=n,t=$E(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return IS(e,void 0);if(e instanceof ArrayBuffer)return IS(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new ES(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=FI(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ns.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(xk(i));const a=new Rk(i,t.localStore,n.It);let e=await n.mc();for(;e;){const t=await a.Fu(e);t&&r._updateProgress(t),e=await n.mc()}var s=await a.complete();return await Qk(t,s.Lu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ns.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.Bu)}catch(t){return p_("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await MS(e),i,r)})}class VS{constructor(){this.Bc=Promise.resolve(),this.Lc=[],this.Uc=!1,this.qc=[],this.Kc=null,this.Gc=!1,this.Qc=!1,this.jc=[],this.xo=new WE(this,"async_queue_retry"),this.Wc=()=>{var e=KE();e&&h_("AsyncQueue","Visibility state changed to "+e.visibilityState),this.xo.Po()};const e=KE();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Wc)}get isShuttingDown(){return this.Uc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.zc(),this.Hc(e)}enterRestrictedMode(e){if(!this.Uc){this.Uc=!0,this.Qc=e||!1;const t=KE();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Wc)}}enqueue(e){if(this.zc(),this.Uc)return new Promise(()=>{});const t=new __;return this.Hc(()=>this.Uc&&this.Qc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Lc.push(e),this.Jc()))}async Jc(){if(0!==this.Lc.length){try{await this.Lc[0](),this.Lc.shift(),this.xo.reset()}catch(e){if(!nw(e))throw e;h_("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Lc.length&&this.xo.Ro(()=>this.Jc())}}Hc(e){var t=this.Bc.then(()=>(this.Gc=!0,e().catch(e=>{throw this.Kc=e,this.Gc=!1,d_("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Gc=!1,e))));return this.Bc=t}enqueueAfterDelay(e,t,n){this.zc(),-1<this.jc.indexOf(e)&&(t=0);var r=vk.createAndSchedule(this,e,t,n,e=>this.Yc(e));return this.qc.push(r),r}zc(){this.Kc&&g_()}verifyOperationInProgress(){}async Xc(){for(var e;await(e=this.Bc),e!==this.Bc;);}Zc(e){for(const t of this.qc)if(t.timerId===e)return!0;return!1}ta(t){return this.Xc().then(()=>{this.qc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.qc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Xc()})}ea(e){this.jc.push(e)}Yc(e){var t=this.qc.indexOf(e);this.qc.splice(t,1)}}function BS(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class jS{constructor(){this._progressObserver={},this._taskCompletionResolver=new __,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}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 KS,$S,WS,zS,GS;class HS extends fS{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new VS,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||YS(this),this._firestoreClient.terminate()}}function QS(e){return e._firestoreClient||YS(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function YS(e){var t,n,r,i,s,a=e._freezeSettings(),a=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",i=e._persistenceKey,s=a,new Cw(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new CS(e._authCredentials,e._appCheckCredentials,e._queue,a)}function JS(e,n,r){const i=new __;return e.asyncQueue.enqueue(async()=>{try{await AS(e,r),await NS(e,n),i.resolve()}catch(e){const n=e;if(!("FirebaseError"===(t=n).name?t.code===v_.FAILED_PRECONDITION||t.code===v_.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw n;p_("Error enabling offline persistence. Falling back to persistence disabled: "+n),i.reject(n)}var t}).then(()=>i.promise)}function XS(e){return function(e){const t=new __;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;ak(n.remoteStore)||h_("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.lc.get(e)||[];r.push(t),n.lc.set(e,r)}catch(e){const n=yk(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await MS(e),t)),t.promise}(QS(e=uS(e,HS)))}function ZS(e){return(n=QS(e=uS(e,HS))).asyncQueue.enqueue(async()=>{const e=await DS(n),t=await OS(n);return e.setNetworkEnabled(!0),function(){const e=t;return e._u.delete(0),XE(e)}()});var n}function eC(e){return(n=QS(e=uS(e,HS))).asyncQueue.enqueue(async()=>{const e=await DS(n),t=await OS(n);return e.setNetworkEnabled(!1),async function(){const e=t;e._u.add(0),await ZE(e),e.gu.set("Offline")}()});var n}function tC(t,e){return n=QS(t=uS(t,HS)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ns.getNamedQuery(e,t))}(await PS(n),r)).then(e=>e?new mS(t,null,e.query):null);var n,r}function nC(e){if(e._initialized||e._terminated)throw new y_(v_.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.")}class rC{constructor(e){this._byteString=e}static fromBase64String(e){try{return new rC(ww.fromBase64String(e))}catch(e){throw new y_(v_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new rC(ww.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 iC{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new y_(v_.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new F_(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class sC{constructor(e){this._methodName=e}}class aC{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new y_(v_.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new y_(v_.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 N_(this._lat,e._lat)||N_(this._long,e._long)}}const oC=/^__.*__$/;class cC{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new iI(e,this.data,this.fieldMask,t,this.fieldTransforms):new rI(e,this.data,t,this.fieldTransforms)}}class lC{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new iI(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function uC(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw g_()}}class hC{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.It=n,this.ignoreUndefinedProperties=r,void 0===i&&this.na(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get sa(){return this.settings.sa}ia(e){return new hC(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.It,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ra(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.ua(e),r}ca(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.na(),r}aa(e){return this.ia({path:void 0,oa:!0})}ha(e){return xC(e,this.settings.methodName,this.settings.la||!1,this.path,this.settings.fa)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}na(){if(this.path)for(let e=0;e<this.path.length;e++)this.ua(this.path.get(e))}ua(e){if(0===e.length)throw this.ha("Document fields must not be empty");if(uC(this.sa)&&oC.test(e))throw this.ha('Document fields cannot begin and end with "__"')}}class dC{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.It=n||$E(e)}da(e,t,n,r=!1){return new hC({sa:e,methodName:t,fa:n,path:F_.emptyPath(),oa:!1,la:r},this.databaseId,this.It,this.ignoreUndefinedProperties)}}function pC(e){var t=e._freezeSettings(),n=$E(e._databaseId);return new dC(e._databaseId,!!t.ignoreUndefinedProperties,n)}function fC(e,t,n,r,i,s={}){const a=e.da(s.merge||s.mergeFields?2:0,t,n,i);CC("Data must be an object, but it was:",a,r);var o=kC(r,a);let c,l;if(s.merge)c=new _w(a.fieldMask),l=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=AC(t,r,n);if(!a.contains(i))throw new y_(v_.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);DC(e,i)||e.push(i)}c=new _w(e),l=a.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=a.fieldTransforms;return new cC(new Yw(o),c,l)}class gC extends sC{_toFieldTransform(e){if(2!==e.sa)throw 1===e.sa?e.ha(`${this._methodName}() can only appear at the top level of your update data`):e.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof gC}}function mC(e,t,n){return new hC({sa:3,fa:t.settings.fa,methodName:e._methodName,oa:n},t.databaseId,t.It,t.ignoreUndefinedProperties)}class vC extends sC{_toFieldTransform(e){return new Hb(e.path,new Vb)}isEqual(e){return e instanceof vC}}class yC extends sC{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=mC(this,e,!0),n=this._a.map(e=>EC(e,t)),r=new Bb(n);return new Hb(e.path,r)}isEqual(e){return this===e}}class _C extends sC{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=mC(this,e,!0),n=this._a.map(e=>EC(e,t)),r=new Kb(n);return new Hb(e.path,r)}isEqual(e){return this===e}}class wC extends sC{constructor(e,t){super(e),this.wa=t}_toFieldTransform(e){var t=new Wb(e.It,Fb(e.It,this.wa));return new Hb(e.path,t)}isEqual(e){return this===e}}function bC(e,i,s,t){const a=e.da(1,i,s);CC("Data must be an object, but it was:",a,t);const o=[],c=Yw.empty();hw(t,(e,t)=>{var n=RC(i,e,s);t=ae(t);var r=a.ca(n);if(t instanceof gC)o.push(n);else{const e=EC(t,r);null!=e&&(o.push(n),c.set(n,e))}});var n=new _w(o);return new lC(c,n,a.fieldTransforms)}function IC(e,t,n,r,i,s){const a=e.da(1,t,n),o=[AC(t,r,n)],c=[i];if(s.length%2!=0)throw new y_(v_.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(AC(t,s[p])),c.push(s[p+1]);const l=[],u=Yw.empty();for(let f=o.length-1;0<=f;--f)if(!DC(l,o[f])){const t=o[f];var h=ae(h=c[f]);const r=a.ca(t);if(h instanceof gC)l.push(t);else{const e=EC(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new _w(l);return new lC(u,d,a.fieldTransforms)}function TC(e,t,n,r=!1){return EC(n,e.da(r?4:3,t))}function EC(s,e){if(SC(s=ae(s)))return CC("Unsupported field value:",e,s),kC(s,e);if(s instanceof sC)return function(e,t){if(!uC(t.sa))throw t.ha(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ha(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(s,e),null;if(void 0===s&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),s instanceof Array){if(e.settings.oa&&4!==e.sa)throw e.ha("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=EC(i,t.aa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=ae(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Fb(t.It,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=D_.fromDate(e);return{timestampValue:MI(t.It,n)}}if(e instanceof D_){n=new D_(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:MI(t.It,n)}}if(e instanceof aC)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof rC)return{bytesValue:LI(t.It,e._byteString)};if(e instanceof gS){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.ha(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:UI(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ha(`Unsupported field value: ${lS(e)}`)}(0,e)}function kC(e,r){const i={};return dw(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):hw(e,(e,t)=>{var n=EC(t,r.ra(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function SC(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof D_||e instanceof aC||e instanceof rC||e instanceof gS||e instanceof sC)}function CC(e,t,n){if(!SC(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=lS(n);throw"an object"===r?t.ha(e+" a custom object"):t.ha(e+" "+r)}var i}function AC(e,t,n){if((t=ae(t))instanceof iC)return t._internalPath;if("string"==typeof t)return RC(e,t);throw xC("Field path arguments must be of type string or ",e,!1,void 0,n)}const NC=new RegExp("[~\\*/\\[\\]]");function RC(t,n,r){if(0<=n.search(NC))throw xC(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new iC(...n.split("."))._internalPath}catch(e){throw xC(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function xC(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let c="";return(s||a)&&(c+=" (found",s&&(c+=` in field ${r}`),a&&(c+=` in document ${i}`),c+=")"),new y_(v_.INVALID_ARGUMENT,o+e+c)}function DC(e,t){return e.some(e=>e.isEqual(t))}class PC{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new gS(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new OC(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(MC("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class OC extends PC{data(){return super.data()}}function MC(e,t){return"string"==typeof t?RC(e,t):(t instanceof iC?t:t._delegate)._internalPath}function LC(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new y_(v_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class FC{}function UC(e,...t){for(const n of t)e=n._apply(e);return e}class qC extends FC{constructor(e,t,n){super(),this.ma=e,this.ga=t,this.ya=n,this.type="where"}_apply(e){var t=pC(e.firestore),t=function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new y_(v_.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){zC(a,s);const t=[];for(const n of a)t.push(WC(r,e,n));o={arrayValue:{values:t}}}else o=WC(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||zC(a,s),o=TC(n,t,a,"in"===s||"not-in"===s);var c=ab.create(i,s,o);return function(e,t){if(t.dt()){const r=Eb(e);if(null!==r&&!r.isEqual(t.field))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${t.field.toString()}'`);var n=Tb(e);null!==n&&GC(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new y_(v_.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new y_(v_.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,c),c}(e._query,"where",t,e.firestore._databaseId,this.ma,this.ga,this.ya);return new mS(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new _b(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class VC extends FC{constructor(e,t){super(),this.ma=e,this.pa=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new y_(v_.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new y_(v_.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new mb(t,n);return n=i,null!==Tb(e=e)||null!==(r=Eb(e))&&GC(0,r,n.field),i}(e._query,this.ma,this.pa);return new mS(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new _b(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class BC extends FC{constructor(e,t,n){super(),this.type=e,this.Ia=t,this.Ta=n}_apply(e){return new mS(e.firestore,e.converter,Ab(e._query,this.Ia,this.Ta))}}class jC extends FC{constructor(e,t,n){super(),this.type=e,this.Ea=t,this.Aa=n}_apply(e){var t,n=$C(e,this.type,this.Ea,this.Aa);return new mS(e.firestore,e.converter,(t=e._query,e=n,new _b(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class KC extends FC{constructor(e,t,n){super(),this.type=e,this.Ea=t,this.Aa=n}_apply(e){var t,n=$C(e,this.type,this.Ea,this.Aa);return new mS(e.firestore,e.converter,(t=e._query,e=n,new _b(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function $C(e,t,n,r){if(n[0]=ae(n[0]),n[0]instanceof PC)return function(e,t,n,r,i){if(!r)throw new y_(v_.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Sb(e))if(n.field.isKeyField())s.push(Vw(t,r.key));else{const e=r.data.field(n.field);if(kw(e))throw new y_(v_.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.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){const e=n.field.canonicalString();throw new y_(v_.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.`)}s.push(e)}return new gb(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=pC(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new y_(v_.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let c=0;c<i.length;c++){const l=i[c];if(a[c].field.isKeyField()){if("string"!=typeof l)throw new y_(v_.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!kb(e)&&-1!==l.indexOf("/"))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(M_.fromString(l));if(!U_.isDocumentKey(n))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new U_(n);o.push(Vw(t,i))}else{const e=TC(n,r,l);o.push(e)}}return new gb(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function WC(e,t,n){if("string"==typeof(n=ae(n))){if(""===n)throw new y_(v_.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!kb(t)&&-1!==n.indexOf("/"))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(M_.fromString(n));if(!U_.isDocumentKey(r))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Vw(e,new U_(r))}if(n instanceof gS)return Vw(e,n._key);throw new y_(v_.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${lS(n)}.`)}function zC(e,t){if(!Array.isArray(e)||0===e.length)throw new y_(v_.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new y_(v_.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function GC(e,t,n){if(!n.isEqual(t))throw new y_(v_.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class HC{convertValue(e,t="none"){switch(Ow(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Tw(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(Ew(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 10:return this.convertObject(e.mapValue,t);default:throw g_()}}convertObject(e,n){const r={};return hw(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new aC(Tw(e.latitude),Tw(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return kw(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Sw(e));default:return null}}convertTimestamp(e){var t=Iw(e);return new D_(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=M_.fromString(e);m_(rT(n));const r=new Aw(n.get(1),n.get(3)),i=new U_(n.popFirst(5));return r.isEqual(t)||d_(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function QC(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class YC extends HC{constructor(e){super(),this.firestore=e}convertBytes(e){return new rC(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new gS(this.firestore,null,t)}}class JC{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class XC extends PC{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new ZC(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(MC("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class ZC extends XC{data(e={}){return super.data(e)}}class eA{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new JC(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new ZC(this._firestore,this._userDataWriter,e.key,e,new JC(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 y_(v_.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=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new ZC(s._firestore,s._userDataWriter,e.doc.key,e.doc,new JC(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new ZC(s._firestore,s._userDataWriter,e.doc.key,e.doc,new JC(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return g_()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function tA(e,t){return e instanceof XC&&t instanceof XC?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 eA&&t instanceof eA&&e._firestore===t._firestore&&bS(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class nA extends HC{constructor(e){super(),this.firestore=e}convertBytes(e){return new rC(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new gS(this.firestore,null,t)}}function rA(t){t=uS(t,gS);const n=uS(t.firestore,HS),e=QS(n),r=new nA(n);return function(e,t){const n=new __;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new y_(v_.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){var r=yk(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await PS(e),t,n)),n.promise}(e,t._key).then(e=>new XC(n,r,t._key,e,new JC(null!==e&&e.hasLocalMutations,!0),t.converter))}function iA(t){t=uS(t,mS);const n=uS(t.firestore,HS),e=QS(n),r=new nA(n);return function(e,t){const n=new __;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await TE(e,t,!0),s=new Ok(t,i.Hi),a=s.Wu(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=yk(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await PS(e),t,n)),n.promise}(e,t._query).then(e=>new eA(n,r,t,e))}function sA(e,t,n){e=uS(e,gS);var r=uS(e.firestore,HS),i=QC(e.converter,t,n);return lA(r,[fC(pC(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Yb.none())])}function aA(e,t,n,...r){e=uS(e,gS);var i=uS(e.firestore,HS),s=pC(i);let a;return a="string"==typeof(t=ae(t))||t instanceof iC?IC(s,"updateDoc",e._key,t,n,r):bC(s,"updateDoc",e._key,t),lA(i,[a.toMutation(e._key,Yb.exists(!0))])}function oA(t,...n){var e;t=ae(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||BS(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(BS(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,c;if(t instanceof gS)o=uS(t.firestore,HS),c=bb(t._key.path),a={next:e=>{n[i]&&n[i](uA(o,t,e))},error:n[i+1],complete:n[i+2]};else{const l=uS(t,mS);o=uS(l.firestore,HS),c=l._query;const u=new nA(o);a={next:e=>{n[i]&&n[i](new eA(o,u,l,e))},error:n[i+1],complete:n[i+2]},LC(t._query)}return function(e,t,n,r){const i=new TS(r),s=new Ck(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Ek(await LS(e),s)),()=>{i.bc(),e.asyncQueue.enqueueAndForget(async()=>kk(await LS(e),s))}}(QS(o),c,s,a)}function cA(e,t){return function(e,t){const n=new TS(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Ru.add(t),t.next()}(await LS(e),n)),()=>{n.bc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Ru.delete(t)}(await LS(e),n))}}(QS(e=uS(e,HS)),BS(t)?t:{next:t})}function lA(e,t){return function(e,t){const n=new __;return e.asyncQueue.enqueueAndForget(async()=>qk(await MS(e),t,n)),n.promise}(QS(e),t)}function uA(e,t,n){var r=n.docs.get(t._key),i=new nA(e);return new XC(e,i,t._key,r,new JC(n.hasPendingWrites,n.fromCache),t.converter)}const hA={maxAttempts:5};class dA{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=pC(e)}set(e,t,n){this._verifyNotCommitted();const r=pA(e,this._firestore),i=QC(r.converter,t,n),s=fC(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Yb.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=pA(e,this._firestore);let s;return s="string"==typeof(t=ae(t))||t instanceof iC?IC(this._dataReader,"WriteBatch.update",i._key,t,n,r):bC(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Yb.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=pA(e,this._firestore);return this._mutations=this._mutations.concat(new cI(t._key,Yb.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 y_(v_.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function pA(e,t){if((e=ae(e)).firestore!==t)throw new y_(v_.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class fA extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=pC(e)}get(e){const n=pA(e,this._firestore),r=new YC(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return g_();const t=e[0];if(t.isFoundDocument())return new PC(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new PC(this._firestore,r,n._key,null,n.converter);throw g_()})}set(e,t,n){var r=pA(e,this._firestore),i=QC(r.converter,t,n),i=fC(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=pA(e,this._firestore),s="string"==typeof(t=ae(t))||t instanceof iC?IC(this._dataReader,"Transaction.update",i._key,t,n,r):bC(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=pA(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=pA(e,this._firestore),n=new nA(this._firestore);return super.get(e).then(e=>new XC(this._firestore,n,t._key,e._document,new JC(!1,!1),t.converter))}}function gA(t,n,e){t=uS(t,HS);var r=Object.assign(Object.assign({},hA),e);return function(){if(r.maxAttempts<1)throw new y_(v_.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(t,n,r){const i=new __;return t.asyncQueue.enqueueAndForget(async()=>{var e=await xS(t).then(e=>e.datastore);new SS(t.asyncQueue,e,r,n,i).run()}),i.promise}(QS(t),e=>n(new fA(t,e)),r)}KS=Ye,c_=KS,ze(new oe("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new HS(new T_(e.getProvider("auth-internal")),new C_(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new y_(v_.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Aw(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:!0},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),et(a_,"3.7.2",void 0),et(a_,"3.7.2","esm2017");function mA(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new y_("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function vA(){if("undefined"==typeof Uint8Array)throw new y_("unimplemented","Uint8Arrays are not available in this environment.")}function yA(){if("undefined"==typeof atob)throw new y_("unimplemented","Blobs are unavailable in Firestore in this environment.")}class _A{constructor(e){this._delegate=e}static fromBase64String(e){return yA(),new _A(rC.fromBase64String(e))}static fromUint8Array(e){return vA(),new _A(rC.fromUint8Array(e))}toBase64(){return yA(),this._delegate.toBase64()}toUint8Array(){return vA(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function wA(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class bA{enableIndexedDbPersistence(e,t){return function(e,t){nC(e=uS(e,HS));var n=QS(e),r=e._freezeSettings(),i=new iS;return JS(n,i,new nS(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){nC(e=uS(e,HS));var t=QS(e),n=e._freezeSettings(),r=new iS;return JS(t,r,new rS(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new y_(v_.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new __;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Z_.C())return Promise.resolve();var t=e+"main";await Z_.delete(t)}(dE(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class IA{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Aw||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||p_("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(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=uS(n,fS))._getSettings();if("firestore.googleapis.com"!==s.host&&s.host!==e&&p_("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},s),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=o_.MOCK_USER;else{e=N(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new y_(v_.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new o_(s)}n._authCredentials=new I_(new w_(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return ZS(this._delegate)}disableNetwork(){return eC(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,aS("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return XS(this._delegate)}onSnapshotsInSync(e){return cA(this._delegate,e)}get app(){if(!this._appCompat)throw new y_("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new LA(this,yS(this._delegate,e))}catch(e){throw AA(e,"collection()","Firestore.collection()")}}doc(e){try{return new CA(this,_S(this._delegate,e))}catch(e){throw AA(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new PA(this,function(e,t){if(e=uS(e,fS),sS("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new y_(v_.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new mS(e,null,(t=t,new _b(M_.emptyPath(),t)))}(this._delegate,e))}catch(e){throw AA(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return gA(this._delegate,e=>t(new EA(this,e)))}batch(){return QS(this._delegate),new kA(new dA(this._delegate,e=>lA(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=QS(t=uS(t,HS)),r=new jS,qS(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return tC(this._delegate,e).then(e=>e?new PA(this,e):null)}}class TA extends HC{constructor(e){super(),this.firestore=e}convertBytes(e){return new _A(new rC(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return CA.forKey(t,this.firestore,null)}}class EA{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new TA(e)}get(e){const t=FA(e);return this._delegate.get(t).then(e=>new xA(this._firestore,new XC(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=FA(e);return n?(mA("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=FA(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=FA(e);return this._delegate.delete(t),this}}class kA{constructor(e){this._delegate=e}set(e,t,n){var r=FA(e);return n?(mA("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=FA(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=FA(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class SA{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new ZC(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new DA(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=SA.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new SA(e,new TA(e),t),r.set(t,i)),i}}SA.INSTANCES=new WeakMap;class CA{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new TA(e)}static forPath(e,t,n){if(e.length%2!=0)throw new y_("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new CA(t,new gS(t._delegate,n,new U_(e)))}static forKey(e,t,n){return new CA(t,new gS(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new LA(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new LA(this.firestore,yS(this._delegate,e))}catch(e){throw AA(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=ae(e))instanceof gS&&wS(this._delegate,e)}set(e,t){t=mA("DocumentReference.set",t);try{return t?sA(this._delegate,e,t):sA(this._delegate,e)}catch(e){throw AA(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?aA(this._delegate,e):aA(this._delegate,e,t,...n)}catch(e){throw AA(e,"updateDoc()","DocumentReference.update()")}}delete(){return lA(uS((e=this._delegate).firestore,HS),[new cI(e._key,Yb.none())]);var e}onSnapshot(...e){var t=NA(e),n=RA(e,e=>new xA(this.firestore,new XC(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return oA(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?rA:"server"===(null==e?void 0:e.source)?function(t){t=uS(t,gS);const n=uS(t.firestore,HS);return FS(QS(n),t._key,{source:"server"}).then(e=>uA(n,t,e))}:function(t){t=uS(t,gS);const n=uS(t.firestore,HS);return FS(QS(n),t._key).then(e=>uA(n,t,e))})(this._delegate),t.then(e=>new xA(this.firestore,new XC(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new CA(this.firestore,e?this._delegate.withConverter(SA.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function AA(e,t,n){return e.message=e.message.replace(t,n),e}function NA(e){for(const t of e)if("object"==typeof t&&!wA(t))return t;return{}}function RA(e,t){var n;let r;return r=wA(e[0])?e[0]:wA(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=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class xA{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new CA(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 tA(this._delegate,e._delegate)}}class DA extends xA{data(e){var t=this._delegate.data(e);return void 0!==t||g_(),t}}class PA{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new TA(e)}where(e,t,n){try{return new PA(this.firestore,UC(this._delegate,(r=n,i=t,s=MC("where",e),new qC(s,i,r))))}catch(e){throw AA(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new PA(this.firestore,UC(this._delegate,([n,r="asc"]=[e,t],i=r,s=MC("orderBy",n),new VC(s,i))))}catch(e){throw AA(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new PA(this.firestore,UC(this._delegate,(hS("limit",t=e),new BC("limit",t,"F"))))}catch(e){throw AA(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new PA(this.firestore,UC(this._delegate,(hS("limitToLast",t=e),new BC("limitToLast",t,"L"))))}catch(e){throw AA(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new PA(this.firestore,UC(this._delegate,function(...e){return new jC("startAt",e,!0)}(...e)))}catch(e){throw AA(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new PA(this.firestore,UC(this._delegate,function(...e){return new jC("startAfter",e,!1)}(...e)))}catch(e){throw AA(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new PA(this.firestore,UC(this._delegate,function(...e){return new KC("endBefore",e,!1)}(...e)))}catch(e){throw AA(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new PA(this.firestore,UC(this._delegate,function(...e){return new KC("endAt",e,!0)}(...e)))}catch(e){throw AA(e,"endAt()","Query.endAt()")}}isEqual(e){return bS(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?iA:"server"===(null==e?void 0:e.source)?function(t){t=uS(t,mS);const n=uS(t.firestore,HS),e=QS(n),r=new nA(n);return US(e,t._query,{source:"server"}).then(e=>new eA(n,r,t,e))}:function(t){t=uS(t,mS);const n=uS(t.firestore,HS),e=QS(n),r=new nA(n);return LC(t._query),US(e,t._query).then(e=>new eA(n,r,t,e))})(this._delegate),t.then(e=>new MA(this.firestore,new eA(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=NA(e),n=RA(e,e=>new MA(this.firestore,new eA(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return oA(this._delegate,t,n)}withConverter(e){return new PA(this.firestore,e?this._delegate.withConverter(SA.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class OA{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new DA(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class MA{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new PA(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 DA(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new OA(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new DA(this._firestore,e))})}isEqual(e){return tA(this._delegate,e._delegate)}}class LA extends PA{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 CA(this.firestore,e):null}doc(e){try{return void 0===e?new CA(this.firestore,_S(this._delegate)):new CA(this.firestore,_S(this._delegate,e))}catch(e){throw AA(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=uS(e.firestore,HS),r=_S(e),i=QC(e.converter,t);return lA(n,[fC(pC(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Yb.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new CA(this.firestore,e))}isEqual(e){return wS(this._delegate,e._delegate)}withConverter(e){return new LA(this.firestore,e?this._delegate.withConverter(SA.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function FA(e){return uS(e,gS)}const UA={Firestore:IA,GeoPoint:aC,Timestamp:D_,Blob:_A,Transaction:EA,WriteBatch:kA,DocumentReference:CA,DocumentSnapshot:xA,Query:PA,QueryDocumentSnapshot:DA,QuerySnapshot:MA,CollectionReference:LA,FieldPath:class $P{constructor(...e){this._delegate=new iC(...e)}static documentId(){return new $P(F_.keyField().canonicalString())}isEqual(e){return(e=ae(e))instanceof iC&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class WP{constructor(e){this._delegate=e}static serverTimestamp(){const e=new vC("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new WP(e)}static delete(){const e=new gC("deleteField");return e._methodName="FieldValue.delete",new WP(e)}static arrayUnion(...e){const t=function(...e){return new yC("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new WP(t)}static arrayRemove(...e){const t=function(...e){return new _C("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new WP(t)}static increment(e){const t=new wC("increment",e);return t._methodName="FieldValue.increment",new WP(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,l_.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};$S=wt,WS=(e,t)=>new IA(e,t,new bA),$S.INTERNAL.registerComponent(new oe("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return WS(t,n)},"PUBLIC").setServiceProps(Object.assign({},UA))),$S.registerVersion("@firebase/firestore-compat","0.2.2");const qA="type.googleapis.com/google.protobuf.Int64Value",VA="type.googleapis.com/google.protobuf.UInt64Value";function BA(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function jA(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case qA:case VA: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=>jA(e)):"function"==typeof e||"object"==typeof e?BA(e,e=>jA(e)):e}const KA="functions",$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 WA extends R{constructor(e,t,n){super(`${KA}/${e}`,t||""),this.details=n}}function zA(e,t){let n=function(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),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!$A[e])return new WA("internal","internal");n=$A[e],r=e}var a=s.message;"string"==typeof a&&(r=a),i=s.details,void 0!==i&&(i=jA(i))}}catch(e){}return"ok"===n?null:new WA(n,r,i)}class GA{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||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){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){var e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const HA="us-central1";class QA{constructor(e,t,n,r,i=HA,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new GA(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var a=new URL(i);this.customDomain=a.origin,this.region=HA}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function YA(i,s,a){return e=>{return t=e,n=a||{},r=(e=i)._url(s),JA(e,r,t,n);var t,n,r}}async function JA(e,t,n,r){var i={data:n=function t(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=>t(e));if("function"==typeof e||"object"==typeof e)return BA(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)};const s={};var a=await e.contextProvider.getContext();a.authToken&&(s.Authorization="Bearer "+a.authToken),a.messagingToken&&(s["Firebase-Instance-ID-Token"]=a.messagingToken),null!==a.appCheckToken&&(s["X-Firebase-AppCheck"]=a.appCheckToken);const o=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new WA("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(r.timeout||7e4);a=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}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),o.promise,e.cancelAllRequests]);if(o.cancel(),!a)throw new WA("cancelled","Firebase Functions instance was deleted.");i=zA(a.status,a.json);if(i)throw i;if(!a.json)throw new WA("internal","Response is not valid JSON object.");let c=a.json.data;if(void 0===c&&(c=a.json.result),void 0===c)throw new WA("internal","Response is missing data field.");return{data:jA(c)}}const XA="@firebase/functions";function ZA(e,t,n){ae(e).emulatorOrigin=`http://${t}:${n}`}function eN(e,t,n){return r=ae(e),i=t,s=n,e=>JA(r,i,e,s||{});var r,i,s}zS=fetch.bind(self),ze(new oe(KA,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new QA(n,r,i,s,t,zS)},"PUBLIC").setMultipleInstances(!0)),et(XA,"0.8.8",GS),et(XA,"0.8.8","esm2017");var tN,nN,rN,iN;class sN{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return YA(ae(this._delegate),e,t)}httpsCallableFromURL(e,t){return eN(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new R("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new R("functions","Port missing in origin provided to useFunctionsEmulator()");return ZA(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return ZA(this._delegate,e,t)}}const aN="us-central1",oN=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:aN});return new sN(n,r)};tN={Functions:sN},wt.INTERNAL.registerComponent(new oe("functions-compat",oN,"PUBLIC").setServiceProps(tN).setMultipleInstances(!0)),wt.registerVersion("@firebase/functions-compat","0.2.8");const cN="/firebase-messaging-sw.js",lN="/firebase-cloud-messaging-push-scope",uN="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",hN="https://fcmregistrations.googleapis.com/v1",dN="google.c.a.c_id",pN="google.c.a.e";function fN(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(Gc=SD=SD||{})[Gc.DATA_MESSAGE=1]="DATA_MESSAGE",Gc[Gc.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(Gc=nN=nN||{}).PUSH_RECEIVED="push-received",Gc.NOTIFICATION_CLICKED="notification-clicked";const gN="fcm_token_details_db",mN="fcm_token_object_Store";async function vN(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(gN))return null}let l=null;const e=await Re(gN,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(mN)){const o=r.objectStore(mN);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:fN(s.vapidKey)}}):3===t?(s=a,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=a,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)}}))}}});return e.close(),await xe(gN),await xe("fcm_vapid_details_db"),await xe("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"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}const yN="firebase-messaging-database",_N=1,wN="firebase-messaging-store";let bN=null;function IN(){return bN=bN||Re(yN,_N,{upgrade:(e,t)=>{0===t&&e.createObjectStore(wN)}}),bN}async function TN(e){var t=kN(e);const n=await IN();t=await n.transaction(wN).objectStore(wN).get(t);if(t)return t;t=await vN(e.appConfig.senderId);return t?(await EN(e,t),t):void 0}async function EN(e,t){var n=kN(e);const r=await IN(),i=r.transaction(wN,"readwrite");return await i.objectStore(wN).put(t,n),await i.done,t}function kN({appConfig:e}){return e.appId}const SN=new x("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 CN(e,t){var n={method:"DELETE",headers:await NN(e)};try{const s=await fetch(`${AN(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw SN.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw SN.create("token-unsubscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}}function AN({projectId:e}){return`${hN}/projects/${e}/registrations`}async function NN({appConfig:e,installations:t}){var n=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 ${n}`})}function RN({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==uN&&(i.web.applicationPubKey=r),i}const xN=6048e5;async function DN(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:fN(t.getKey("auth")),p256dh:fN(t.getKey("p256dh"))},c=await TN(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+xN?async function(t,e){try{var n=await async function(e,t){var n=await NN(e),r=RN(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${AN(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw SN.create("token-update-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw SN.create("token-update-failed",{errorInfo:r})}if(!i.token)throw SN.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await EN(t.firebaseDependencies,r),n}catch(e){throw await PN(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await CN(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return ON(e.firebaseDependencies,o)}return ON(e.firebaseDependencies,o)}async function PN(e){var t=await TN(e.firebaseDependencies);t&&(await CN(e.firebaseDependencies,t.token),await async function(e){var t=kN(e);const n=await IN(),r=n.transaction(wN,"readwrite");await r.objectStore(wN).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function ON(e,t){var n={token:await async function(e,t){var n=await NN(e),r=RN(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(AN(e.appConfig),r);i=await s.json()}catch(e){throw SN.create("token-subscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw SN.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw SN.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await EN(e,n),n.token}function MN(e){var t,n,r,i,s,a={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return r=a,(n=e).notification&&(r.notification={},(t=n.notification.title)&&(r.notification.title=t),(t=n.notification.body)&&(r.notification.body=t),(t=n.notification.image)&&(r.notification.image=t),(t=n.notification.icon)&&(r.notification.icon=t)),n=a,(r=e).data&&(n.data=r.data),r=a,((e=e).fcmOptions||null!==(i=e.notification)&&void 0!==i&&i.click_action)&&(r.fcmOptions={},(s=null!==(i=null===(i=e.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=e.notification)||void 0===s?void 0:s.click_action)&&(r.fcmOptions.link=s),(s=null===(s=e.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(r.fcmOptions.analyticsLabel=s)),a}function LN(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function FN(e){return SN.create("missing-app-config-values",{valueName:e})}LN("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),LN("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class UN{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw FN("App Configuration Object");if(!e.name)throw FN("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw FN(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function qN(e){try{e.swRegistration=await navigator.serviceWorker.register(cN,{scope:lN}),e.swRegistration.update().catch(()=>{})}catch(e){throw SN.create("failed-service-worker-registration",{browserErrorMessage:null===e||void 0===e?void 0:e.message})}}async function VN(e,t){if(!navigator)throw SN.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw SN.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=uN)),await async function(e,t){if(t||e.swRegistration||await qN(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw SN.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),DN(e)}async function BN(e,t,n){var r=function(e){switch(e){case nN.NOTIFICATION_CLICKED:return"notification_open";case nN.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[dN],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function jN(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===nN.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(MN(r)):e.onMessageHandler.next(MN(r))),n=r.data,"object"==typeof(t=n)&&t&&dN in t&&"1"===n[pN]&&await BN(e,r.messageType,n))}const KN="@firebase/messaging",$N=e=>{const t=new UN(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>jN(t,e)),t},WN=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>VN(t,e)}};function zN(e){return async function(e){if(!navigator)throw SN.create("only-available-in-window");return e.swRegistration||await qN(e),PN(e)}(e=ae(e))}function GN(e,t){return function(e,t){if(!navigator)throw SN.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=ae(e),t)}ze(new oe("messaging",$N,"PUBLIC")),ze(new oe("messaging-internal",WN,"PRIVATE")),et(KN,"0.10.0"),et(KN,"0.10.0","esm2017");const HN="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",QN="https://fcmregistrations.googleapis.com/v1",YN="FCM_MSG",JN="google.c.a.c_id",XN=3,ZN=1;function eR(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(Gc=rN=rN||{})[Gc.DATA_MESSAGE=1]="DATA_MESSAGE",Gc[Gc.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(It=iN=iN||{}).PUSH_RECEIVED="push-received",It.NOTIFICATION_CLICKED="notification-clicked";const tR="fcm_token_details_db",nR="fcm_token_object_Store";async function rR(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(tR))return null}let l=null;const e=await Re(tR,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(nR)){const o=r.objectStore(nR);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:eR(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:eR(s.auth),p256dh:eR(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:eR(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:eR(a.auth),p256dh:eR(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:eR(a.vapidKey)}}))}}});return e.close(),await xe(tR),await xe("fcm_vapid_details_db"),await xe("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"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}const iR="firebase-messaging-database",sR=1,aR="firebase-messaging-store";let oR=null;function cR(){return oR=oR||Re(iR,sR,{upgrade:(e,t)=>{0===t&&e.createObjectStore(aR)}}),oR}async function lR(e){var t=hR(e);const n=await cR();t=await n.transaction(aR).objectStore(aR).get(t);if(t)return t;t=await rR(e.appConfig.senderId);return t?(await uR(e,t),t):void 0}async function uR(e,t){var n=hR(e);const r=await cR(),i=r.transaction(aR,"readwrite");return await i.objectStore(aR).put(t,n),await i.done,t}function hR({appConfig:e}){return e.appId}const dR=new x("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 pR(e,t){var n={method:"DELETE",headers:await gR(e)};try{const s=await fetch(`${fR(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw dR.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw dR.create("token-unsubscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}}function fR({projectId:e}){return`${QN}/projects/${e}/registrations`}async function gR({appConfig:e,installations:t}){var n=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 ${n}`})}function mR({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==HN&&(i.web.applicationPubKey=r),i}async function vR(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:eR(t.getKey("auth")),p256dh:eR(t.getKey("p256dh"))},c=await lR(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await gR(e),r=mR(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${fR(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw dR.create("token-update-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw dR.create("token-update-failed",{errorInfo:r})}if(!i.token)throw dR.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await uR(t.firebaseDependencies,r),n}catch(e){throw await yR(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await pR(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return _R(e.firebaseDependencies,o)}return _R(e.firebaseDependencies,o)}async function yR(e){var t=await lR(e.firebaseDependencies);t&&(await pR(e.firebaseDependencies,t.token),await async function(e){var t=hR(e);const n=await cR(),r=n.transaction(aR,"readwrite");await r.objectStore(aR).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function _R(e,t){var n={token:await async function(e,t){var n=await gR(e),r=mR(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(fR(e.appConfig),r);i=await s.json()}catch(e){throw dR.create("token-subscribe-failed",{errorInfo:null===e||void 0===e?void 0:e.toString()})}if(i.error){r=i.error.message;throw dR.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw dR.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await uR(e,n),n.token}async function wR(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=rN.DISPLAY_NOTIFICATION.toString():r.message_type=rN.DATA_MESSAGE.toString();r.sdk_platform=XN.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=ZN.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function bR(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function IR(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await wR(t,n);var r,i,s,a,o=await ER();if(o.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=iN.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(o,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[YN]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(a={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},o=a,(e=r).notification&&(o.notification={},(n=e.notification.title)&&(o.notification.title=n),(n=e.notification.body)&&(o.notification.body=n),(n=e.notification.image)&&(o.notification.image=n),(n=e.notification.icon)&&(o.notification.icon=n)),e=a,(o=r).data&&(e.data=o.data),o=a,((r=r).fcmOptions||null!==(i=r.notification)&&void 0!==i&&i.click_action)&&(o.fcmOptions={},(s=null!==(i=null===(i=r.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=r.notification)||void 0===s?void 0:s.click_action)&&(o.fcmOptions.link=s),(s=null===(s=r.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(o.fcmOptions.analyticsLabel=s)),a=a,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(a):t.onBackgroundMessageHandler.next(a))}}async function TR(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[YN];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&JN in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await ER();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=iN.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function ER(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function kR(e){return dR.create("missing-app-config-values",{valueName:e})}bR("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),bR("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class SR{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw kR("App Configuration Object");if(!e.name)throw kR("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw kR(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const CR=e=>{const t=new SR(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(IR(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await lR(t.firebaseDependencies),await yR(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:HN,await vR(t)):await yR(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(TR(e))}),t};function AR(e,t){return function(e,t){if(void 0!==self.document)throw dR.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=ae(e),t)}ze(new oe("messaging-sw",CR,"PUBLIC"));var NR,RR,xR;class DR{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return VN(e=ae(e),t)}(this._delegate,e)}async deleteToken(){return zN(this._delegate)}onMessage(e){return GN(this._delegate,e)}onBackgroundMessage(e){return AR(this._delegate,e)}}const PR=e=>self&&"ServiceWorkerGlobalScope"in self?new DR(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new DR(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),OR={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?v()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&v()&&_()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};wt.INTERNAL.registerComponent(new oe("messaging-compat",PR,"PUBLIC").setServiceProps(OR)),wt.registerVersion("@firebase/messaging-compat","0.1.20");const MR="firebasestorage.googleapis.com",LR="storageBucket";class FR extends R{constructor(e,t,n=0){super(UR(e),`Firebase Storage: ${t} (${UR(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,FR.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return UR(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function UR(e){return"storage/"+e}function qR(){return new FR("unknown","An unknown error occurred, please check the error payload for server response.")}function VR(){return new FR("retry-limit-exceeded","Max retry time for operation exceeded, please try again.")}function BR(){return new FR("canceled","User canceled the upload/download.")}function jR(){return new FR("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function KR(e){return new FR("invalid-argument",e)}function $R(){return new FR("app-deleted","The Firebase app was deleted.")}function WR(e){return new FR("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 zR(e,t){return new FR("invalid-format","String does not match format '"+e+"': "+t)}function GR(e){throw new FR("internal-error","Internal error: "+e)}class HR{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=HR.makeFromUrl(t,e)}catch(e){return new HR(t,"")}if(""===n.path)return n;throw t=t,new FR("invalid-default-bucket","Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),o=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),a=t===MR?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{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:o,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${a}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new HR(u,e),d.postModify(n);break}}if(null==n)throw t=e,new FR("invalid-url","Invalid URL '"+t+"'.");return n}}class QR{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function YR(e){return"string"==typeof e||e instanceof String}function JR(e){return XR()&&e instanceof Blob}function XR(){return"undefined"!=typeof Blob&&!l()}function ZR(e,t,n,r){if(r<t)throw KR(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw KR(`Invalid value for '${e}'. Expected ${n} or less.`)}function ex(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function tx(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}function nx(e,t){var n=500<=e&&e<600,r=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return n||r||i}(It=NR=NR||{})[It.NO_ERROR=0]="NO_ERROR",It[It.NETWORK_ERROR=1]="NETWORK_ERROR",It[It.ABORT=2]="ABORT";class rx{constructor(e,t,n,r,i,s,a,o,c,l,u,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=a,this.errorCallback_=o,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.retry=h,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=(r,e)=>{if(e)r(!1,new ix(!1,null,!0));else{const i=this.connectionFactory_();this.pendingConnection_=i;const s=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&i.addUploadProgressListener(s),i.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&i.removeUploadProgressListener(s),this.pendingConnection_=null;var e,t=i.getErrorCode()===NR.NO_ERROR,n=i.getStatus();t&&!nx(n,this.additionalRetryCodes_)||!this.retry?(e=-1!==this.successCodes_.indexOf(n),r(!0,new ix(e,i))):(e=i.getErrorCode()===NR.ABORT,r(!1,new ix(!1,null,e)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const o=qR();o.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,o)):r(o)}else{var a;t.canceled?(a=(this.appDelete_?$R:BR)(),r(a)):(a=VR(),r(a))}};this.canceled_?t(0,new ix(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,a=!1,o=0;function c(){return 2===o}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(p,c())},e)}function d(){s&&clearTimeout(s)}function p(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||a)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===o?(o=2,0):1e3*(r+Math.random()),h(e)}}let f=!1;function g(e){f||(f=!0,d(),l||(null!==i?(e||(o=2),clearTimeout(i),h(0)):e||(o=1)))}return h(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 ix{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function sx(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(XR())return new Blob(t);throw new FR("unsupported-environment","This browser doesn't seem to support creating Blobs")}const ax={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class ox{constructor(e,t){this.data=e,this.contentType=t||null}}function cx(e,t){switch(e){case ax.RAW:return new ox(lx(t));case ax.BASE64:case ax.BASE64URL:return new ox(ux(e,t));case ax.DATA_URL:return new ox((n=t,(r=new hx(n)).base64?ux(ax.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw zR(ax.DATA_URL,"Malformed data URL.")}return lx(t)}(r.rest)),(n=t,new hx(n).contentType))}var n,r;throw qR()}function lx(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function ux(t,e){switch(t){case ax.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw zR(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case ax.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw zR(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw zR(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return s}class hx{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw zR(ax.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class dx{constructor(e,t){let n=0,r="";JR(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(JR(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new dx(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new dx(n,!0)}static getBlob(...e){if(XR()){var t=e.map(e=>e instanceof dx?e.data_:e);return new dx(sx.apply(null,t))}{const r=e.map(e=>YR(e)?cx(ax.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new dx(i,!0)}}uploadData(){return this.data_}}function px(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function fx(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function gx(e,t){return t}class mx{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||gx}}let vx=null;function yx(){if(vx)return vx;const e=[];e.push(new mx("bucket")),e.push(new mx("generation")),e.push(new mx("metageneration")),e.push(new mx("name","fullPath",!0));const t=new mx("name");t.xform=function(e,t){return!YR(t=t)||t.length<2?t:fx(t)},e.push(t);const n=new mx("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new mx("timeCreated")),e.push(new mx("updated")),e.push(new mx("md5Hash",null,!0)),e.push(new mx("cacheControl",null,!0)),e.push(new mx("contentDisposition",null,!0)),e.push(new mx("contentEncoding",null,!0)),e.push(new mx("contentLanguage",null,!0)),e.push(new mx("contentType",null,!0)),e.push(new mx("metadata","customMetadata",!0)),vx=e,vx}function _x(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new HR(e,t);return r._makeStorageReference(t)}})}function wx(e,t,n){var r=px(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const a=n[s];r[a.local]=a.xform(r,t[a.server])}return _x(r,e),r}(e,r,n)}function bx(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}const Ix="prefixes";function Tx(e,t,n){var r=px(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[Ix])for(const a of n[Ix]){var i=a.replace(/\/$/,""),i=e._makeStorageReference(new HR(t,i));r.prefixes.push(i)}if(n.items)for(const o of n.items){var s=e._makeStorageReference(new HR(t,o.name));r.items.push(s)}return r}(e,t,r)}class Ex{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function kx(e){if(!e)throw qR()}function Sx(r,i){return function(e,t){var n=wx(r,t,i);return kx(null!==n),n}}function Cx(r,i){return function(e,t){var n=Tx(r,i,t);return kx(null!==n),n}}function Ax(r,i){return function(e,t){var n=wx(r,t,i);return kx(null!==n),function(r,e,i,s){var t=px(e);if(null===t)return null;if(!YR(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const a=encodeURIComponent,o=n.split(",");return o.map(e=>{var t=r.bucket,n=r.fullPath;return ex("/b/"+a(t)+"/o/"+a(n),i,s)+tx({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function Nx(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new FR("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new FR("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new FR("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(r=i.path,new FR("unauthorized","User does not have permission to access '"+r+"'.")):t,n.status=e.getStatus(),n.serverResponse=t.serverResponse,n}}function Rx(r){const i=Nx(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new FR("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function xx(e,t,n){var r=ex(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new Ex(r,"GET",Sx(e,n),i);return s.errorHandler=Rx(t),s}function Dx(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function Px(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const a={"X-Goog-Upload-Protocol":"multipart"};var o=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();a["Content-Type"]="multipart/related; boundary="+o;var c=Dx(t,r,i),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+bx(c,n)+"\r\n--"+o+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",o="\r\n--"+o+"--";const u=dx.getBlob(l,r,o);if(null===u)throw jR();o={name:c.fullPath},c=ex(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new Ex(c,"POST",Sx(e,n),s);return h.urlParams=o,h.headers=a,h.body=u.uploadData(),h.errorHandler=Nx(t),h}class Ox{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function Mx(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){kx(!1)}const r=t||["active"];return kx(!!n&&-1!==r.indexOf(n)),n}function Lx(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),a=Dx(t,r,i),o={name:a.fullPath},c=ex(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},s=bx(a,n),a=e.maxUploadRetryTime;const u=new Ex(c,"POST",function(e){Mx(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){kx(!1)}return kx(YR(t)),t},a);return u.urlParams=o,u.headers=l,u.body=s,u.errorHandler=Nx(t),u}function Fx(e,t,n,i){var r=e.maxUploadRetryTime;const s=new Ex(n,"POST",function(e){var t=Mx(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){kx(!1)}n||kx(!1);var r=Number(n);return kx(!isNaN(r)),new Ox(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=Nx(t),s}function Ux(e,a,t,o,n,c,r,i){const l=new Ox(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=o.size()),o.size()!==l.total)throw new FR("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u;let p="";p=0===u?"finalize":s===u?"upload, finalize":"upload";s={"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":`${l.current}`};const f=o.slice(h,d);if(null===f)throw jR();d=a.maxUploadRetryTime;const g=new Ex(t,"POST",function(e,t){var n=Mx(e,["active","final"]),r=l.current+u,i=o.size();let s;return s="final"===n?Sx(a,c)(e,t):null,new Ox(r,i,"final"===n,s)},d);return g.headers=s,g.body=f.uploadData(),g.progressCallback=i||null,g.errorHandler=Nx(e),g}const qx={STATE_CHANGED:"state_changed"},Vx={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Bx(e){switch(e){case"running":case"pausing":case"canceling":return Vx.RUNNING;case"paused":return Vx.PAUSED;case"success":return Vx.SUCCESS;case"canceled":return Vx.CANCELED;default:return Vx.ERROR}}class jx{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function Kx(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class $x extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=NR.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=NR.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=NR.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw GR("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw GR("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw GR("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw GR("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw GR("cannot .getErrorText() before sending");return this.xhr_.statusText}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 Wx(){return new $x}class zx{constructor(e,t,n=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=n,this._mappings=yx(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals("canceled"))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(nx(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=VR()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals("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,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const 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(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=Lx(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,Wx,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=Fx(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,Wx,e,t);this._request=r,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(){const i=262144*this._chunkMultiplier,s=new Ox(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=Ux(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")}const r=this._ref.storage._makeRequest(n,Wx,e,t,!1);this._request=r,r.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 n=xx(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,Wx,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=Px(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,Wx,e,t);this._request=r,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=BR(),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=Bx(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new jx(t||void 0,n||void 0,r||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();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(Bx(this._state)){case Vx.SUCCESS:Kx(this._resolve.bind(null,this.snapshot))();break;case Vx.CANCELED:case Vx.ERROR:const t=this._reject;Kx(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Bx(this._state)){case Vx.RUNNING:case Vx.PAUSED:e.next&&Kx(e.next.bind(e,this.snapshot))();break;case Vx.SUCCESS:e.complete&&Kx(e.complete.bind(e))();break;case Vx.CANCELED:case Vx.ERROR:default:e.error&&Kx(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 Gx{constructor(e,t){this._service=e,t instanceof HR?this._location=t:this._location=HR.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new Gx(e,t)}get root(){var e=new HR(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return fx(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new HR(this._location.bucket,e);return new Gx(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw WR(e)}}function Hx(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await Qx(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function Qx(e,t){null!=t&&"number"==typeof t.maxResults&&ZR("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var a=ex(t.bucketOnlyServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime;const c=new Ex(a,"GET",Cx(e,t.bucket),o);return c.urlParams=s,c.errorHandler=Nx(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,Wx)}function Yx(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=ex(t.fullServerUrl(),e.host,e._protocol),s=bx(n,r),a=e.maxOperationRetryTime;const o=new Ex(i,"PATCH",Sx(e,r),a);return o.headers={"Content-Type":"application/json; charset=utf-8"},o.body=s,o.errorHandler=Rx(t),o}(e.storage,e._location,t,yx());return e.storage.makeRequestWithTokens(n,Wx)}function Jx(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=ex(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new Ex(r,"GET",Ax(e,n),i);return s.errorHandler=Rx(t),s}(e.storage,e._location,yx());return e.storage.makeRequestWithTokens(t,Wx).then(e=>{if(null===e)throw new FR("no-download-url","The given file does not have any download URLs.");return e})}function Xx(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=ex(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new Ex(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=Rx(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,Wx)}function Zx(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new HR(e._location.bucket,r);return new Gx(e.storage,r)}function eD(e,t){if(e instanceof rD){var n=e;if(null==n._bucket)throw new FR("no-default-bucket","No default bucket found. Did you set the '"+LR+"' property when initializing the app?");n=new Gx(n,n._bucket);return null!=t?eD(n,t):n}return void 0!==t?Zx(e,t):e}function tD(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof rD)return n=e,r=t,new Gx(n,r);throw KR("To use ref(service, url), the first argument must be a Storage instance.")}return eD(e,t);var n,r}function nD(e,t){var n=null==t?void 0:t[LR];return null==n?null:HR.makeFromBucketSpec(n,e)}class rD{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=MR,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?HR.makeFromBucketSpec(r,this._host):nD(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=HR.makeFromBucketSpec(this._url,e):this._bucket=nD(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){ZR("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){ZR("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(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 Gx(this,e)}_makeRequest(e,t,n,r,i=!0){if(this._deleted)return new QR($R());{const u=([s,a,o,e,n,r,t=!0]=[e,this._appId,n,r,t,this._firebaseVersion,i],c=tx(s.urlParams),l=s.url+c,c=Object.assign({},s.headers),i=c,(a=a)&&(i["X-Firebase-GMPID"]=a),a=c,null!==(o=o)&&0<o.length&&(a.Authorization="Firebase "+o),r=r,c["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=c,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new rx(l,s.method,c,s.body,s.successCodes,s.additionalRetryCodes,s.handler,s.errorHandler,s.timeout,s.progressCallback,n,t));return this._requests.add(u),u.getPromise().then(()=>this._requests.delete(u),()=>this._requests.delete(u)),u}var s,a,o,c,l}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const iD="@firebase/storage";function sD(e,t,n){return e=ae(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new zx(e,new dx(t),n)}function aD(e){return function(e){e._throwIfRoot("getMetadata");var t=xx(e.storage,e._location,yx());return e.storage.makeRequestWithTokens(t,Wx)}(e=ae(e))}function oD(e,t){return tD(e=ae(e),t)}function cD(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:N(i,e.app.options.projectId))}(e,t,n,r)}function lD(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new rD(n,r,i,t,Ye)}ze(new oe("storage",lD,"PUBLIC").setMultipleInstances(!0)),et(iD,"0.9.13",""),et(iD,"0.9.13","esm2017");class uD{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}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 hD{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 uD(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new uD(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new uD(e,this,this._ref)):{next:t.next?e=>t.next(new uD(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class dD{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new pD(e,this._service))}get items(){return this._delegate.items.map(e=>new pD(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class pD{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=Zx(this._delegate,e);return new pD(t,this.storage)}get root(){return new pD(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new pD(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new hD(sD(this._delegate,e,t),this)}putString(e,t=ax.RAW,n){this._throwIfRoot("putString");var r=cx(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new hD(new zx(this._delegate,new dx(r.data,!0),i),this)}listAll(){return Hx(ae(this._delegate)).then(e=>new dD(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,Qx(t=ae(t),e).then(e=>new dD(e,this.storage));var t}getMetadata(){return aD(this._delegate)}updateMetadata(e){return Yx(ae(this._delegate),e)}getDownloadURL(){return Jx(ae(this._delegate))}delete(){return this._throwIfRoot("delete"),Xx(ae(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw WR(e)}}class fD{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(gD(e))throw KR("ref() expected a child path but got a URL, use refFromURL instead.");return new pD(oD(this._delegate,e),this)}refFromURL(e){if(!gD(e))throw KR("refFromURL() expected a full URL but got a child path, use ref() instead.");try{HR.makeFromUrl(e,this._delegate.host)}catch(e){throw KR("refFromUrl() expected a valid full URL but got an invalid one.")}return new pD(oD(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){cD(this._delegate,e,t,n)}}function gD(e){return/^[A-Za-z]+:\/\//.test(e)}function mD(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new fD(n,r)}RR=wt,xR={TaskState:Vx,TaskEvent:qx,StringFormat:ax,Storage:fD,Reference:pD},RR.INTERNAL.registerComponent(new oe("storage-compat",mD,"PUBLIC").setServiceProps(xR).setMultipleInstances(!0)),RR.registerVersion("@firebase/storage-compat","0.1.21");const vD="@firebase/performance",yD="0.5.16",_D=yD,wD="FB-PERF-TRACE-MEASURE",bD="@firebase/performance/config",ID="@firebase/performance/configexpire";var TD,ED,kD,SD="Performance";const CD=new x("performance",SD,{"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."}),AD=new me(SD);AD.logLevel=k.INFO;let ND,RD;class xD{constructor(e){if(!(this.window=e))throw CD.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)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}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&&_()?!!v()||(AD.info("IndexedDB is not supported by current browswer"),!1):(AD.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===ND&&(ND=new xD(RD)),ND}}let DD;function PD(e,t){var n=e.length-t.length;if(n<0||1<n)throw CD.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let OD;class MD{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=PD("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=PD("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 void 0===OD&&(OD=new MD),OD}}(It=TD=TD||{})[It.UNKNOWN=0]="UNKNOWN",It[It.VISIBLE=1]="VISIBLE",It[It.HIDDEN=2]="HIDDEN";const LD=["firebase_","google_","ga_"],FD=new RegExp("^[a-zA-Z]\\w*$");function UD(){switch(xD.getInstance().document.visibilityState){case"visible":return TD.VISIBLE;case"hidden":return TD.HIDDEN;default:return TD.UNKNOWN}}function qD(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw CD.create("no app id");return t}const VD="0.0.1",BD={loggingEnabled:!0},jD="FIREBASE_INSTALLATIONS_AUTH";function KD(e,t){var r,i,n=function(){const e=xD.getInstance().localStorage;if(e){var t=e.getItem(ID);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(bD);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(WD(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw CD.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw CD.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${jD} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:qD(r.app),app_version:_D,sdk_version:VD})});return fetch(n).then(e=>{if(e.ok)return e.json();throw CD.create("RC response not ok")})}).catch(()=>{AD.info($D)}).then(WD).then(e=>function(e){const t=xD.getInstance().localStorage;e&&t&&(t.setItem(bD,JSON.stringify(e)),t.setItem(ID,String(Date.now()+60*MD.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const $D="Could not fetch config, will use default configs";function WD(e){if(!e)return e;const t=MD.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=BD.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):BD.logSource&&(t.logSource=BD.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:BD.logEndPointUrl&&(t.logEndPointUrl=BD.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:BD.transportKey&&(t.transportKey=BD.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==BD.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=BD.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==BD.tracesSamplingRate&&(t.tracesSamplingRate=BD.tracesSamplingRate),t.logTraceAfterSampling=zD(t.tracesSamplingRate),t.logNetworkAfterSampling=zD(t.networkRequestsSamplingRate),e}function zD(e){return Math.random()<=e}let GD=1,HD;function QD(e){var t;return GD=2,HD=HD||(t=e,function(){const n=xD.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{DD=e}),t}(t.installations)).then(e=>KD(t,e)).then(()=>YD(),()=>YD())),HD}function YD(){GD=3}const JD=1e4,XD=3,ZD=1e3;let eP=XD,tP=[],nP=!1;function rP(e){setTimeout(()=>{if(0!==eP)return tP.length?void function(){const e=tP.splice(0,ZD),t=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:MD.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=MD.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||AD.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=JD;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(tP=[...r,...tP],AD.info("Retry transport request later.")),eP=XD,rP(n)})}(n,e).catch(()=>{tP=[...e,...tP],eP--,AD.info(`Tries left: ${eP}.`),rP(JD)})}():rP(JD)},e)}function iP(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw CD.create("invalid cc log");tP=[...tP,e]}({message:t(...e),eventTime:Date.now()})}}let sP;function aP(e,t){sP=sP||iP(lP),sP(e,t)}function oP(e){var t=MD.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&xD.getInstance().requiredApisAvailable()&&(e.isAuto&&UD()!==TD.VISIBLE||(3===GD?cP(e):QD(e.performanceController).then(()=>cP(e),()=>cP(e))))}function cP(e){var t;!DD||(t=MD.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>aP(e,1),0)}function lP(e,t){return 0===t?(n={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},n={application_info:uP(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:uP(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function uP(e){return{google_app_id:qD(e),app_instance_id:DD,web_app_info:{sdk_version:_D,page_url:xD.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=xD.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:UD(),effective_connection_type:function(){var e=xD.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}const hP=["_fp","_fcp","_fid"];class dP{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=xD.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=r||`${wD}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw CD.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw CD.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(),oP(this)}record(e,t,n){if(e<=0)throw CD.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw CD.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));oP(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(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<hP.indexOf(r))&&r.startsWith("_"))throw CD.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&AD.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!LD.some(e=>n.startsWith(e))&&!!n.match(FD)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw CD.create("invalid attribute name",{attributeName:e});if(!s)throw CD.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,n,r){var i=xD.getInstance().getUrl();if(i){const s=new dP(e,"_wt_"+i,!0);i=Math.floor(1e3*xD.getInstance().getTimeOrigin());s.setStartTime(i),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)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),oP(s)}}static createUserTimingTrace(e,t){oP(new dP(e,t,!1,t))}}function pP(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=xD.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=MD.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>aP(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const fP=5e3;function gP(e){DD&&(setTimeout(()=>function(n){const e=xD.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{dP.createOobTrace(n,r,i),t=void 0},fP);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),dP.createOobTrace(n,r,i,e))})}else dP.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=xD.getInstance(),n=e.getEntriesByType("resource");for(const r of n)pP(t,r);e.setupObserver("resource",e=>pP(t,e))}(e),0),setTimeout(()=>function(t){const e=xD.getInstance(),n=e.getEntriesByType("measure");for(const r of n)mP(t,r);e.setupObserver("measure",e=>mP(t,e))}(e),0))}function mP(e,t){const n=t.name;n.substring(0,wD.length)!==wD&&dP.createUserTimingTrace(e,n)}class vP{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),xD.getInstance().requiredApisAvailable()?y().then(e=>{e&&(nP||(rP(5500),nP=!0),QD(this).then(()=>gP(this),()=>gP(this)),this.initialized=!0)}).catch(e=>{AD.info(`Environment doesn't support IndexedDB: ${e}`)}):AD.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){MD.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return MD.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){MD.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return MD.getInstance().dataCollectionEnabled}}const yP="[DEFAULT]";const _P=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==yP)throw CD.create("FB not default");if("undefined"==typeof window)throw CD.create("no window");e=window,RD=e;const i=new vP(n,r);return i._init(t),i};ze(new oe("performance",_P,"PUBLIC")),et(vD,yD),et(vD,yD,"esm2017");class wP{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=ae(t),new dP(t,e);var t}}function bP(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new wP(t,n)}(ED=wt).INTERNAL.registerComponent(new oe("performance-compat",bP,"PUBLIC")),ED.registerVersion("@firebase/performance-compat","0.1.16");const IP="@firebase/remote-config";class TP{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const EP=new x("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"});const kP=["1","true","t","yes","y","on"];class SP{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=kP.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function CP(e){const t=ae(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function AP(e){const t=ae(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function NP(t){const n=ae(t),e=new TP;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof R&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function RP(n){const e=ae(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=xP(n,t),e),{});var t,r}function xP(e,t){const n=ae(e);n._isInitializationComplete||n._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.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new SP("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new SP("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new SP("static"))}class DP{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class PP{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=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":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let a;try{await Promise.race([i,r]),a=await i}catch(e){let t="fetch-client-network";throw"AbortError"===(null===e||void 0===e?void 0:e.name)&&(t="fetch-timeout"),EP.create(t,{originalErrorMessage:null===e||void 0===e?void 0:e.message})}let o=a.status;i=a.headers.get("ETag")||void 0;let c,l;if(200===a.status){let e;try{e=await a.json()}catch(e){throw EP.create("fetch-client-parse",{originalErrorMessage:null===e||void 0===e?void 0:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?o=500:"NO_CHANGE"===l?o=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==o&&200!==o)throw EP.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:c}}}class OP{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:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(EP.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof R&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+se(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class MP{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function LP(e,t){var n=e.target.error||void 0;return EP.create(t,{originalErrorMessage:n&&(null===n||void 0===n?void 0:n.message)})}const FP="app_namespace_store";class UP{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(LP(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(FP,{keyPath:"compositeKey"})}}catch(e){n(EP.create("storage-open",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}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")}async get(a){const o=await this.openDbPromise;return new Promise((n,t)=>{const e=o.transaction([FP],"readonly"),r=e.objectStore(FP);var i=this.createCompositeKey(a);try{const s=r.get(i);s.onerror=e=>{t(LP(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(EP.create("storage-get",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}async set(a,o){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([FP],"readwrite"),r=n.objectStore(FP);var i=this.createCompositeKey(a);try{const s=r.put({compositeKey:i,value:o});s.onerror=e=>{t(LP(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(EP.create("storage-set",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}async delete(a){const o=await this.openDbPromise;return new Promise((e,t)=>{const n=o.transaction([FP],"readwrite"),r=n.objectStore(FP);var i=this.createCompositeKey(a);try{const s=r.delete(i);s.onerror=e=>{t(LP(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(EP.create("storage-delete",{originalErrorMessage:null===e||void 0===e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class qP{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}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 function VP(){if(!v())return!1;try{return await y()}catch(e){return!1}}ze(new oe("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw EP.create("registration-window");if(!v())throw EP.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=n.options;if(!i)throw EP.create("registration-project-id");if(!s)throw EP.create("registration-api-key");if(!a)throw EP.create("registration-app-id");t=t||"firebase";const o=new UP(a,n.name,t),c=new qP(o),l=new me(IP);l.logLevel=k.ERROR;a=new PP(r,Ye,t,i,s,a),a=new OP(a,o),a=new DP(a,o,c,l),a=new MP(n,a,c,o,l);return AP(a),a},"PUBLIC").setMultipleInstances(!0)),et(IP,"0.3.15"),et(IP,"0.3.15","esm2017");class BP{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 CP(this._delegate)}ensureInitialized(){return AP(this._delegate)}fetch(){return NP(this._delegate)}fetchAndActivate(){return async function(e){return await NP(e=ae(e)),CP(e)}(this._delegate)}getAll(){return RP(this._delegate)}getBoolean(e){return xP(ae(this._delegate),e).asBoolean()}getNumber(e){return xP(ae(this._delegate),e).asNumber()}getString(e){return xP(ae(this._delegate),e).asString()}getValue(e){return xP(this._delegate,e)}setLogLevel(e){!function(e,t){const n=ae(e);switch(t){case"debug":n._logger.logLevel=k.DEBUG;break;case"silent":n._logger.logLevel=k.SILENT;break;default:n._logger.logLevel=k.ERROR}}(this._delegate,e)}}function jP(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new BP(n,r)}return(kD=wt).INTERNAL.registerComponent(new oe("remoteConfig-compat",jP,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:VP})),kD.registerVersion("@firebase/remote-config-compat","0.1.16"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),wt.registerVersion("firebase","9.13.0","compat-cdn"),wt});
10
10
  //# sourceMappingURL=firebase-compat.js.map