@entropic-bond/firebase 1.13.21 → 1.13.23

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.
@@ -1,4 +1,4 @@
1
- (function(Ue,or){typeof exports=="object"&&typeof module<"u"?or(exports):typeof define=="function"&&define.amd?define(["exports"],or):(Ue=typeof globalThis<"u"?globalThis:Ue||self,or(Ue["entropic-bond-firebase"]={}))})(this,function(Ue){"use strict";const or=()=>{};const dc=function(n){const e=[];let t=0;for(let r=0;r<n.length;r++){let s=n.charCodeAt(r);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&r+1<n.length&&(n.charCodeAt(r+1)&64512)===56320?(s=65536+((s&1023)<<10)+(n.charCodeAt(++r)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},fp=function(n){const e=[];let t=0,r=0;for(;t<n.length;){const s=n[t++];if(s<128)e[r++]=String.fromCharCode(s);else if(s>191&&s<224){const i=n[t++];e[r++]=String.fromCharCode((s&31)<<6|i&63)}else if(s>239&&s<365){const i=n[t++],a=n[t++],c=n[t++],l=((s&7)<<18|(i&63)<<12|(a&63)<<6|c&63)-65536;e[r++]=String.fromCharCode(55296+(l>>10)),e[r++]=String.fromCharCode(56320+(l&1023))}else{const i=n[t++],a=n[t++];e[r++]=String.fromCharCode((s&15)<<12|(i&63)<<6|a&63)}}return e.join("")},fc={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:typeof atob=="function",encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();const t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let s=0;s<n.length;s+=3){const i=n[s],a=s+1<n.length,c=a?n[s+1]:0,l=s+2<n.length,d=l?n[s+2]:0,f=i>>2,m=(i&3)<<4|c>>4;let g=(c&15)<<2|d>>6,R=d&63;l||(R=64,a||(g=64)),r.push(t[f],t[m],t[g],t[R])}return r.join("")},encodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(n):this.encodeByteArray(dc(n),e)},decodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(n):fp(this.decodeStringToByteArray(n,e))},decodeStringToByteArray(n,e){this.init_();const t=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let s=0;s<n.length;){const i=t[n.charAt(s++)],c=s<n.length?t[n.charAt(s)]:0;++s;const d=s<n.length?t[n.charAt(s)]:64;++s;const m=s<n.length?t[n.charAt(s)]:64;if(++s,i==null||c==null||d==null||m==null)throw new pp;const g=i<<2|c>>4;if(r.push(g),d!==64){const R=c<<4&240|d>>2;if(r.push(R),m!==64){const C=d<<6&192|m;r.push(C)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let n=0;n<this.ENCODED_VALS.length;n++)this.byteToCharMap_[n]=this.ENCODED_VALS.charAt(n),this.charToByteMap_[this.byteToCharMap_[n]]=n,this.byteToCharMapWebSafe_[n]=this.ENCODED_VALS_WEBSAFE.charAt(n),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[n]]=n,n>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(n)]=n,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(n)]=n)}}};class pp extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const mp=function(n){const e=dc(n);return fc.encodeByteArray(e,!0)},cs=function(n){return mp(n).replace(/\./g,"")},pc=function(n){try{return fc.decodeString(n,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function gp(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}const _p=()=>gp().__FIREBASE_DEFAULTS__,yp=()=>{if(typeof process>"u"||typeof process.env>"u")return;const n=process.env.__FIREBASE_DEFAULTS__;if(n)return JSON.parse(n)},Ep=()=>{if(typeof document>"u")return;let n;try{n=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=n&&pc(n[1]);return e&&JSON.parse(e)},us=()=>{try{return or()||_p()||yp()||Ep()}catch(n){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${n}`);return}},mc=n=>us()?.emulatorHosts?.[n],ji=n=>{const e=mc(n);if(!e)return;const t=e.lastIndexOf(":");if(t<=0||t+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const r=parseInt(e.substring(t+1),10);return e[0]==="["?[e.substring(1,t-1),r]:[e.substring(0,t),r]},gc=()=>us()?.config,_c=n=>us()?.[`_${n}`];class Tp{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(t):e(t,r))}}}function tt(n){try{return(n.startsWith("http://")||n.startsWith("https://")?new URL(n).hostname:n).endsWith(".cloudworkstations.dev")}catch{return!1}}async function ls(n){return(await fetch(n,{credentials:"include"})).ok}function yc(n,e){if(n.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const t={alg:"none",type:"JWT"},r=e||"demo-project",s=n.iat||0,i=n.sub||n.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const a={iss:`https://securetoken.google.com/${r}`,aud:r,iat:s,exp:s+3600,auth_time:s,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...n};return[cs(JSON.stringify(t)),cs(JSON.stringify(a)),""].join(".")}const ar={};function wp(){const n={prod:[],emulator:[]};for(const e of Object.keys(ar))ar[e]?n.emulator.push(e):n.prod.push(e);return n}function Ip(n){let e=document.getElementById(n),t=!1;return e||(e=document.createElement("div"),e.setAttribute("id",n),t=!0),{created:t,element:e}}let Ec=!1;function hs(n,e){if(typeof window>"u"||typeof document>"u"||!tt(window.location.host)||ar[n]===e||ar[n]||Ec)return;ar[n]=e;function t(g){return`__firebase__banner__${g}`}const r="__firebase__banner",i=wp().prod.length>0;function a(){const g=document.getElementById(r);g&&g.remove()}function c(g){g.style.display="flex",g.style.background="#7faaf0",g.style.position="fixed",g.style.bottom="5px",g.style.left="5px",g.style.padding=".5em",g.style.borderRadius="5px",g.style.alignItems="center"}function l(g,R){g.setAttribute("width","24"),g.setAttribute("id",R),g.setAttribute("height","24"),g.setAttribute("viewBox","0 0 24 24"),g.setAttribute("fill","none"),g.style.marginLeft="-6px"}function d(){const g=document.createElement("span");return g.style.cursor="pointer",g.style.marginLeft="16px",g.style.fontSize="24px",g.innerHTML=" &times;",g.onclick=()=>{Ec=!0,a()},g}function f(g,R){g.setAttribute("id",R),g.innerText="Learn more",g.href="https://firebase.google.com/docs/studio/preview-apps#preview-backend",g.setAttribute("target","__blank"),g.style.paddingLeft="5px",g.style.textDecoration="underline"}function m(){const g=Ip(r),R=t("text"),C=document.getElementById(R)||document.createElement("span"),N=t("learnmore"),k=document.getElementById(N)||document.createElement("a"),F=t("preprendIcon"),$=document.getElementById(F)||document.createElementNS("http://www.w3.org/2000/svg","svg");if(g.created){const j=g.element;c(j),f(k,N);const J=d();l($,F),j.append($,C,k,J),document.body.appendChild(j)}i?(C.innerText="Preview backend disconnected.",$.innerHTML=`<g clip-path="url(#clip0_6013_33858)">
1
+ (function(Ue,or){typeof exports=="object"&&typeof module<"u"?or(exports):typeof define=="function"&&define.amd?define(["exports"],or):(Ue=typeof globalThis<"u"?globalThis:Ue||self,or(Ue["entropic-bond-firebase"]={}))})(this,function(Ue){"use strict";const or=()=>{};const dc=function(n){const e=[];let t=0;for(let r=0;r<n.length;r++){let s=n.charCodeAt(r);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&r+1<n.length&&(n.charCodeAt(r+1)&64512)===56320?(s=65536+((s&1023)<<10)+(n.charCodeAt(++r)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},fp=function(n){const e=[];let t=0,r=0;for(;t<n.length;){const s=n[t++];if(s<128)e[r++]=String.fromCharCode(s);else if(s>191&&s<224){const i=n[t++];e[r++]=String.fromCharCode((s&31)<<6|i&63)}else if(s>239&&s<365){const i=n[t++],a=n[t++],c=n[t++],l=((s&7)<<18|(i&63)<<12|(a&63)<<6|c&63)-65536;e[r++]=String.fromCharCode(55296+(l>>10)),e[r++]=String.fromCharCode(56320+(l&1023))}else{const i=n[t++],a=n[t++];e[r++]=String.fromCharCode((s&15)<<12|(i&63)<<6|a&63)}}return e.join("")},fc={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:typeof atob=="function",encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();const t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let s=0;s<n.length;s+=3){const i=n[s],a=s+1<n.length,c=a?n[s+1]:0,l=s+2<n.length,d=l?n[s+2]:0,f=i>>2,m=(i&3)<<4|c>>4;let _=(c&15)<<2|d>>6,R=d&63;l||(R=64,a||(_=64)),r.push(t[f],t[m],t[_],t[R])}return r.join("")},encodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(n):this.encodeByteArray(dc(n),e)},decodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(n):fp(this.decodeStringToByteArray(n,e))},decodeStringToByteArray(n,e){this.init_();const t=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let s=0;s<n.length;){const i=t[n.charAt(s++)],c=s<n.length?t[n.charAt(s)]:0;++s;const d=s<n.length?t[n.charAt(s)]:64;++s;const m=s<n.length?t[n.charAt(s)]:64;if(++s,i==null||c==null||d==null||m==null)throw new pp;const _=i<<2|c>>4;if(r.push(_),d!==64){const R=c<<4&240|d>>2;if(r.push(R),m!==64){const S=d<<6&192|m;r.push(S)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let n=0;n<this.ENCODED_VALS.length;n++)this.byteToCharMap_[n]=this.ENCODED_VALS.charAt(n),this.charToByteMap_[this.byteToCharMap_[n]]=n,this.byteToCharMapWebSafe_[n]=this.ENCODED_VALS_WEBSAFE.charAt(n),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[n]]=n,n>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(n)]=n,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(n)]=n)}}};class pp extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const mp=function(n){const e=dc(n);return fc.encodeByteArray(e,!0)},cs=function(n){return mp(n).replace(/\./g,"")},pc=function(n){try{return fc.decodeString(n,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function gp(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}const _p=()=>gp().__FIREBASE_DEFAULTS__,yp=()=>{if(typeof process>"u"||typeof process.env>"u")return;const n=process.env.__FIREBASE_DEFAULTS__;if(n)return JSON.parse(n)},Ep=()=>{if(typeof document>"u")return;let n;try{n=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=n&&pc(n[1]);return e&&JSON.parse(e)},us=()=>{try{return or()||_p()||yp()||Ep()}catch(n){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${n}`);return}},mc=n=>us()?.emulatorHosts?.[n],ji=n=>{const e=mc(n);if(!e)return;const t=e.lastIndexOf(":");if(t<=0||t+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const r=parseInt(e.substring(t+1),10);return e[0]==="["?[e.substring(1,t-1),r]:[e.substring(0,t),r]},gc=()=>us()?.config,_c=n=>us()?.[`_${n}`];class Tp{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(t):e(t,r))}}}function tt(n){try{return(n.startsWith("http://")||n.startsWith("https://")?new URL(n).hostname:n).endsWith(".cloudworkstations.dev")}catch{return!1}}async function ls(n){return(await fetch(n,{credentials:"include"})).ok}function yc(n,e){if(n.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const t={alg:"none",type:"JWT"},r=e||"demo-project",s=n.iat||0,i=n.sub||n.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const a={iss:`https://securetoken.google.com/${r}`,aud:r,iat:s,exp:s+3600,auth_time:s,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...n};return[cs(JSON.stringify(t)),cs(JSON.stringify(a)),""].join(".")}const ar={};function wp(){const n={prod:[],emulator:[]};for(const e of Object.keys(ar))ar[e]?n.emulator.push(e):n.prod.push(e);return n}function Ip(n){let e=document.getElementById(n),t=!1;return e||(e=document.createElement("div"),e.setAttribute("id",n),t=!0),{created:t,element:e}}let Ec=!1;function hs(n,e){if(typeof window>"u"||typeof document>"u"||!tt(window.location.host)||ar[n]===e||ar[n]||Ec)return;ar[n]=e;function t(_){return`__firebase__banner__${_}`}const r="__firebase__banner",i=wp().prod.length>0;function a(){const _=document.getElementById(r);_&&_.remove()}function c(_){_.style.display="flex",_.style.background="#7faaf0",_.style.position="fixed",_.style.bottom="5px",_.style.left="5px",_.style.padding=".5em",_.style.borderRadius="5px",_.style.alignItems="center"}function l(_,R){_.setAttribute("width","24"),_.setAttribute("id",R),_.setAttribute("height","24"),_.setAttribute("viewBox","0 0 24 24"),_.setAttribute("fill","none"),_.style.marginLeft="-6px"}function d(){const _=document.createElement("span");return _.style.cursor="pointer",_.style.marginLeft="16px",_.style.fontSize="24px",_.innerHTML=" &times;",_.onclick=()=>{Ec=!0,a()},_}function f(_,R){_.setAttribute("id",R),_.innerText="Learn more",_.href="https://firebase.google.com/docs/studio/preview-apps#preview-backend",_.setAttribute("target","__blank"),_.style.paddingLeft="5px",_.style.textDecoration="underline"}function m(){const _=Ip(r),R=t("text"),S=document.getElementById(R)||document.createElement("span"),N=t("learnmore"),k=document.getElementById(N)||document.createElement("a"),U=t("preprendIcon"),$=document.getElementById(U)||document.createElementNS("http://www.w3.org/2000/svg","svg");if(_.created){const j=_.element;c(j),f(k,N);const Q=d();l($,U),j.append($,S,k,Q),document.body.appendChild(j)}i?(S.innerText="Preview backend disconnected.",$.innerHTML=`<g clip-path="url(#clip0_6013_33858)">
2
2
  <path d="M4.8 17.6L12 5.6L19.2 17.6H4.8ZM6.91667 16.4H17.0833L12 7.93333L6.91667 16.4ZM12 15.6C12.1667 15.6 12.3056 15.5444 12.4167 15.4333C12.5389 15.3111 12.6 15.1667 12.6 15C12.6 14.8333 12.5389 14.6944 12.4167 14.5833C12.3056 14.4611 12.1667 14.4 12 14.4C11.8333 14.4 11.6889 14.4611 11.5667 14.5833C11.4556 14.6944 11.4 14.8333 11.4 15C11.4 15.1667 11.4556 15.3111 11.5667 15.4333C11.6889 15.5444 11.8333 15.6 12 15.6ZM11.4 13.6H12.6V10.4H11.4V13.6Z" fill="#212121"/>
3
3
  </g>
4
4
  <defs>
@@ -12,42 +12,42 @@
12
12
  <clipPath id="clip0_6083_34804">
13
13
  <rect width="24" height="24" fill="white"/>
14
14
  </clipPath>
15
- </defs>`,C.innerText="Preview backend running in this workspace."),C.setAttribute("id",R)}document.readyState==="loading"?window.addEventListener("DOMContentLoaded",m):m()}function ve(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function vp(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(ve())}function Ap(){const n=us()?.forceEnvironment;if(n==="node")return!0;if(n==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function Rp(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function bp(){const n=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof n=="object"&&n.id!==void 0}function Pp(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Sp(){const n=ve();return n.indexOf("MSIE ")>=0||n.indexOf("Trident/")>=0}function Cp(){return!Ap()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function kp(){try{return typeof indexedDB=="object"}catch{return!1}}function Np(){return new Promise((n,e)=>{try{let t=!0;const r="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(r);s.onsuccess=()=>{s.result.close(),t||self.indexedDB.deleteDatabase(r),n(!0)},s.onupgradeneeded=()=>{t=!1},s.onerror=()=>{e(s.error?.message||"")}}catch(t){e(t)}})}const Dp="FirebaseError";class We extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name=Dp,Object.setPrototypeOf(this,We.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,cr.prototype.create)}}class cr{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],a=i?Op(i,r):"Error",c=`${this.serviceName}: ${a} (${s}).`;return new We(s,c,r)}}function Op(n,e){return n.replace(Vp,(t,r)=>{const s=e[r];return s!=null?String(s):`<${r}?>`})}const Vp=/\{\$([^}]+)}/g;function Lp(n){for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}function en(n,e){if(n===e)return!0;const t=Object.keys(n),r=Object.keys(e);for(const s of t){if(!r.includes(s))return!1;const i=n[s],a=e[s];if(Tc(i)&&Tc(a)){if(!en(i,a))return!1}else if(i!==a)return!1}for(const s of r)if(!t.includes(s))return!1;return!0}function Tc(n){return n!==null&&typeof n=="object"}function ur(n){const e=[];for(const[t,r]of Object.entries(n))Array.isArray(r)?r.forEach(s=>{e.push(encodeURIComponent(t)+"="+encodeURIComponent(s))}):e.push(encodeURIComponent(t)+"="+encodeURIComponent(r));return e.length?"&"+e.join("&"):""}function lr(n){const e={};return n.replace(/^\?/,"").split("&").forEach(r=>{if(r){const[s,i]=r.split("=");e[decodeURIComponent(s)]=decodeURIComponent(i)}}),e}function hr(n){const e=n.indexOf("?");if(!e)return"";const t=n.indexOf("#",e);return n.substring(e,t>0?t:void 0)}function Mp(n,e){const t=new xp(n,e);return t.subscribe.bind(t)}class xp{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(r=>{this.error(r)})}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let s;if(e===void 0&&t===void 0&&r===void 0)throw new Error("Missing Observer.");Up(e,["next","error","complete"])?s=e:s={next:e,error:t,complete:r},s.next===void 0&&(s.next=$i),s.error===void 0&&(s.error=$i),s.complete===void 0&&(s.complete=$i);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?s.error(this.finalError):s.complete()}catch{}}),this.observers.push(s),i}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{t(this.observers[e])}catch(r){typeof console<"u"&&console.error&&console.error(r)}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Up(n,e){if(typeof n!="object"||n===null)return!1;for(const t of e)if(t in n&&typeof n[t]=="function")return!0;return!1}function $i(){}function Q(n){return n&&n._delegate?n._delegate:n}class _t{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const tn="[DEFAULT]";class Fp{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){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new Tp;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{const s=this.getOrInitializeService({instanceIdentifier:t});s&&r.resolve(s)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){const t=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??!1;if(this.isInitialized(t)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:t})}catch(s){if(r)return null;throw s}else{if(r)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(qp(e))try{this.getOrInitializeService({instanceIdentifier:tn})}catch{}for(const[t,r]of this.instancesDeferred.entries()){const s=this.normalizeInstanceIdentifier(t);try{const i=this.getOrInitializeService({instanceIdentifier:s});r.resolve(i)}catch{}}}}clearInstance(e=tn){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(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...e.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=tn){return this.instances.has(e)}getOptions(e=tn){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const s=this.getOrInitializeService({instanceIdentifier:r,options:t});for(const[i,a]of this.instancesDeferred.entries()){const c=this.normalizeInstanceIdentifier(i);r===c&&a.resolve(s)}return s}onInit(e,t){const r=this.normalizeInstanceIdentifier(t),s=this.onInitCallbacks.get(r)??new Set;s.add(e),this.onInitCallbacks.set(r,s);const i=this.instances.get(r);return i&&e(i,r),()=>{s.delete(e)}}invokeOnInitCallbacks(e,t){const r=this.onInitCallbacks.get(t);if(r)for(const s of r)try{s(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:Bp(e),options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}return r||null}normalizeInstanceIdentifier(e=tn){return this.component?this.component.multipleInstances?e:tn:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function Bp(n){return n===tn?void 0:n}function qp(n){return n.instantiationMode==="EAGER"}class jp{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){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new Fp(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}var H;(function(n){n[n.DEBUG=0]="DEBUG",n[n.VERBOSE=1]="VERBOSE",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.SILENT=5]="SILENT"})(H||(H={}));const $p={debug:H.DEBUG,verbose:H.VERBOSE,info:H.INFO,warn:H.WARN,error:H.ERROR,silent:H.SILENT},zp=H.INFO,Hp={[H.DEBUG]:"log",[H.VERBOSE]:"log",[H.INFO]:"info",[H.WARN]:"warn",[H.ERROR]:"error"},Wp=(n,e,...t)=>{if(e<n.logLevel)return;const r=new Date().toISOString(),s=Hp[e];if(s)console[s](`[${r}] ${n.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)};class zi{constructor(e){this.name=e,this._logLevel=zp,this._logHandler=Wp,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in H))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?$p[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")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,H.DEBUG,...e),this._logHandler(this,H.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,H.VERBOSE,...e),this._logHandler(this,H.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,H.INFO,...e),this._logHandler(this,H.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,H.WARN,...e),this._logHandler(this,H.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,H.ERROR,...e),this._logHandler(this,H.ERROR,...e)}}const Gp=(n,e)=>e.some(t=>n instanceof t);let wc,Ic;function Kp(){return wc||(wc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Qp(){return Ic||(Ic=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const vc=new WeakMap,Hi=new WeakMap,Ac=new WeakMap,Wi=new WeakMap,Gi=new WeakMap;function Yp(n){const e=new Promise((t,r)=>{const s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",a)},i=()=>{t(Pt(n.result)),s()},a=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",a)});return e.then(t=>{t instanceof IDBCursor&&vc.set(t,n)}).catch(()=>{}),Gi.set(e,n),e}function Jp(n){if(Hi.has(n))return;const e=new Promise((t,r)=>{const s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",a),n.removeEventListener("abort",a)},i=()=>{t(),s()},a=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",i),n.addEventListener("error",a),n.addEventListener("abort",a)});Hi.set(n,e)}let Ki={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Hi.get(n);if(e==="objectStoreNames")return n.objectStoreNames||Ac.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Pt(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};function Xp(n){Ki=n(Ki)}function Zp(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){const r=n.call(Qi(this),e,...t);return Ac.set(r,e.sort?e.sort():[e]),Pt(r)}:Qp().includes(n)?function(...e){return n.apply(Qi(this),e),Pt(vc.get(this))}:function(...e){return Pt(n.apply(Qi(this),e))}}function em(n){return typeof n=="function"?Zp(n):(n instanceof IDBTransaction&&Jp(n),Gp(n,Kp())?new Proxy(n,Ki):n)}function Pt(n){if(n instanceof IDBRequest)return Yp(n);if(Wi.has(n))return Wi.get(n);const e=em(n);return e!==n&&(Wi.set(n,e),Gi.set(e,n)),e}const Qi=n=>Gi.get(n);function tm(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){const a=indexedDB.open(n,e),c=Pt(a);return r&&a.addEventListener("upgradeneeded",l=>{r(Pt(a.result),l.oldVersion,l.newVersion,Pt(a.transaction),l)}),t&&a.addEventListener("blocked",l=>t(l.oldVersion,l.newVersion,l)),c.then(l=>{i&&l.addEventListener("close",()=>i()),s&&l.addEventListener("versionchange",d=>s(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}const nm=["get","getKey","getAll","getAllKeys","count"],rm=["put","add","delete","clear"],Yi=new Map;function Rc(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Yi.get(e))return Yi.get(e);const t=e.replace(/FromIndex$/,""),r=e!==t,s=rm.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||nm.includes(t)))return;const i=async function(a,...c){const l=this.transaction(a,s?"readwrite":"readonly");let d=l.store;return r&&(d=d.index(c.shift())),(await Promise.all([d[t](...c),s&&l.done]))[0]};return Yi.set(e,i),i}Xp(n=>({...n,get:(e,t,r)=>Rc(e,t)||n.get(e,t,r),has:(e,t)=>!!Rc(e,t)||n.has(e,t)}));class sm{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(im(t)){const r=t.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(t=>t).join(" ")}}function im(n){return n.getComponent()?.type==="VERSION"}const Ji="@firebase/app",bc="0.14.7";const yt=new zi("@firebase/app"),om="@firebase/app-compat",am="@firebase/analytics-compat",cm="@firebase/analytics",um="@firebase/app-check-compat",lm="@firebase/app-check",hm="@firebase/auth",dm="@firebase/auth-compat",fm="@firebase/database",pm="@firebase/data-connect",mm="@firebase/database-compat",gm="@firebase/functions",_m="@firebase/functions-compat",ym="@firebase/installations",Em="@firebase/installations-compat",Tm="@firebase/messaging",wm="@firebase/messaging-compat",Im="@firebase/performance",vm="@firebase/performance-compat",Am="@firebase/remote-config",Rm="@firebase/remote-config-compat",bm="@firebase/storage",Pm="@firebase/storage-compat",Sm="@firebase/firestore",Cm="@firebase/ai",km="@firebase/firestore-compat",Nm="firebase",Dm="12.8.0";const Xi="[DEFAULT]",Om={[Ji]:"fire-core",[om]:"fire-core-compat",[cm]:"fire-analytics",[am]:"fire-analytics-compat",[lm]:"fire-app-check",[um]:"fire-app-check-compat",[hm]:"fire-auth",[dm]:"fire-auth-compat",[fm]:"fire-rtdb",[pm]:"fire-data-connect",[mm]:"fire-rtdb-compat",[gm]:"fire-fn",[_m]:"fire-fn-compat",[ym]:"fire-iid",[Em]:"fire-iid-compat",[Tm]:"fire-fcm",[wm]:"fire-fcm-compat",[Im]:"fire-perf",[vm]:"fire-perf-compat",[Am]:"fire-rc",[Rm]:"fire-rc-compat",[bm]:"fire-gcs",[Pm]:"fire-gcs-compat",[Sm]:"fire-fst",[km]:"fire-fst-compat",[Cm]:"fire-vertex","fire-js":"fire-js",[Nm]:"fire-js-all"};const ds=new Map,Vm=new Map,Zi=new Map;function Pc(n,e){try{n.container.addComponent(e)}catch(t){yt.debug(`Component ${e.name} failed to register with FirebaseApp ${n.name}`,t)}}function St(n){const e=n.name;if(Zi.has(e))return yt.debug(`There were multiple attempts to register component ${e}.`),!1;Zi.set(e,n);for(const t of ds.values())Pc(t,n);for(const t of Vm.values())Pc(t,n);return!0}function dr(n,e){const t=n.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),n.container.getProvider(e)}function Ae(n){return n==null?!1:n.settings!==void 0}const Lm={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Ct=new cr("app","Firebase",Lm);class Mm{constructor(e,t,r){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new _t("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 Ct.create("app-deleted",{appName:this._name})}}const nn=Dm;function Sc(n,e={}){let t=n;typeof e!="object"&&(e={name:e});const r={name:Xi,automaticDataCollectionEnabled:!0,...e},s=r.name;if(typeof s!="string"||!s)throw Ct.create("bad-app-name",{appName:String(s)});if(t||(t=gc()),!t)throw Ct.create("no-options");const i=ds.get(s);if(i){if(en(t,i.options)&&en(r,i.config))return i;throw Ct.create("duplicate-app",{appName:s})}const a=new jp(s);for(const l of Zi.values())a.addComponent(l);const c=new Mm(t,r,a);return ds.set(s,c),c}function fs(n=Xi){const e=ds.get(n);if(!e&&n===Xi&&gc())return Sc();if(!e)throw Ct.create("no-app",{appName:n});return e}function je(n,e,t){let r=Om[n]??n;t&&(r+=`-${t}`);const s=r.match(/\s|\//),i=e.match(/\s|\//);if(s||i){const a=[`Unable to register library "${r}" with version "${e}":`];s&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),s&&i&&a.push("and"),i&&a.push(`version name "${e}" contains illegal characters (whitespace or "/")`),yt.warn(a.join(" "));return}St(new _t(`${r}-version`,()=>({library:r,version:e}),"VERSION"))}const xm="firebase-heartbeat-database",Um=1,fr="firebase-heartbeat-store";let eo=null;function Cc(){return eo||(eo=tm(xm,Um,{upgrade:(n,e)=>{switch(e){case 0:try{n.createObjectStore(fr)}catch(t){console.warn(t)}}}}).catch(n=>{throw Ct.create("idb-open",{originalErrorMessage:n.message})})),eo}async function Fm(n){try{const t=(await Cc()).transaction(fr),r=await t.objectStore(fr).get(Nc(n));return await t.done,r}catch(e){if(e instanceof We)yt.warn(e.message);else{const t=Ct.create("idb-get",{originalErrorMessage:e?.message});yt.warn(t.message)}}}async function kc(n,e){try{const r=(await Cc()).transaction(fr,"readwrite");await r.objectStore(fr).put(e,Nc(n)),await r.done}catch(t){if(t instanceof We)yt.warn(t.message);else{const r=Ct.create("idb-set",{originalErrorMessage:t?.message});yt.warn(r.message)}}}function Nc(n){return`${n.name}!${n.options.appId}`}const Bm=1024,qm=30;class jm{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new zm(t),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{const t=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=Dc();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(s=>s.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:t}),this._heartbeatsCache.heartbeats.length>qm){const s=Hm(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(s,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){yt.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";const e=Dc(),{heartbeatsToSend:t,unsentEntries:r}=$m(this._heartbeatsCache.heartbeats),s=cs(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}catch(e){return yt.warn(e),""}}}function Dc(){return new Date().toISOString().substring(0,10)}function $m(n,e=Bm){const t=[];let r=n.slice();for(const s of n){const i=t.find(a=>a.agent===s.agent);if(i){if(i.dates.push(s.date),Oc(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Oc(t)>e){t.pop();break}r=r.slice(1)}return{heartbeatsToSend:t,unsentEntries:r}}class zm{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return kp()?Np().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const t=await Fm(this.app);return t?.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){const r=await this.read();return kc(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){const r=await this.read();return kc(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}}function Oc(n){return cs(JSON.stringify({version:2,heartbeats:n})).length}function Hm(n){if(n.length===0)return-1;let e=0,t=n[0].date;for(let r=1;r<n.length;r++)n[r].date<t&&(t=n[r].date,e=r);return e}function Wm(n){St(new _t("platform-logger",e=>new sm(e),"PRIVATE")),St(new _t("heartbeat",e=>new jm(e),"PRIVATE")),je(Ji,bc,n),je(Ji,bc,"esm2020"),je("fire-js","")}Wm("");var Vc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var kt,Lc;(function(){var n;function e(w,_){function E(){}E.prototype=_.prototype,w.F=_.prototype,w.prototype=new E,w.prototype.constructor=w,w.D=function(I,T,A){for(var y=Array(arguments.length-2),Me=2;Me<arguments.length;Me++)y[Me-2]=arguments[Me];return _.prototype[T].apply(I,y)}}function t(){this.blockSize=-1}function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}e(r,t),r.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(w,_,E){E||(E=0);const I=Array(16);if(typeof _=="string")for(var T=0;T<16;++T)I[T]=_.charCodeAt(E++)|_.charCodeAt(E++)<<8|_.charCodeAt(E++)<<16|_.charCodeAt(E++)<<24;else for(T=0;T<16;++T)I[T]=_[E++]|_[E++]<<8|_[E++]<<16|_[E++]<<24;_=w.g[0],E=w.g[1],T=w.g[2];let A=w.g[3],y;y=_+(A^E&(T^A))+I[0]+3614090360&4294967295,_=E+(y<<7&4294967295|y>>>25),y=A+(T^_&(E^T))+I[1]+3905402710&4294967295,A=_+(y<<12&4294967295|y>>>20),y=T+(E^A&(_^E))+I[2]+606105819&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(_^T&(A^_))+I[3]+3250441966&4294967295,E=T+(y<<22&4294967295|y>>>10),y=_+(A^E&(T^A))+I[4]+4118548399&4294967295,_=E+(y<<7&4294967295|y>>>25),y=A+(T^_&(E^T))+I[5]+1200080426&4294967295,A=_+(y<<12&4294967295|y>>>20),y=T+(E^A&(_^E))+I[6]+2821735955&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(_^T&(A^_))+I[7]+4249261313&4294967295,E=T+(y<<22&4294967295|y>>>10),y=_+(A^E&(T^A))+I[8]+1770035416&4294967295,_=E+(y<<7&4294967295|y>>>25),y=A+(T^_&(E^T))+I[9]+2336552879&4294967295,A=_+(y<<12&4294967295|y>>>20),y=T+(E^A&(_^E))+I[10]+4294925233&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(_^T&(A^_))+I[11]+2304563134&4294967295,E=T+(y<<22&4294967295|y>>>10),y=_+(A^E&(T^A))+I[12]+1804603682&4294967295,_=E+(y<<7&4294967295|y>>>25),y=A+(T^_&(E^T))+I[13]+4254626195&4294967295,A=_+(y<<12&4294967295|y>>>20),y=T+(E^A&(_^E))+I[14]+2792965006&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(_^T&(A^_))+I[15]+1236535329&4294967295,E=T+(y<<22&4294967295|y>>>10),y=_+(T^A&(E^T))+I[1]+4129170786&4294967295,_=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(_^E))+I[6]+3225465664&4294967295,A=_+(y<<9&4294967295|y>>>23),y=T+(_^E&(A^_))+I[11]+643717713&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^_&(T^A))+I[0]+3921069994&4294967295,E=T+(y<<20&4294967295|y>>>12),y=_+(T^A&(E^T))+I[5]+3593408605&4294967295,_=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(_^E))+I[10]+38016083&4294967295,A=_+(y<<9&4294967295|y>>>23),y=T+(_^E&(A^_))+I[15]+3634488961&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^_&(T^A))+I[4]+3889429448&4294967295,E=T+(y<<20&4294967295|y>>>12),y=_+(T^A&(E^T))+I[9]+568446438&4294967295,_=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(_^E))+I[14]+3275163606&4294967295,A=_+(y<<9&4294967295|y>>>23),y=T+(_^E&(A^_))+I[3]+4107603335&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^_&(T^A))+I[8]+1163531501&4294967295,E=T+(y<<20&4294967295|y>>>12),y=_+(T^A&(E^T))+I[13]+2850285829&4294967295,_=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(_^E))+I[2]+4243563512&4294967295,A=_+(y<<9&4294967295|y>>>23),y=T+(_^E&(A^_))+I[7]+1735328473&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^_&(T^A))+I[12]+2368359562&4294967295,E=T+(y<<20&4294967295|y>>>12),y=_+(E^T^A)+I[5]+4294588738&4294967295,_=E+(y<<4&4294967295|y>>>28),y=A+(_^E^T)+I[8]+2272392833&4294967295,A=_+(y<<11&4294967295|y>>>21),y=T+(A^_^E)+I[11]+1839030562&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^_)+I[14]+4259657740&4294967295,E=T+(y<<23&4294967295|y>>>9),y=_+(E^T^A)+I[1]+2763975236&4294967295,_=E+(y<<4&4294967295|y>>>28),y=A+(_^E^T)+I[4]+1272893353&4294967295,A=_+(y<<11&4294967295|y>>>21),y=T+(A^_^E)+I[7]+4139469664&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^_)+I[10]+3200236656&4294967295,E=T+(y<<23&4294967295|y>>>9),y=_+(E^T^A)+I[13]+681279174&4294967295,_=E+(y<<4&4294967295|y>>>28),y=A+(_^E^T)+I[0]+3936430074&4294967295,A=_+(y<<11&4294967295|y>>>21),y=T+(A^_^E)+I[3]+3572445317&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^_)+I[6]+76029189&4294967295,E=T+(y<<23&4294967295|y>>>9),y=_+(E^T^A)+I[9]+3654602809&4294967295,_=E+(y<<4&4294967295|y>>>28),y=A+(_^E^T)+I[12]+3873151461&4294967295,A=_+(y<<11&4294967295|y>>>21),y=T+(A^_^E)+I[15]+530742520&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^_)+I[2]+3299628645&4294967295,E=T+(y<<23&4294967295|y>>>9),y=_+(T^(E|~A))+I[0]+4096336452&4294967295,_=E+(y<<6&4294967295|y>>>26),y=A+(E^(_|~T))+I[7]+1126891415&4294967295,A=_+(y<<10&4294967295|y>>>22),y=T+(_^(A|~E))+I[14]+2878612391&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~_))+I[5]+4237533241&4294967295,E=T+(y<<21&4294967295|y>>>11),y=_+(T^(E|~A))+I[12]+1700485571&4294967295,_=E+(y<<6&4294967295|y>>>26),y=A+(E^(_|~T))+I[3]+2399980690&4294967295,A=_+(y<<10&4294967295|y>>>22),y=T+(_^(A|~E))+I[10]+4293915773&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~_))+I[1]+2240044497&4294967295,E=T+(y<<21&4294967295|y>>>11),y=_+(T^(E|~A))+I[8]+1873313359&4294967295,_=E+(y<<6&4294967295|y>>>26),y=A+(E^(_|~T))+I[15]+4264355552&4294967295,A=_+(y<<10&4294967295|y>>>22),y=T+(_^(A|~E))+I[6]+2734768916&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~_))+I[13]+1309151649&4294967295,E=T+(y<<21&4294967295|y>>>11),y=_+(T^(E|~A))+I[4]+4149444226&4294967295,_=E+(y<<6&4294967295|y>>>26),y=A+(E^(_|~T))+I[11]+3174756917&4294967295,A=_+(y<<10&4294967295|y>>>22),y=T+(_^(A|~E))+I[2]+718787259&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~_))+I[9]+3951481745&4294967295,w.g[0]=w.g[0]+_&4294967295,w.g[1]=w.g[1]+(T+(y<<21&4294967295|y>>>11))&4294967295,w.g[2]=w.g[2]+T&4294967295,w.g[3]=w.g[3]+A&4294967295}r.prototype.v=function(w,_){_===void 0&&(_=w.length);const E=_-this.blockSize,I=this.C;let T=this.h,A=0;for(;A<_;){if(T==0)for(;A<=E;)s(this,w,A),A+=this.blockSize;if(typeof w=="string"){for(;A<_;)if(I[T++]=w.charCodeAt(A++),T==this.blockSize){s(this,I),T=0;break}}else for(;A<_;)if(I[T++]=w[A++],T==this.blockSize){s(this,I),T=0;break}}this.h=T,this.o+=_},r.prototype.A=function(){var w=Array((this.h<56?this.blockSize:this.blockSize*2)-this.h);w[0]=128;for(var _=1;_<w.length-8;++_)w[_]=0;_=this.o*8;for(var E=w.length-8;E<w.length;++E)w[E]=_&255,_/=256;for(this.v(w),w=Array(16),_=0,E=0;E<4;++E)for(let I=0;I<32;I+=8)w[_++]=this.g[E]>>>I&255;return w};function i(w,_){var E=c;return Object.prototype.hasOwnProperty.call(E,w)?E[w]:E[w]=_(w)}function a(w,_){this.h=_;const E=[];let I=!0;for(let T=w.length-1;T>=0;T--){const A=w[T]|0;I&&A==_||(E[T]=A,I=!1)}this.g=E}var c={};function l(w){return-128<=w&&w<128?i(w,function(_){return new a([_|0],_<0?-1:0)}):new a([w|0],w<0?-1:0)}function d(w){if(isNaN(w)||!isFinite(w))return m;if(w<0)return k(d(-w));const _=[];let E=1;for(let I=0;w>=E;I++)_[I]=w/E|0,E*=4294967296;return new a(_,0)}function f(w,_){if(w.length==0)throw Error("number format error: empty string");if(_=_||10,_<2||36<_)throw Error("radix out of range: "+_);if(w.charAt(0)=="-")return k(f(w.substring(1),_));if(w.indexOf("-")>=0)throw Error('number format error: interior "-" character');const E=d(Math.pow(_,8));let I=m;for(let A=0;A<w.length;A+=8){var T=Math.min(8,w.length-A);const y=parseInt(w.substring(A,A+T),_);T<8?(T=d(Math.pow(_,T)),I=I.j(T).add(d(y))):(I=I.j(E),I=I.add(d(y)))}return I}var m=l(0),g=l(1),R=l(16777216);n=a.prototype,n.m=function(){if(N(this))return-k(this).m();let w=0,_=1;for(let E=0;E<this.g.length;E++){const I=this.i(E);w+=(I>=0?I:4294967296+I)*_,_*=4294967296}return w},n.toString=function(w){if(w=w||10,w<2||36<w)throw Error("radix out of range: "+w);if(C(this))return"0";if(N(this))return"-"+k(this).toString(w);const _=d(Math.pow(w,6));var E=this;let I="";for(;;){const T=J(E,_).g;E=F(E,T.j(_));let A=((E.g.length>0?E.g[0]:E.h)>>>0).toString(w);if(E=T,C(E))return A+I;for(;A.length<6;)A="0"+A;I=A+I}},n.i=function(w){return w<0?0:w<this.g.length?this.g[w]:this.h};function C(w){if(w.h!=0)return!1;for(let _=0;_<w.g.length;_++)if(w.g[_]!=0)return!1;return!0}function N(w){return w.h==-1}n.l=function(w){return w=F(this,w),N(w)?-1:C(w)?0:1};function k(w){const _=w.g.length,E=[];for(let I=0;I<_;I++)E[I]=~w.g[I];return new a(E,~w.h).add(g)}n.abs=function(){return N(this)?k(this):this},n.add=function(w){const _=Math.max(this.g.length,w.g.length),E=[];let I=0;for(let T=0;T<=_;T++){let A=I+(this.i(T)&65535)+(w.i(T)&65535),y=(A>>>16)+(this.i(T)>>>16)+(w.i(T)>>>16);I=y>>>16,A&=65535,y&=65535,E[T]=y<<16|A}return new a(E,E[E.length-1]&-2147483648?-1:0)};function F(w,_){return w.add(k(_))}n.j=function(w){if(C(this)||C(w))return m;if(N(this))return N(w)?k(this).j(k(w)):k(k(this).j(w));if(N(w))return k(this.j(k(w)));if(this.l(R)<0&&w.l(R)<0)return d(this.m()*w.m());const _=this.g.length+w.g.length,E=[];for(var I=0;I<2*_;I++)E[I]=0;for(I=0;I<this.g.length;I++)for(let T=0;T<w.g.length;T++){const A=this.i(I)>>>16,y=this.i(I)&65535,Me=w.i(T)>>>16,En=w.i(T)&65535;E[2*I+2*T]+=y*En,$(E,2*I+2*T),E[2*I+2*T+1]+=A*En,$(E,2*I+2*T+1),E[2*I+2*T+1]+=y*Me,$(E,2*I+2*T+1),E[2*I+2*T+2]+=A*Me,$(E,2*I+2*T+2)}for(w=0;w<_;w++)E[w]=E[2*w+1]<<16|E[2*w];for(w=_;w<2*_;w++)E[w]=0;return new a(E,0)};function $(w,_){for(;(w[_]&65535)!=w[_];)w[_+1]+=w[_]>>>16,w[_]&=65535,_++}function j(w,_){this.g=w,this.h=_}function J(w,_){if(C(_))throw Error("division by zero");if(C(w))return new j(m,m);if(N(w))return _=J(k(w),_),new j(k(_.g),k(_.h));if(N(_))return _=J(w,k(_)),new j(k(_.g),_.h);if(w.g.length>30){if(N(w)||N(_))throw Error("slowDivide_ only works with positive integers.");for(var E=g,I=_;I.l(w)<=0;)E=_e(E),I=_e(I);var T=re(E,1),A=re(I,1);for(I=re(I,2),E=re(E,2);!C(I);){var y=A.add(I);y.l(w)<=0&&(T=T.add(E),A=y),I=re(I,1),E=re(E,1)}return _=F(w,T.j(_)),new j(T,_)}for(T=m;w.l(_)>=0;){for(E=Math.max(1,Math.floor(w.m()/_.m())),I=Math.ceil(Math.log(E)/Math.LN2),I=I<=48?1:Math.pow(2,I-48),A=d(E),y=A.j(_);N(y)||y.l(w)>0;)E-=I,A=d(E),y=A.j(_);C(A)&&(A=g),T=T.add(A),w=F(w,y)}return new j(T,w)}n.B=function(w){return J(this,w).h},n.and=function(w){const _=Math.max(this.g.length,w.g.length),E=[];for(let I=0;I<_;I++)E[I]=this.i(I)&w.i(I);return new a(E,this.h&w.h)},n.or=function(w){const _=Math.max(this.g.length,w.g.length),E=[];for(let I=0;I<_;I++)E[I]=this.i(I)|w.i(I);return new a(E,this.h|w.h)},n.xor=function(w){const _=Math.max(this.g.length,w.g.length),E=[];for(let I=0;I<_;I++)E[I]=this.i(I)^w.i(I);return new a(E,this.h^w.h)};function _e(w){const _=w.g.length+1,E=[];for(let I=0;I<_;I++)E[I]=w.i(I)<<1|w.i(I-1)>>>31;return new a(E,w.h)}function re(w,_){const E=_>>5;_%=32;const I=w.g.length-E,T=[];for(let A=0;A<I;A++)T[A]=_>0?w.i(A+E)>>>_|w.i(A+E+1)<<32-_:w.i(A+E);return new a(T,w.h)}r.prototype.digest=r.prototype.A,r.prototype.reset=r.prototype.u,r.prototype.update=r.prototype.v,Lc=r,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.B,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=d,a.fromString=f,kt=a}).apply(typeof Vc<"u"?Vc:typeof self<"u"?self:typeof window<"u"?window:{});var ps=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var Mc,pr,xc,ms,to,Uc,Fc,Bc;(function(){var n,e=Object.defineProperty;function t(o){o=[typeof globalThis=="object"&&globalThis,o,typeof window=="object"&&window,typeof self=="object"&&self,typeof ps=="object"&&ps];for(var u=0;u<o.length;++u){var h=o[u];if(h&&h.Math==Math)return h}throw Error("Cannot find global object")}var r=t(this);function s(o,u){if(u)e:{var h=r;o=o.split(".");for(var p=0;p<o.length-1;p++){var v=o[p];if(!(v in h))break e;h=h[v]}o=o[o.length-1],p=h[o],u=u(p),u!=p&&u!=null&&e(h,o,{configurable:!0,writable:!0,value:u})}}s("Symbol.dispose",function(o){return o||Symbol("Symbol.dispose")}),s("Array.prototype.values",function(o){return o||function(){return this[Symbol.iterator]()}}),s("Object.entries",function(o){return o||function(u){var h=[],p;for(p in u)Object.prototype.hasOwnProperty.call(u,p)&&h.push([p,u[p]]);return h}});var i=i||{},a=this||self;function c(o){var u=typeof o;return u=="object"&&o!=null||u=="function"}function l(o,u,h){return o.call.apply(o.bind,arguments)}function d(o,u,h){return d=l,d.apply(null,arguments)}function f(o,u){var h=Array.prototype.slice.call(arguments,1);return function(){var p=h.slice();return p.push.apply(p,arguments),o.apply(this,p)}}function m(o,u){function h(){}h.prototype=u.prototype,o.Z=u.prototype,o.prototype=new h,o.prototype.constructor=o,o.Ob=function(p,v,b){for(var O=Array(arguments.length-2),z=2;z<arguments.length;z++)O[z-2]=arguments[z];return u.prototype[v].apply(p,O)}}var g=typeof AsyncContext<"u"&&typeof AsyncContext.Snapshot=="function"?o=>o&&AsyncContext.Snapshot.wrap(o):o=>o;function R(o){const u=o.length;if(u>0){const h=Array(u);for(let p=0;p<u;p++)h[p]=o[p];return h}return[]}function C(o,u){for(let p=1;p<arguments.length;p++){const v=arguments[p];var h=typeof v;if(h=h!="object"?h:v?Array.isArray(v)?"array":h:"null",h=="array"||h=="object"&&typeof v.length=="number"){h=o.length||0;const b=v.length||0;o.length=h+b;for(let O=0;O<b;O++)o[h+O]=v[O]}else o.push(v)}}class N{constructor(u,h){this.i=u,this.j=h,this.h=0,this.g=null}get(){let u;return this.h>0?(this.h--,u=this.g,this.g=u.next,u.next=null):u=this.i(),u}}function k(o){a.setTimeout(()=>{throw o},0)}function F(){var o=w;let u=null;return o.g&&(u=o.g,o.g=o.g.next,o.g||(o.h=null),u.next=null),u}class ${constructor(){this.h=this.g=null}add(u,h){const p=j.get();p.set(u,h),this.h?this.h.next=p:this.g=p,this.h=p}}var j=new N(()=>new J,o=>o.reset());class J{constructor(){this.next=this.g=this.h=null}set(u,h){this.h=u,this.g=h,this.next=null}reset(){this.next=this.g=this.h=null}}let _e,re=!1,w=new $,_=()=>{const o=Promise.resolve(void 0);_e=()=>{o.then(E)}};function E(){for(var o;o=F();){try{o.h.call(o.g)}catch(h){k(h)}var u=j;u.j(o),u.h<100&&(u.h++,o.next=u.g,u.g=o)}re=!1}function I(){this.u=this.u,this.C=this.C}I.prototype.u=!1,I.prototype.dispose=function(){this.u||(this.u=!0,this.N())},I.prototype[Symbol.dispose]=function(){this.dispose()},I.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function T(o,u){this.type=o,this.g=this.target=u,this.defaultPrevented=!1}T.prototype.h=function(){this.defaultPrevented=!0};var A=function(){if(!a.addEventListener||!Object.defineProperty)return!1;var o=!1,u=Object.defineProperty({},"passive",{get:function(){o=!0}});try{const h=()=>{};a.addEventListener("test",h,u),a.removeEventListener("test",h,u)}catch{}return o}();function y(o){return/^[\s\xa0]*$/.test(o)}function Me(o,u){T.call(this,o?o.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,o&&this.init(o,u)}m(Me,T),Me.prototype.init=function(o,u){const h=this.type=o.type,p=o.changedTouches&&o.changedTouches.length?o.changedTouches[0]:null;this.target=o.target||o.srcElement,this.g=u,u=o.relatedTarget,u||(h=="mouseover"?u=o.fromElement:h=="mouseout"&&(u=o.toElement)),this.relatedTarget=u,p?(this.clientX=p.clientX!==void 0?p.clientX:p.pageX,this.clientY=p.clientY!==void 0?p.clientY:p.pageY,this.screenX=p.screenX||0,this.screenY=p.screenY||0):(this.clientX=o.clientX!==void 0?o.clientX:o.pageX,this.clientY=o.clientY!==void 0?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0),this.button=o.button,this.key=o.key||"",this.ctrlKey=o.ctrlKey,this.altKey=o.altKey,this.shiftKey=o.shiftKey,this.metaKey=o.metaKey,this.pointerId=o.pointerId||0,this.pointerType=o.pointerType,this.state=o.state,this.i=o,o.defaultPrevented&&Me.Z.h.call(this)},Me.prototype.h=function(){Me.Z.h.call(this);const o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var En="closure_listenable_"+(Math.random()*1e6|0),eA=0;function tA(o,u,h,p,v){this.listener=o,this.proxy=null,this.src=u,this.type=h,this.capture=!!p,this.ha=v,this.key=++eA,this.da=this.fa=!1}function Pi(o){o.da=!0,o.listener=null,o.proxy=null,o.src=null,o.ha=null}function Si(o,u,h){for(const p in o)u.call(h,o[p],p,o)}function nA(o,u){for(const h in o)u.call(void 0,o[h],h,o)}function hf(o){const u={};for(const h in o)u[h]=o[h];return u}const df="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ff(o,u){let h,p;for(let v=1;v<arguments.length;v++){p=arguments[v];for(h in p)o[h]=p[h];for(let b=0;b<df.length;b++)h=df[b],Object.prototype.hasOwnProperty.call(p,h)&&(o[h]=p[h])}}function Ci(o){this.src=o,this.g={},this.h=0}Ci.prototype.add=function(o,u,h,p,v){const b=o.toString();o=this.g[b],o||(o=this.g[b]=[],this.h++);const O=$a(o,u,p,v);return O>-1?(u=o[O],h||(u.fa=!1)):(u=new tA(u,this.src,b,!!p,v),u.fa=h,o.push(u)),u};function ja(o,u){const h=u.type;if(h in o.g){var p=o.g[h],v=Array.prototype.indexOf.call(p,u,void 0),b;(b=v>=0)&&Array.prototype.splice.call(p,v,1),b&&(Pi(u),o.g[h].length==0&&(delete o.g[h],o.h--))}}function $a(o,u,h,p){for(let v=0;v<o.length;++v){const b=o[v];if(!b.da&&b.listener==u&&b.capture==!!h&&b.ha==p)return v}return-1}var za="closure_lm_"+(Math.random()*1e6|0),Ha={};function pf(o,u,h,p,v){if(Array.isArray(u)){for(let b=0;b<u.length;b++)pf(o,u[b],h,p,v);return null}return h=_f(h),o&&o[En]?o.J(u,h,c(p)?!!p.capture:!1,v):rA(o,u,h,!1,p,v)}function rA(o,u,h,p,v,b){if(!u)throw Error("Invalid event type");const O=c(v)?!!v.capture:!!v;let z=Ga(o);if(z||(o[za]=z=new Ci(o)),h=z.add(u,h,p,O,b),h.proxy)return h;if(p=sA(),h.proxy=p,p.src=o,p.listener=h,o.addEventListener)A||(v=O),v===void 0&&(v=!1),o.addEventListener(u.toString(),p,v);else if(o.attachEvent)o.attachEvent(gf(u.toString()),p);else if(o.addListener&&o.removeListener)o.addListener(p);else throw Error("addEventListener and attachEvent are unavailable.");return h}function sA(){function o(h){return u.call(o.src,o.listener,h)}const u=iA;return o}function mf(o,u,h,p,v){if(Array.isArray(u))for(var b=0;b<u.length;b++)mf(o,u[b],h,p,v);else p=c(p)?!!p.capture:!!p,h=_f(h),o&&o[En]?(o=o.i,b=String(u).toString(),b in o.g&&(u=o.g[b],h=$a(u,h,p,v),h>-1&&(Pi(u[h]),Array.prototype.splice.call(u,h,1),u.length==0&&(delete o.g[b],o.h--)))):o&&(o=Ga(o))&&(u=o.g[u.toString()],o=-1,u&&(o=$a(u,h,p,v)),(h=o>-1?u[o]:null)&&Wa(h))}function Wa(o){if(typeof o!="number"&&o&&!o.da){var u=o.src;if(u&&u[En])ja(u.i,o);else{var h=o.type,p=o.proxy;u.removeEventListener?u.removeEventListener(h,p,o.capture):u.detachEvent?u.detachEvent(gf(h),p):u.addListener&&u.removeListener&&u.removeListener(p),(h=Ga(u))?(ja(h,o),h.h==0&&(h.src=null,u[za]=null)):Pi(o)}}}function gf(o){return o in Ha?Ha[o]:Ha[o]="on"+o}function iA(o,u){if(o.da)o=!0;else{u=new Me(u,this);const h=o.listener,p=o.ha||o.src;o.fa&&Wa(o),o=h.call(p,u)}return o}function Ga(o){return o=o[za],o instanceof Ci?o:null}var Ka="__closure_events_fn_"+(Math.random()*1e9>>>0);function _f(o){return typeof o=="function"?o:(o[Ka]||(o[Ka]=function(u){return o.handleEvent(u)}),o[Ka])}function Se(){I.call(this),this.i=new Ci(this),this.M=this,this.G=null}m(Se,I),Se.prototype[En]=!0,Se.prototype.removeEventListener=function(o,u,h,p){mf(this,o,u,h,p)};function Ne(o,u){var h,p=o.G;if(p)for(h=[];p;p=p.G)h.push(p);if(o=o.M,p=u.type||u,typeof u=="string")u=new T(u,o);else if(u instanceof T)u.target=u.target||o;else{var v=u;u=new T(p,o),ff(u,v)}v=!0;let b,O;if(h)for(O=h.length-1;O>=0;O--)b=u.g=h[O],v=ki(b,p,!0,u)&&v;if(b=u.g=o,v=ki(b,p,!0,u)&&v,v=ki(b,p,!1,u)&&v,h)for(O=0;O<h.length;O++)b=u.g=h[O],v=ki(b,p,!1,u)&&v}Se.prototype.N=function(){if(Se.Z.N.call(this),this.i){var o=this.i;for(const u in o.g){const h=o.g[u];for(let p=0;p<h.length;p++)Pi(h[p]);delete o.g[u],o.h--}}this.G=null},Se.prototype.J=function(o,u,h,p){return this.i.add(String(o),u,!1,h,p)},Se.prototype.K=function(o,u,h,p){return this.i.add(String(o),u,!0,h,p)};function ki(o,u,h,p){if(u=o.i.g[String(u)],!u)return!0;u=u.concat();let v=!0;for(let b=0;b<u.length;++b){const O=u[b];if(O&&!O.da&&O.capture==h){const z=O.listener,me=O.ha||O.src;O.fa&&ja(o.i,O),v=z.call(me,p)!==!1&&v}}return v&&!p.defaultPrevented}function oA(o,u){if(typeof o!="function")if(o&&typeof o.handleEvent=="function")o=d(o.handleEvent,o);else throw Error("Invalid listener argument");return Number(u)>2147483647?-1:a.setTimeout(o,u||0)}function yf(o){o.g=oA(()=>{o.g=null,o.i&&(o.i=!1,yf(o))},o.l);const u=o.h;o.h=null,o.m.apply(null,u)}class aA extends I{constructor(u,h){super(),this.m=u,this.l=h,this.h=null,this.i=!1,this.g=null}j(u){this.h=arguments,this.g?this.i=!0:yf(this)}N(){super.N(),this.g&&(a.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Wr(o){I.call(this),this.h=o,this.g={}}m(Wr,I);var Ef=[];function Tf(o){Si(o.g,function(u,h){this.g.hasOwnProperty(h)&&Wa(u)},o),o.g={}}Wr.prototype.N=function(){Wr.Z.N.call(this),Tf(this)},Wr.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Qa=a.JSON.stringify,cA=a.JSON.parse,uA=class{stringify(o){return a.JSON.stringify(o,void 0)}parse(o){return a.JSON.parse(o,void 0)}};function wf(){}function If(){}var Gr={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function Ya(){T.call(this,"d")}m(Ya,T);function Ja(){T.call(this,"c")}m(Ja,T);var Tn={},vf=null;function Ni(){return vf=vf||new Se}Tn.Ia="serverreachability";function Af(o){T.call(this,Tn.Ia,o)}m(Af,T);function Kr(o){const u=Ni();Ne(u,new Af(u))}Tn.STAT_EVENT="statevent";function Rf(o,u){T.call(this,Tn.STAT_EVENT,o),this.stat=u}m(Rf,T);function De(o){const u=Ni();Ne(u,new Rf(u,o))}Tn.Ja="timingevent";function bf(o,u){T.call(this,Tn.Ja,o),this.size=u}m(bf,T);function Qr(o,u){if(typeof o!="function")throw Error("Fn must not be null and must be a function");return a.setTimeout(function(){o()},u)}function Yr(){this.g=!0}Yr.prototype.ua=function(){this.g=!1};function lA(o,u,h,p,v,b){o.info(function(){if(o.g)if(b){var O="",z=b.split("&");for(let Z=0;Z<z.length;Z++){var me=z[Z].split("=");if(me.length>1){const ye=me[0];me=me[1];const gt=ye.split("_");O=gt.length>=2&&gt[1]=="type"?O+(ye+"="+me+"&"):O+(ye+"=redacted&")}}}else O=null;else O=b;return"XMLHTTP REQ ("+p+") [attempt "+v+"]: "+u+`
15
+ </defs>`,S.innerText="Preview backend running in this workspace."),S.setAttribute("id",R)}document.readyState==="loading"?window.addEventListener("DOMContentLoaded",m):m()}function ve(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function vp(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(ve())}function Ap(){const n=us()?.forceEnvironment;if(n==="node")return!0;if(n==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function Rp(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function bp(){const n=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof n=="object"&&n.id!==void 0}function Pp(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Cp(){const n=ve();return n.indexOf("MSIE ")>=0||n.indexOf("Trident/")>=0}function Sp(){return!Ap()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function kp(){try{return typeof indexedDB=="object"}catch{return!1}}function Np(){return new Promise((n,e)=>{try{let t=!0;const r="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(r);s.onsuccess=()=>{s.result.close(),t||self.indexedDB.deleteDatabase(r),n(!0)},s.onupgradeneeded=()=>{t=!1},s.onerror=()=>{e(s.error?.message||"")}}catch(t){e(t)}})}const Dp="FirebaseError";class We extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name=Dp,Object.setPrototypeOf(this,We.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,cr.prototype.create)}}class cr{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],a=i?Op(i,r):"Error",c=`${this.serviceName}: ${a} (${s}).`;return new We(s,c,r)}}function Op(n,e){return n.replace(Vp,(t,r)=>{const s=e[r];return s!=null?String(s):`<${r}?>`})}const Vp=/\{\$([^}]+)}/g;function Lp(n){for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}function en(n,e){if(n===e)return!0;const t=Object.keys(n),r=Object.keys(e);for(const s of t){if(!r.includes(s))return!1;const i=n[s],a=e[s];if(Tc(i)&&Tc(a)){if(!en(i,a))return!1}else if(i!==a)return!1}for(const s of r)if(!t.includes(s))return!1;return!0}function Tc(n){return n!==null&&typeof n=="object"}function ur(n){const e=[];for(const[t,r]of Object.entries(n))Array.isArray(r)?r.forEach(s=>{e.push(encodeURIComponent(t)+"="+encodeURIComponent(s))}):e.push(encodeURIComponent(t)+"="+encodeURIComponent(r));return e.length?"&"+e.join("&"):""}function lr(n){const e={};return n.replace(/^\?/,"").split("&").forEach(r=>{if(r){const[s,i]=r.split("=");e[decodeURIComponent(s)]=decodeURIComponent(i)}}),e}function hr(n){const e=n.indexOf("?");if(!e)return"";const t=n.indexOf("#",e);return n.substring(e,t>0?t:void 0)}function Mp(n,e){const t=new xp(n,e);return t.subscribe.bind(t)}class xp{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(r=>{this.error(r)})}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let s;if(e===void 0&&t===void 0&&r===void 0)throw new Error("Missing Observer.");Up(e,["next","error","complete"])?s=e:s={next:e,error:t,complete:r},s.next===void 0&&(s.next=$i),s.error===void 0&&(s.error=$i),s.complete===void 0&&(s.complete=$i);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?s.error(this.finalError):s.complete()}catch{}}),this.observers.push(s),i}unsubscribeOne(e){this.observers===void 0||this.observers[e]===void 0||(delete this.observers[e],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then(()=>{if(this.observers!==void 0&&this.observers[e]!==void 0)try{t(this.observers[e])}catch(r){typeof console<"u"&&console.error&&console.error(r)}})}close(e){this.finalized||(this.finalized=!0,e!==void 0&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Up(n,e){if(typeof n!="object"||n===null)return!1;for(const t of e)if(t in n&&typeof n[t]=="function")return!0;return!1}function $i(){}function Y(n){return n&&n._delegate?n._delegate:n}class _t{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const tn="[DEFAULT]";class Fp{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){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new Tp;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{const s=this.getOrInitializeService({instanceIdentifier:t});s&&r.resolve(s)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){const t=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??!1;if(this.isInitialized(t)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:t})}catch(s){if(r)return null;throw s}else{if(r)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(qp(e))try{this.getOrInitializeService({instanceIdentifier:tn})}catch{}for(const[t,r]of this.instancesDeferred.entries()){const s=this.normalizeInstanceIdentifier(t);try{const i=this.getOrInitializeService({instanceIdentifier:s});r.resolve(i)}catch{}}}}clearInstance(e=tn){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(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...e.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=tn){return this.instances.has(e)}getOptions(e=tn){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const s=this.getOrInitializeService({instanceIdentifier:r,options:t});for(const[i,a]of this.instancesDeferred.entries()){const c=this.normalizeInstanceIdentifier(i);r===c&&a.resolve(s)}return s}onInit(e,t){const r=this.normalizeInstanceIdentifier(t),s=this.onInitCallbacks.get(r)??new Set;s.add(e),this.onInitCallbacks.set(r,s);const i=this.instances.get(r);return i&&e(i,r),()=>{s.delete(e)}}invokeOnInitCallbacks(e,t){const r=this.onInitCallbacks.get(t);if(r)for(const s of r)try{s(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:Bp(e),options:t}),this.instances.set(e,r),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r)}catch{}return r||null}normalizeInstanceIdentifier(e=tn){return this.component?this.component.multipleInstances?e:tn:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function Bp(n){return n===tn?void 0:n}function qp(n){return n.instantiationMode==="EAGER"}class jp{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){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new Fp(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}var H;(function(n){n[n.DEBUG=0]="DEBUG",n[n.VERBOSE=1]="VERBOSE",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.SILENT=5]="SILENT"})(H||(H={}));const $p={debug:H.DEBUG,verbose:H.VERBOSE,info:H.INFO,warn:H.WARN,error:H.ERROR,silent:H.SILENT},zp=H.INFO,Hp={[H.DEBUG]:"log",[H.VERBOSE]:"log",[H.INFO]:"info",[H.WARN]:"warn",[H.ERROR]:"error"},Wp=(n,e,...t)=>{if(e<n.logLevel)return;const r=new Date().toISOString(),s=Hp[e];if(s)console[s](`[${r}] ${n.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)};class zi{constructor(e){this.name=e,this._logLevel=zp,this._logHandler=Wp,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in H))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?$p[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")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,H.DEBUG,...e),this._logHandler(this,H.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,H.VERBOSE,...e),this._logHandler(this,H.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,H.INFO,...e),this._logHandler(this,H.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,H.WARN,...e),this._logHandler(this,H.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,H.ERROR,...e),this._logHandler(this,H.ERROR,...e)}}const Gp=(n,e)=>e.some(t=>n instanceof t);let wc,Ic;function Kp(){return wc||(wc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Qp(){return Ic||(Ic=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const vc=new WeakMap,Hi=new WeakMap,Ac=new WeakMap,Wi=new WeakMap,Gi=new WeakMap;function Yp(n){const e=new Promise((t,r)=>{const s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",a)},i=()=>{t(Pt(n.result)),s()},a=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",a)});return e.then(t=>{t instanceof IDBCursor&&vc.set(t,n)}).catch(()=>{}),Gi.set(e,n),e}function Jp(n){if(Hi.has(n))return;const e=new Promise((t,r)=>{const s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",a),n.removeEventListener("abort",a)},i=()=>{t(),s()},a=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",i),n.addEventListener("error",a),n.addEventListener("abort",a)});Hi.set(n,e)}let Ki={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Hi.get(n);if(e==="objectStoreNames")return n.objectStoreNames||Ac.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Pt(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};function Xp(n){Ki=n(Ki)}function Zp(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){const r=n.call(Qi(this),e,...t);return Ac.set(r,e.sort?e.sort():[e]),Pt(r)}:Qp().includes(n)?function(...e){return n.apply(Qi(this),e),Pt(vc.get(this))}:function(...e){return Pt(n.apply(Qi(this),e))}}function em(n){return typeof n=="function"?Zp(n):(n instanceof IDBTransaction&&Jp(n),Gp(n,Kp())?new Proxy(n,Ki):n)}function Pt(n){if(n instanceof IDBRequest)return Yp(n);if(Wi.has(n))return Wi.get(n);const e=em(n);return e!==n&&(Wi.set(n,e),Gi.set(e,n)),e}const Qi=n=>Gi.get(n);function tm(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){const a=indexedDB.open(n,e),c=Pt(a);return r&&a.addEventListener("upgradeneeded",l=>{r(Pt(a.result),l.oldVersion,l.newVersion,Pt(a.transaction),l)}),t&&a.addEventListener("blocked",l=>t(l.oldVersion,l.newVersion,l)),c.then(l=>{i&&l.addEventListener("close",()=>i()),s&&l.addEventListener("versionchange",d=>s(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}const nm=["get","getKey","getAll","getAllKeys","count"],rm=["put","add","delete","clear"],Yi=new Map;function Rc(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Yi.get(e))return Yi.get(e);const t=e.replace(/FromIndex$/,""),r=e!==t,s=rm.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||nm.includes(t)))return;const i=async function(a,...c){const l=this.transaction(a,s?"readwrite":"readonly");let d=l.store;return r&&(d=d.index(c.shift())),(await Promise.all([d[t](...c),s&&l.done]))[0]};return Yi.set(e,i),i}Xp(n=>({...n,get:(e,t,r)=>Rc(e,t)||n.get(e,t,r),has:(e,t)=>!!Rc(e,t)||n.has(e,t)}));class sm{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(im(t)){const r=t.getImmediate();return`${r.library}/${r.version}`}else return null}).filter(t=>t).join(" ")}}function im(n){return n.getComponent()?.type==="VERSION"}const Ji="@firebase/app",bc="0.14.9";const yt=new zi("@firebase/app"),om="@firebase/app-compat",am="@firebase/analytics-compat",cm="@firebase/analytics",um="@firebase/app-check-compat",lm="@firebase/app-check",hm="@firebase/auth",dm="@firebase/auth-compat",fm="@firebase/database",pm="@firebase/data-connect",mm="@firebase/database-compat",gm="@firebase/functions",_m="@firebase/functions-compat",ym="@firebase/installations",Em="@firebase/installations-compat",Tm="@firebase/messaging",wm="@firebase/messaging-compat",Im="@firebase/performance",vm="@firebase/performance-compat",Am="@firebase/remote-config",Rm="@firebase/remote-config-compat",bm="@firebase/storage",Pm="@firebase/storage-compat",Cm="@firebase/firestore",Sm="@firebase/ai",km="@firebase/firestore-compat",Nm="firebase",Dm="12.10.0";const Xi="[DEFAULT]",Om={[Ji]:"fire-core",[om]:"fire-core-compat",[cm]:"fire-analytics",[am]:"fire-analytics-compat",[lm]:"fire-app-check",[um]:"fire-app-check-compat",[hm]:"fire-auth",[dm]:"fire-auth-compat",[fm]:"fire-rtdb",[pm]:"fire-data-connect",[mm]:"fire-rtdb-compat",[gm]:"fire-fn",[_m]:"fire-fn-compat",[ym]:"fire-iid",[Em]:"fire-iid-compat",[Tm]:"fire-fcm",[wm]:"fire-fcm-compat",[Im]:"fire-perf",[vm]:"fire-perf-compat",[Am]:"fire-rc",[Rm]:"fire-rc-compat",[bm]:"fire-gcs",[Pm]:"fire-gcs-compat",[Cm]:"fire-fst",[km]:"fire-fst-compat",[Sm]:"fire-vertex","fire-js":"fire-js",[Nm]:"fire-js-all"};const ds=new Map,Vm=new Map,Zi=new Map;function Pc(n,e){try{n.container.addComponent(e)}catch(t){yt.debug(`Component ${e.name} failed to register with FirebaseApp ${n.name}`,t)}}function Ct(n){const e=n.name;if(Zi.has(e))return yt.debug(`There were multiple attempts to register component ${e}.`),!1;Zi.set(e,n);for(const t of ds.values())Pc(t,n);for(const t of Vm.values())Pc(t,n);return!0}function dr(n,e){const t=n.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),n.container.getProvider(e)}function Ae(n){return n==null?!1:n.settings!==void 0}const Lm={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},St=new cr("app","Firebase",Lm);class Mm{constructor(e,t,r){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new _t("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 St.create("app-deleted",{appName:this._name})}}const nn=Dm;function Cc(n,e={}){let t=n;typeof e!="object"&&(e={name:e});const r={name:Xi,automaticDataCollectionEnabled:!0,...e},s=r.name;if(typeof s!="string"||!s)throw St.create("bad-app-name",{appName:String(s)});if(t||(t=gc()),!t)throw St.create("no-options");const i=ds.get(s);if(i){if(en(t,i.options)&&en(r,i.config))return i;throw St.create("duplicate-app",{appName:s})}const a=new jp(s);for(const l of Zi.values())a.addComponent(l);const c=new Mm(t,r,a);return ds.set(s,c),c}function fs(n=Xi){const e=ds.get(n);if(!e&&n===Xi&&gc())return Cc();if(!e)throw St.create("no-app",{appName:n});return e}function je(n,e,t){let r=Om[n]??n;t&&(r+=`-${t}`);const s=r.match(/\s|\//),i=e.match(/\s|\//);if(s||i){const a=[`Unable to register library "${r}" with version "${e}":`];s&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),s&&i&&a.push("and"),i&&a.push(`version name "${e}" contains illegal characters (whitespace or "/")`),yt.warn(a.join(" "));return}Ct(new _t(`${r}-version`,()=>({library:r,version:e}),"VERSION"))}const xm="firebase-heartbeat-database",Um=1,fr="firebase-heartbeat-store";let eo=null;function Sc(){return eo||(eo=tm(xm,Um,{upgrade:(n,e)=>{switch(e){case 0:try{n.createObjectStore(fr)}catch(t){console.warn(t)}}}}).catch(n=>{throw St.create("idb-open",{originalErrorMessage:n.message})})),eo}async function Fm(n){try{const t=(await Sc()).transaction(fr),r=await t.objectStore(fr).get(Nc(n));return await t.done,r}catch(e){if(e instanceof We)yt.warn(e.message);else{const t=St.create("idb-get",{originalErrorMessage:e?.message});yt.warn(t.message)}}}async function kc(n,e){try{const r=(await Sc()).transaction(fr,"readwrite");await r.objectStore(fr).put(e,Nc(n)),await r.done}catch(t){if(t instanceof We)yt.warn(t.message);else{const r=St.create("idb-set",{originalErrorMessage:t?.message});yt.warn(r.message)}}}function Nc(n){return`${n.name}!${n.options.appId}`}const Bm=1024,qm=30;class jm{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new zm(t),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r))}async triggerHeartbeat(){try{const t=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=Dc();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(s=>s.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:t}),this._heartbeatsCache.heartbeats.length>qm){const s=Hm(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(s,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){yt.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return"";const e=Dc(),{heartbeatsToSend:t,unsentEntries:r}=$m(this._heartbeatsCache.heartbeats),s=cs(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}catch(e){return yt.warn(e),""}}}function Dc(){return new Date().toISOString().substring(0,10)}function $m(n,e=Bm){const t=[];let r=n.slice();for(const s of n){const i=t.find(a=>a.agent===s.agent);if(i){if(i.dates.push(s.date),Oc(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Oc(t)>e){t.pop();break}r=r.slice(1)}return{heartbeatsToSend:t,unsentEntries:r}}class zm{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return kp()?Np().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const t=await Fm(this.app);return t?.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){const r=await this.read();return kc(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){const r=await this.read();return kc(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}}function Oc(n){return cs(JSON.stringify({version:2,heartbeats:n})).length}function Hm(n){if(n.length===0)return-1;let e=0,t=n[0].date;for(let r=1;r<n.length;r++)n[r].date<t&&(t=n[r].date,e=r);return e}function Wm(n){Ct(new _t("platform-logger",e=>new sm(e),"PRIVATE")),Ct(new _t("heartbeat",e=>new jm(e),"PRIVATE")),je(Ji,bc,n),je(Ji,bc,"esm2020"),je("fire-js","")}Wm("");var Vc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var kt,Lc;(function(){var n;function e(w,g){function E(){}E.prototype=g.prototype,w.F=g.prototype,w.prototype=new E,w.prototype.constructor=w,w.D=function(I,T,A){for(var y=Array(arguments.length-2),Me=2;Me<arguments.length;Me++)y[Me-2]=arguments[Me];return g.prototype[T].apply(I,y)}}function t(){this.blockSize=-1}function r(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}e(r,t),r.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(w,g,E){E||(E=0);const I=Array(16);if(typeof g=="string")for(var T=0;T<16;++T)I[T]=g.charCodeAt(E++)|g.charCodeAt(E++)<<8|g.charCodeAt(E++)<<16|g.charCodeAt(E++)<<24;else for(T=0;T<16;++T)I[T]=g[E++]|g[E++]<<8|g[E++]<<16|g[E++]<<24;g=w.g[0],E=w.g[1],T=w.g[2];let A=w.g[3],y;y=g+(A^E&(T^A))+I[0]+3614090360&4294967295,g=E+(y<<7&4294967295|y>>>25),y=A+(T^g&(E^T))+I[1]+3905402710&4294967295,A=g+(y<<12&4294967295|y>>>20),y=T+(E^A&(g^E))+I[2]+606105819&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(g^T&(A^g))+I[3]+3250441966&4294967295,E=T+(y<<22&4294967295|y>>>10),y=g+(A^E&(T^A))+I[4]+4118548399&4294967295,g=E+(y<<7&4294967295|y>>>25),y=A+(T^g&(E^T))+I[5]+1200080426&4294967295,A=g+(y<<12&4294967295|y>>>20),y=T+(E^A&(g^E))+I[6]+2821735955&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(g^T&(A^g))+I[7]+4249261313&4294967295,E=T+(y<<22&4294967295|y>>>10),y=g+(A^E&(T^A))+I[8]+1770035416&4294967295,g=E+(y<<7&4294967295|y>>>25),y=A+(T^g&(E^T))+I[9]+2336552879&4294967295,A=g+(y<<12&4294967295|y>>>20),y=T+(E^A&(g^E))+I[10]+4294925233&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(g^T&(A^g))+I[11]+2304563134&4294967295,E=T+(y<<22&4294967295|y>>>10),y=g+(A^E&(T^A))+I[12]+1804603682&4294967295,g=E+(y<<7&4294967295|y>>>25),y=A+(T^g&(E^T))+I[13]+4254626195&4294967295,A=g+(y<<12&4294967295|y>>>20),y=T+(E^A&(g^E))+I[14]+2792965006&4294967295,T=A+(y<<17&4294967295|y>>>15),y=E+(g^T&(A^g))+I[15]+1236535329&4294967295,E=T+(y<<22&4294967295|y>>>10),y=g+(T^A&(E^T))+I[1]+4129170786&4294967295,g=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(g^E))+I[6]+3225465664&4294967295,A=g+(y<<9&4294967295|y>>>23),y=T+(g^E&(A^g))+I[11]+643717713&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^g&(T^A))+I[0]+3921069994&4294967295,E=T+(y<<20&4294967295|y>>>12),y=g+(T^A&(E^T))+I[5]+3593408605&4294967295,g=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(g^E))+I[10]+38016083&4294967295,A=g+(y<<9&4294967295|y>>>23),y=T+(g^E&(A^g))+I[15]+3634488961&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^g&(T^A))+I[4]+3889429448&4294967295,E=T+(y<<20&4294967295|y>>>12),y=g+(T^A&(E^T))+I[9]+568446438&4294967295,g=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(g^E))+I[14]+3275163606&4294967295,A=g+(y<<9&4294967295|y>>>23),y=T+(g^E&(A^g))+I[3]+4107603335&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^g&(T^A))+I[8]+1163531501&4294967295,E=T+(y<<20&4294967295|y>>>12),y=g+(T^A&(E^T))+I[13]+2850285829&4294967295,g=E+(y<<5&4294967295|y>>>27),y=A+(E^T&(g^E))+I[2]+4243563512&4294967295,A=g+(y<<9&4294967295|y>>>23),y=T+(g^E&(A^g))+I[7]+1735328473&4294967295,T=A+(y<<14&4294967295|y>>>18),y=E+(A^g&(T^A))+I[12]+2368359562&4294967295,E=T+(y<<20&4294967295|y>>>12),y=g+(E^T^A)+I[5]+4294588738&4294967295,g=E+(y<<4&4294967295|y>>>28),y=A+(g^E^T)+I[8]+2272392833&4294967295,A=g+(y<<11&4294967295|y>>>21),y=T+(A^g^E)+I[11]+1839030562&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^g)+I[14]+4259657740&4294967295,E=T+(y<<23&4294967295|y>>>9),y=g+(E^T^A)+I[1]+2763975236&4294967295,g=E+(y<<4&4294967295|y>>>28),y=A+(g^E^T)+I[4]+1272893353&4294967295,A=g+(y<<11&4294967295|y>>>21),y=T+(A^g^E)+I[7]+4139469664&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^g)+I[10]+3200236656&4294967295,E=T+(y<<23&4294967295|y>>>9),y=g+(E^T^A)+I[13]+681279174&4294967295,g=E+(y<<4&4294967295|y>>>28),y=A+(g^E^T)+I[0]+3936430074&4294967295,A=g+(y<<11&4294967295|y>>>21),y=T+(A^g^E)+I[3]+3572445317&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^g)+I[6]+76029189&4294967295,E=T+(y<<23&4294967295|y>>>9),y=g+(E^T^A)+I[9]+3654602809&4294967295,g=E+(y<<4&4294967295|y>>>28),y=A+(g^E^T)+I[12]+3873151461&4294967295,A=g+(y<<11&4294967295|y>>>21),y=T+(A^g^E)+I[15]+530742520&4294967295,T=A+(y<<16&4294967295|y>>>16),y=E+(T^A^g)+I[2]+3299628645&4294967295,E=T+(y<<23&4294967295|y>>>9),y=g+(T^(E|~A))+I[0]+4096336452&4294967295,g=E+(y<<6&4294967295|y>>>26),y=A+(E^(g|~T))+I[7]+1126891415&4294967295,A=g+(y<<10&4294967295|y>>>22),y=T+(g^(A|~E))+I[14]+2878612391&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~g))+I[5]+4237533241&4294967295,E=T+(y<<21&4294967295|y>>>11),y=g+(T^(E|~A))+I[12]+1700485571&4294967295,g=E+(y<<6&4294967295|y>>>26),y=A+(E^(g|~T))+I[3]+2399980690&4294967295,A=g+(y<<10&4294967295|y>>>22),y=T+(g^(A|~E))+I[10]+4293915773&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~g))+I[1]+2240044497&4294967295,E=T+(y<<21&4294967295|y>>>11),y=g+(T^(E|~A))+I[8]+1873313359&4294967295,g=E+(y<<6&4294967295|y>>>26),y=A+(E^(g|~T))+I[15]+4264355552&4294967295,A=g+(y<<10&4294967295|y>>>22),y=T+(g^(A|~E))+I[6]+2734768916&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~g))+I[13]+1309151649&4294967295,E=T+(y<<21&4294967295|y>>>11),y=g+(T^(E|~A))+I[4]+4149444226&4294967295,g=E+(y<<6&4294967295|y>>>26),y=A+(E^(g|~T))+I[11]+3174756917&4294967295,A=g+(y<<10&4294967295|y>>>22),y=T+(g^(A|~E))+I[2]+718787259&4294967295,T=A+(y<<15&4294967295|y>>>17),y=E+(A^(T|~g))+I[9]+3951481745&4294967295,w.g[0]=w.g[0]+g&4294967295,w.g[1]=w.g[1]+(T+(y<<21&4294967295|y>>>11))&4294967295,w.g[2]=w.g[2]+T&4294967295,w.g[3]=w.g[3]+A&4294967295}r.prototype.v=function(w,g){g===void 0&&(g=w.length);const E=g-this.blockSize,I=this.C;let T=this.h,A=0;for(;A<g;){if(T==0)for(;A<=E;)s(this,w,A),A+=this.blockSize;if(typeof w=="string"){for(;A<g;)if(I[T++]=w.charCodeAt(A++),T==this.blockSize){s(this,I),T=0;break}}else for(;A<g;)if(I[T++]=w[A++],T==this.blockSize){s(this,I),T=0;break}}this.h=T,this.o+=g},r.prototype.A=function(){var w=Array((this.h<56?this.blockSize:this.blockSize*2)-this.h);w[0]=128;for(var g=1;g<w.length-8;++g)w[g]=0;g=this.o*8;for(var E=w.length-8;E<w.length;++E)w[E]=g&255,g/=256;for(this.v(w),w=Array(16),g=0,E=0;E<4;++E)for(let I=0;I<32;I+=8)w[g++]=this.g[E]>>>I&255;return w};function i(w,g){var E=c;return Object.prototype.hasOwnProperty.call(E,w)?E[w]:E[w]=g(w)}function a(w,g){this.h=g;const E=[];let I=!0;for(let T=w.length-1;T>=0;T--){const A=w[T]|0;I&&A==g||(E[T]=A,I=!1)}this.g=E}var c={};function l(w){return-128<=w&&w<128?i(w,function(g){return new a([g|0],g<0?-1:0)}):new a([w|0],w<0?-1:0)}function d(w){if(isNaN(w)||!isFinite(w))return m;if(w<0)return k(d(-w));const g=[];let E=1;for(let I=0;w>=E;I++)g[I]=w/E|0,E*=4294967296;return new a(g,0)}function f(w,g){if(w.length==0)throw Error("number format error: empty string");if(g=g||10,g<2||36<g)throw Error("radix out of range: "+g);if(w.charAt(0)=="-")return k(f(w.substring(1),g));if(w.indexOf("-")>=0)throw Error('number format error: interior "-" character');const E=d(Math.pow(g,8));let I=m;for(let A=0;A<w.length;A+=8){var T=Math.min(8,w.length-A);const y=parseInt(w.substring(A,A+T),g);T<8?(T=d(Math.pow(g,T)),I=I.j(T).add(d(y))):(I=I.j(E),I=I.add(d(y)))}return I}var m=l(0),_=l(1),R=l(16777216);n=a.prototype,n.m=function(){if(N(this))return-k(this).m();let w=0,g=1;for(let E=0;E<this.g.length;E++){const I=this.i(E);w+=(I>=0?I:4294967296+I)*g,g*=4294967296}return w},n.toString=function(w){if(w=w||10,w<2||36<w)throw Error("radix out of range: "+w);if(S(this))return"0";if(N(this))return"-"+k(this).toString(w);const g=d(Math.pow(w,6));var E=this;let I="";for(;;){const T=Q(E,g).g;E=U(E,T.j(g));let A=((E.g.length>0?E.g[0]:E.h)>>>0).toString(w);if(E=T,S(E))return A+I;for(;A.length<6;)A="0"+A;I=A+I}},n.i=function(w){return w<0?0:w<this.g.length?this.g[w]:this.h};function S(w){if(w.h!=0)return!1;for(let g=0;g<w.g.length;g++)if(w.g[g]!=0)return!1;return!0}function N(w){return w.h==-1}n.l=function(w){return w=U(this,w),N(w)?-1:S(w)?0:1};function k(w){const g=w.g.length,E=[];for(let I=0;I<g;I++)E[I]=~w.g[I];return new a(E,~w.h).add(_)}n.abs=function(){return N(this)?k(this):this},n.add=function(w){const g=Math.max(this.g.length,w.g.length),E=[];let I=0;for(let T=0;T<=g;T++){let A=I+(this.i(T)&65535)+(w.i(T)&65535),y=(A>>>16)+(this.i(T)>>>16)+(w.i(T)>>>16);I=y>>>16,A&=65535,y&=65535,E[T]=y<<16|A}return new a(E,E[E.length-1]&-2147483648?-1:0)};function U(w,g){return w.add(k(g))}n.j=function(w){if(S(this)||S(w))return m;if(N(this))return N(w)?k(this).j(k(w)):k(k(this).j(w));if(N(w))return k(this.j(k(w)));if(this.l(R)<0&&w.l(R)<0)return d(this.m()*w.m());const g=this.g.length+w.g.length,E=[];for(var I=0;I<2*g;I++)E[I]=0;for(I=0;I<this.g.length;I++)for(let T=0;T<w.g.length;T++){const A=this.i(I)>>>16,y=this.i(I)&65535,Me=w.i(T)>>>16,Tn=w.i(T)&65535;E[2*I+2*T]+=y*Tn,$(E,2*I+2*T),E[2*I+2*T+1]+=A*Tn,$(E,2*I+2*T+1),E[2*I+2*T+1]+=y*Me,$(E,2*I+2*T+1),E[2*I+2*T+2]+=A*Me,$(E,2*I+2*T+2)}for(w=0;w<g;w++)E[w]=E[2*w+1]<<16|E[2*w];for(w=g;w<2*g;w++)E[w]=0;return new a(E,0)};function $(w,g){for(;(w[g]&65535)!=w[g];)w[g+1]+=w[g]>>>16,w[g]&=65535,g++}function j(w,g){this.g=w,this.h=g}function Q(w,g){if(S(g))throw Error("division by zero");if(S(w))return new j(m,m);if(N(w))return g=Q(k(w),g),new j(k(g.g),k(g.h));if(N(g))return g=Q(w,k(g)),new j(k(g.g),g.h);if(w.g.length>30){if(N(w)||N(g))throw Error("slowDivide_ only works with positive integers.");for(var E=_,I=g;I.l(w)<=0;)E=_e(E),I=_e(I);var T=re(E,1),A=re(I,1);for(I=re(I,2),E=re(E,2);!S(I);){var y=A.add(I);y.l(w)<=0&&(T=T.add(E),A=y),I=re(I,1),E=re(E,1)}return g=U(w,T.j(g)),new j(T,g)}for(T=m;w.l(g)>=0;){for(E=Math.max(1,Math.floor(w.m()/g.m())),I=Math.ceil(Math.log(E)/Math.LN2),I=I<=48?1:Math.pow(2,I-48),A=d(E),y=A.j(g);N(y)||y.l(w)>0;)E-=I,A=d(E),y=A.j(g);S(A)&&(A=_),T=T.add(A),w=U(w,y)}return new j(T,w)}n.B=function(w){return Q(this,w).h},n.and=function(w){const g=Math.max(this.g.length,w.g.length),E=[];for(let I=0;I<g;I++)E[I]=this.i(I)&w.i(I);return new a(E,this.h&w.h)},n.or=function(w){const g=Math.max(this.g.length,w.g.length),E=[];for(let I=0;I<g;I++)E[I]=this.i(I)|w.i(I);return new a(E,this.h|w.h)},n.xor=function(w){const g=Math.max(this.g.length,w.g.length),E=[];for(let I=0;I<g;I++)E[I]=this.i(I)^w.i(I);return new a(E,this.h^w.h)};function _e(w){const g=w.g.length+1,E=[];for(let I=0;I<g;I++)E[I]=w.i(I)<<1|w.i(I-1)>>>31;return new a(E,w.h)}function re(w,g){const E=g>>5;g%=32;const I=w.g.length-E,T=[];for(let A=0;A<I;A++)T[A]=g>0?w.i(A+E)>>>g|w.i(A+E+1)<<32-g:w.i(A+E);return new a(T,w.h)}r.prototype.digest=r.prototype.A,r.prototype.reset=r.prototype.u,r.prototype.update=r.prototype.v,Lc=r,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.B,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=d,a.fromString=f,kt=a}).apply(typeof Vc<"u"?Vc:typeof self<"u"?self:typeof window<"u"?window:{});var ps=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};var Mc,pr,xc,ms,to,Uc,Fc,Bc;(function(){var n,e=Object.defineProperty;function t(o){o=[typeof globalThis=="object"&&globalThis,o,typeof window=="object"&&window,typeof self=="object"&&self,typeof ps=="object"&&ps];for(var u=0;u<o.length;++u){var h=o[u];if(h&&h.Math==Math)return h}throw Error("Cannot find global object")}var r=t(this);function s(o,u){if(u)e:{var h=r;o=o.split(".");for(var p=0;p<o.length-1;p++){var v=o[p];if(!(v in h))break e;h=h[v]}o=o[o.length-1],p=h[o],u=u(p),u!=p&&u!=null&&e(h,o,{configurable:!0,writable:!0,value:u})}}s("Symbol.dispose",function(o){return o||Symbol("Symbol.dispose")}),s("Array.prototype.values",function(o){return o||function(){return this[Symbol.iterator]()}}),s("Object.entries",function(o){return o||function(u){var h=[],p;for(p in u)Object.prototype.hasOwnProperty.call(u,p)&&h.push([p,u[p]]);return h}});var i=i||{},a=this||self;function c(o){var u=typeof o;return u=="object"&&o!=null||u=="function"}function l(o,u,h){return o.call.apply(o.bind,arguments)}function d(o,u,h){return d=l,d.apply(null,arguments)}function f(o,u){var h=Array.prototype.slice.call(arguments,1);return function(){var p=h.slice();return p.push.apply(p,arguments),o.apply(this,p)}}function m(o,u){function h(){}h.prototype=u.prototype,o.Z=u.prototype,o.prototype=new h,o.prototype.constructor=o,o.Ob=function(p,v,b){for(var O=Array(arguments.length-2),z=2;z<arguments.length;z++)O[z-2]=arguments[z];return u.prototype[v].apply(p,O)}}var _=typeof AsyncContext<"u"&&typeof AsyncContext.Snapshot=="function"?o=>o&&AsyncContext.Snapshot.wrap(o):o=>o;function R(o){const u=o.length;if(u>0){const h=Array(u);for(let p=0;p<u;p++)h[p]=o[p];return h}return[]}function S(o,u){for(let p=1;p<arguments.length;p++){const v=arguments[p];var h=typeof v;if(h=h!="object"?h:v?Array.isArray(v)?"array":h:"null",h=="array"||h=="object"&&typeof v.length=="number"){h=o.length||0;const b=v.length||0;o.length=h+b;for(let O=0;O<b;O++)o[h+O]=v[O]}else o.push(v)}}class N{constructor(u,h){this.i=u,this.j=h,this.h=0,this.g=null}get(){let u;return this.h>0?(this.h--,u=this.g,this.g=u.next,u.next=null):u=this.i(),u}}function k(o){a.setTimeout(()=>{throw o},0)}function U(){var o=w;let u=null;return o.g&&(u=o.g,o.g=o.g.next,o.g||(o.h=null),u.next=null),u}class ${constructor(){this.h=this.g=null}add(u,h){const p=j.get();p.set(u,h),this.h?this.h.next=p:this.g=p,this.h=p}}var j=new N(()=>new Q,o=>o.reset());class Q{constructor(){this.next=this.g=this.h=null}set(u,h){this.h=u,this.g=h,this.next=null}reset(){this.next=this.g=this.h=null}}let _e,re=!1,w=new $,g=()=>{const o=Promise.resolve(void 0);_e=()=>{o.then(E)}};function E(){for(var o;o=U();){try{o.h.call(o.g)}catch(h){k(h)}var u=j;u.j(o),u.h<100&&(u.h++,o.next=u.g,u.g=o)}re=!1}function I(){this.u=this.u,this.C=this.C}I.prototype.u=!1,I.prototype.dispose=function(){this.u||(this.u=!0,this.N())},I.prototype[Symbol.dispose]=function(){this.dispose()},I.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function T(o,u){this.type=o,this.g=this.target=u,this.defaultPrevented=!1}T.prototype.h=function(){this.defaultPrevented=!0};var A=function(){if(!a.addEventListener||!Object.defineProperty)return!1;var o=!1,u=Object.defineProperty({},"passive",{get:function(){o=!0}});try{const h=()=>{};a.addEventListener("test",h,u),a.removeEventListener("test",h,u)}catch{}return o}();function y(o){return/^[\s\xa0]*$/.test(o)}function Me(o,u){T.call(this,o?o.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,o&&this.init(o,u)}m(Me,T),Me.prototype.init=function(o,u){const h=this.type=o.type,p=o.changedTouches&&o.changedTouches.length?o.changedTouches[0]:null;this.target=o.target||o.srcElement,this.g=u,u=o.relatedTarget,u||(h=="mouseover"?u=o.fromElement:h=="mouseout"&&(u=o.toElement)),this.relatedTarget=u,p?(this.clientX=p.clientX!==void 0?p.clientX:p.pageX,this.clientY=p.clientY!==void 0?p.clientY:p.pageY,this.screenX=p.screenX||0,this.screenY=p.screenY||0):(this.clientX=o.clientX!==void 0?o.clientX:o.pageX,this.clientY=o.clientY!==void 0?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0),this.button=o.button,this.key=o.key||"",this.ctrlKey=o.ctrlKey,this.altKey=o.altKey,this.shiftKey=o.shiftKey,this.metaKey=o.metaKey,this.pointerId=o.pointerId||0,this.pointerType=o.pointerType,this.state=o.state,this.i=o,o.defaultPrevented&&Me.Z.h.call(this)},Me.prototype.h=function(){Me.Z.h.call(this);const o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var Tn="closure_listenable_"+(Math.random()*1e6|0),eA=0;function tA(o,u,h,p,v){this.listener=o,this.proxy=null,this.src=u,this.type=h,this.capture=!!p,this.ha=v,this.key=++eA,this.da=this.fa=!1}function Pi(o){o.da=!0,o.listener=null,o.proxy=null,o.src=null,o.ha=null}function Ci(o,u,h){for(const p in o)u.call(h,o[p],p,o)}function nA(o,u){for(const h in o)u.call(void 0,o[h],h,o)}function hf(o){const u={};for(const h in o)u[h]=o[h];return u}const df="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ff(o,u){let h,p;for(let v=1;v<arguments.length;v++){p=arguments[v];for(h in p)o[h]=p[h];for(let b=0;b<df.length;b++)h=df[b],Object.prototype.hasOwnProperty.call(p,h)&&(o[h]=p[h])}}function Si(o){this.src=o,this.g={},this.h=0}Si.prototype.add=function(o,u,h,p,v){const b=o.toString();o=this.g[b],o||(o=this.g[b]=[],this.h++);const O=$a(o,u,p,v);return O>-1?(u=o[O],h||(u.fa=!1)):(u=new tA(u,this.src,b,!!p,v),u.fa=h,o.push(u)),u};function ja(o,u){const h=u.type;if(h in o.g){var p=o.g[h],v=Array.prototype.indexOf.call(p,u,void 0),b;(b=v>=0)&&Array.prototype.splice.call(p,v,1),b&&(Pi(u),o.g[h].length==0&&(delete o.g[h],o.h--))}}function $a(o,u,h,p){for(let v=0;v<o.length;++v){const b=o[v];if(!b.da&&b.listener==u&&b.capture==!!h&&b.ha==p)return v}return-1}var za="closure_lm_"+(Math.random()*1e6|0),Ha={};function pf(o,u,h,p,v){if(Array.isArray(u)){for(let b=0;b<u.length;b++)pf(o,u[b],h,p,v);return null}return h=_f(h),o&&o[Tn]?o.J(u,h,c(p)?!!p.capture:!1,v):rA(o,u,h,!1,p,v)}function rA(o,u,h,p,v,b){if(!u)throw Error("Invalid event type");const O=c(v)?!!v.capture:!!v;let z=Ga(o);if(z||(o[za]=z=new Si(o)),h=z.add(u,h,p,O,b),h.proxy)return h;if(p=sA(),h.proxy=p,p.src=o,p.listener=h,o.addEventListener)A||(v=O),v===void 0&&(v=!1),o.addEventListener(u.toString(),p,v);else if(o.attachEvent)o.attachEvent(gf(u.toString()),p);else if(o.addListener&&o.removeListener)o.addListener(p);else throw Error("addEventListener and attachEvent are unavailable.");return h}function sA(){function o(h){return u.call(o.src,o.listener,h)}const u=iA;return o}function mf(o,u,h,p,v){if(Array.isArray(u))for(var b=0;b<u.length;b++)mf(o,u[b],h,p,v);else p=c(p)?!!p.capture:!!p,h=_f(h),o&&o[Tn]?(o=o.i,b=String(u).toString(),b in o.g&&(u=o.g[b],h=$a(u,h,p,v),h>-1&&(Pi(u[h]),Array.prototype.splice.call(u,h,1),u.length==0&&(delete o.g[b],o.h--)))):o&&(o=Ga(o))&&(u=o.g[u.toString()],o=-1,u&&(o=$a(u,h,p,v)),(h=o>-1?u[o]:null)&&Wa(h))}function Wa(o){if(typeof o!="number"&&o&&!o.da){var u=o.src;if(u&&u[Tn])ja(u.i,o);else{var h=o.type,p=o.proxy;u.removeEventListener?u.removeEventListener(h,p,o.capture):u.detachEvent?u.detachEvent(gf(h),p):u.addListener&&u.removeListener&&u.removeListener(p),(h=Ga(u))?(ja(h,o),h.h==0&&(h.src=null,u[za]=null)):Pi(o)}}}function gf(o){return o in Ha?Ha[o]:Ha[o]="on"+o}function iA(o,u){if(o.da)o=!0;else{u=new Me(u,this);const h=o.listener,p=o.ha||o.src;o.fa&&Wa(o),o=h.call(p,u)}return o}function Ga(o){return o=o[za],o instanceof Si?o:null}var Ka="__closure_events_fn_"+(Math.random()*1e9>>>0);function _f(o){return typeof o=="function"?o:(o[Ka]||(o[Ka]=function(u){return o.handleEvent(u)}),o[Ka])}function Ce(){I.call(this),this.i=new Si(this),this.M=this,this.G=null}m(Ce,I),Ce.prototype[Tn]=!0,Ce.prototype.removeEventListener=function(o,u,h,p){mf(this,o,u,h,p)};function Ne(o,u){var h,p=o.G;if(p)for(h=[];p;p=p.G)h.push(p);if(o=o.M,p=u.type||u,typeof u=="string")u=new T(u,o);else if(u instanceof T)u.target=u.target||o;else{var v=u;u=new T(p,o),ff(u,v)}v=!0;let b,O;if(h)for(O=h.length-1;O>=0;O--)b=u.g=h[O],v=ki(b,p,!0,u)&&v;if(b=u.g=o,v=ki(b,p,!0,u)&&v,v=ki(b,p,!1,u)&&v,h)for(O=0;O<h.length;O++)b=u.g=h[O],v=ki(b,p,!1,u)&&v}Ce.prototype.N=function(){if(Ce.Z.N.call(this),this.i){var o=this.i;for(const u in o.g){const h=o.g[u];for(let p=0;p<h.length;p++)Pi(h[p]);delete o.g[u],o.h--}}this.G=null},Ce.prototype.J=function(o,u,h,p){return this.i.add(String(o),u,!1,h,p)},Ce.prototype.K=function(o,u,h,p){return this.i.add(String(o),u,!0,h,p)};function ki(o,u,h,p){if(u=o.i.g[String(u)],!u)return!0;u=u.concat();let v=!0;for(let b=0;b<u.length;++b){const O=u[b];if(O&&!O.da&&O.capture==h){const z=O.listener,me=O.ha||O.src;O.fa&&ja(o.i,O),v=z.call(me,p)!==!1&&v}}return v&&!p.defaultPrevented}function oA(o,u){if(typeof o!="function")if(o&&typeof o.handleEvent=="function")o=d(o.handleEvent,o);else throw Error("Invalid listener argument");return Number(u)>2147483647?-1:a.setTimeout(o,u||0)}function yf(o){o.g=oA(()=>{o.g=null,o.i&&(o.i=!1,yf(o))},o.l);const u=o.h;o.h=null,o.m.apply(null,u)}class aA extends I{constructor(u,h){super(),this.m=u,this.l=h,this.h=null,this.i=!1,this.g=null}j(u){this.h=arguments,this.g?this.i=!0:yf(this)}N(){super.N(),this.g&&(a.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Wr(o){I.call(this),this.h=o,this.g={}}m(Wr,I);var Ef=[];function Tf(o){Ci(o.g,function(u,h){this.g.hasOwnProperty(h)&&Wa(u)},o),o.g={}}Wr.prototype.N=function(){Wr.Z.N.call(this),Tf(this)},Wr.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Qa=a.JSON.stringify,cA=a.JSON.parse,uA=class{stringify(o){return a.JSON.stringify(o,void 0)}parse(o){return a.JSON.parse(o,void 0)}};function wf(){}function If(){}var Gr={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function Ya(){T.call(this,"d")}m(Ya,T);function Ja(){T.call(this,"c")}m(Ja,T);var wn={},vf=null;function Ni(){return vf=vf||new Ce}wn.Ia="serverreachability";function Af(o){T.call(this,wn.Ia,o)}m(Af,T);function Kr(o){const u=Ni();Ne(u,new Af(u))}wn.STAT_EVENT="statevent";function Rf(o,u){T.call(this,wn.STAT_EVENT,o),this.stat=u}m(Rf,T);function De(o){const u=Ni();Ne(u,new Rf(u,o))}wn.Ja="timingevent";function bf(o,u){T.call(this,wn.Ja,o),this.size=u}m(bf,T);function Qr(o,u){if(typeof o!="function")throw Error("Fn must not be null and must be a function");return a.setTimeout(function(){o()},u)}function Yr(){this.g=!0}Yr.prototype.ua=function(){this.g=!1};function lA(o,u,h,p,v,b){o.info(function(){if(o.g)if(b){var O="",z=b.split("&");for(let Z=0;Z<z.length;Z++){var me=z[Z].split("=");if(me.length>1){const ye=me[0];me=me[1];const gt=ye.split("_");O=gt.length>=2&&gt[1]=="type"?O+(ye+"="+me+"&"):O+(ye+"=redacted&")}}}else O=null;else O=b;return"XMLHTTP REQ ("+p+") [attempt "+v+"]: "+u+`
16
16
  `+h+`
17
17
  `+O})}function hA(o,u,h,p,v,b,O){o.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+v+"]: "+u+`
18
18
  `+h+`
19
- `+b+" "+O})}function tr(o,u,h,p){o.info(function(){return"XMLHTTP TEXT ("+u+"): "+fA(o,h)+(p?" "+p:"")})}function dA(o,u){o.info(function(){return"TIMEOUT: "+u})}Yr.prototype.info=function(){};function fA(o,u){if(!o.g)return u;if(!u)return null;try{const b=JSON.parse(u);if(b){for(o=0;o<b.length;o++)if(Array.isArray(b[o])){var h=b[o];if(!(h.length<2)){var p=h[1];if(Array.isArray(p)&&!(p.length<1)){var v=p[0];if(v!="noop"&&v!="stop"&&v!="close")for(let O=1;O<p.length;O++)p[O]=""}}}}return Qa(b)}catch{return u}}var Di={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},Pf={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"},Sf;function Xa(){}m(Xa,wf),Xa.prototype.g=function(){return new XMLHttpRequest},Sf=new Xa;function Jr(o){return encodeURIComponent(String(o))}function pA(o){var u=1;o=o.split(":");const h=[];for(;u>0&&o.length;)h.push(o.shift()),u--;return o.length&&h.push(o.join(":")),h}function Kt(o,u,h,p){this.j=o,this.i=u,this.l=h,this.S=p||1,this.V=new Wr(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new Cf}function Cf(){this.i=null,this.g="",this.h=!1}var kf={},Za={};function ec(o,u,h){o.M=1,o.A=Vi(mt(u)),o.u=h,o.R=!0,Nf(o,null)}function Nf(o,u){o.F=Date.now(),Oi(o),o.B=mt(o.A);var h=o.B,p=o.S;Array.isArray(p)||(p=[String(p)]),zf(h.i,"t",p),o.C=0,h=o.j.L,o.h=new Cf,o.g=cp(o.j,h?u:null,!o.u),o.P>0&&(o.O=new aA(d(o.Y,o,o.g),o.P)),u=o.V,h=o.g,p=o.ba;var v="readystatechange";Array.isArray(v)||(v&&(Ef[0]=v.toString()),v=Ef);for(let b=0;b<v.length;b++){const O=pf(h,v[b],p||u.handleEvent,!1,u.h||u);if(!O)break;u.g[O.key]=O}u=o.J?hf(o.J):{},o.u?(o.v||(o.v="POST"),u["Content-Type"]="application/x-www-form-urlencoded",o.g.ea(o.B,o.v,o.u,u)):(o.v="GET",o.g.ea(o.B,o.v,null,u)),Kr(),lA(o.i,o.v,o.B,o.l,o.S,o.u)}Kt.prototype.ba=function(o){o=o.target;const u=this.O;u&&Jt(o)==3?u.j():this.Y(o)},Kt.prototype.Y=function(o){try{if(o==this.g)e:{const z=Jt(this.g),me=this.g.ya(),Z=this.g.ca();if(!(z<3)&&(z!=3||this.g&&(this.h.h||this.g.la()||Jf(this.g)))){this.K||z!=4||me==7||(me==8||Z<=0?Kr(3):Kr(2)),tc(this);var u=this.g.ca();this.X=u;var h=mA(this);if(this.o=u==200,hA(this.i,this.v,this.B,this.l,this.S,z,u),this.o){if(this.U&&!this.L){t:{if(this.g){var p,v=this.g;if((p=v.g?v.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!y(p)){var b=p;break t}}b=null}if(o=b)tr(this.i,this.l,o,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,nc(this,o);else{this.o=!1,this.m=3,De(12),wn(this),Xr(this);break e}}if(this.R){o=!0;let ye;for(;!this.K&&this.C<h.length;)if(ye=gA(this,h),ye==Za){z==4&&(this.m=4,De(14),o=!1),tr(this.i,this.l,null,"[Incomplete Response]");break}else if(ye==kf){this.m=4,De(15),tr(this.i,this.l,h,"[Invalid Chunk]"),o=!1;break}else tr(this.i,this.l,ye,null),nc(this,ye);if(Df(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),z!=4||h.length!=0||this.h.h||(this.m=1,De(16),o=!1),this.o=this.o&&o,!o)tr(this.i,this.l,h,"[Invalid Chunked Response]"),wn(this),Xr(this);else if(h.length>0&&!this.W){this.W=!0;var O=this.j;O.g==this&&O.aa&&!O.P&&(O.j.info("Great, no buffering proxy detected. Bytes received: "+h.length),lc(O),O.P=!0,De(11))}}else tr(this.i,this.l,h,null),nc(this,h);z==4&&wn(this),this.o&&!this.K&&(z==4?sp(this.j,this):(this.o=!1,Oi(this)))}else kA(this.g),u==400&&h.indexOf("Unknown SID")>0?(this.m=3,De(12)):(this.m=0,De(13)),wn(this),Xr(this)}}}catch{}finally{}};function mA(o){if(!Df(o))return o.g.la();const u=Jf(o.g);if(u==="")return"";let h="";const p=u.length,v=Jt(o.g)==4;if(!o.h.i){if(typeof TextDecoder>"u")return wn(o),Xr(o),"";o.h.i=new a.TextDecoder}for(let b=0;b<p;b++)o.h.h=!0,h+=o.h.i.decode(u[b],{stream:!(v&&b==p-1)});return u.length=0,o.h.g+=h,o.C=0,o.h.g}function Df(o){return o.g?o.v=="GET"&&o.M!=2&&o.j.Aa:!1}function gA(o,u){var h=o.C,p=u.indexOf(`
20
- `,h);return p==-1?Za:(h=Number(u.substring(h,p)),isNaN(h)?kf:(p+=1,p+h>u.length?Za:(u=u.slice(p,p+h),o.C=p+h,u)))}Kt.prototype.cancel=function(){this.K=!0,wn(this)};function Oi(o){o.T=Date.now()+o.H,Of(o,o.H)}function Of(o,u){if(o.D!=null)throw Error("WatchDog timer not null");o.D=Qr(d(o.aa,o),u)}function tc(o){o.D&&(a.clearTimeout(o.D),o.D=null)}Kt.prototype.aa=function(){this.D=null;const o=Date.now();o-this.T>=0?(dA(this.i,this.B),this.M!=2&&(Kr(),De(17)),wn(this),this.m=2,Xr(this)):Of(this,this.T-o)};function Xr(o){o.j.I==0||o.K||sp(o.j,o)}function wn(o){tc(o);var u=o.O;u&&typeof u.dispose=="function"&&u.dispose(),o.O=null,Tf(o.V),o.g&&(u=o.g,o.g=null,u.abort(),u.dispose())}function nc(o,u){try{var h=o.j;if(h.I!=0&&(h.g==o||rc(h.h,o))){if(!o.L&&rc(h.h,o)&&h.I==3){try{var p=h.Ba.g.parse(u)}catch{p=null}if(Array.isArray(p)&&p.length==3){var v=p;if(v[0]==0){e:if(!h.v){if(h.g)if(h.g.F+3e3<o.F)Fi(h),xi(h);else break e;uc(h),De(18)}}else h.xa=v[1],0<h.xa-h.K&&v[2]<37500&&h.F&&h.A==0&&!h.C&&(h.C=Qr(d(h.Va,h),6e3));Mf(h.h)<=1&&h.ta&&(h.ta=void 0)}else vn(h,11)}else if((o.L||h.g==o)&&Fi(h),!y(u))for(v=h.Ba.g.parse(u),u=0;u<v.length;u++){let Z=v[u];const ye=Z[0];if(!(ye<=h.K))if(h.K=ye,Z=Z[1],h.I==2)if(Z[0]=="c"){h.M=Z[1],h.ba=Z[2];const gt=Z[3];gt!=null&&(h.ka=gt,h.j.info("VER="+h.ka));const An=Z[4];An!=null&&(h.za=An,h.j.info("SVER="+h.za));const Xt=Z[5];Xt!=null&&typeof Xt=="number"&&Xt>0&&(p=1.5*Xt,h.O=p,h.j.info("backChannelRequestTimeoutMs_="+p)),p=h;const Zt=o.g;if(Zt){const qi=Zt.g?Zt.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(qi){var b=p.h;b.g||qi.indexOf("spdy")==-1&&qi.indexOf("quic")==-1&&qi.indexOf("h2")==-1||(b.j=b.l,b.g=new Set,b.h&&(sc(b,b.h),b.h=null))}if(p.G){const hc=Zt.g?Zt.g.getResponseHeader("X-HTTP-Session-Id"):null;hc&&(p.wa=hc,ne(p.J,p.G,hc))}}h.I=3,h.l&&h.l.ra(),h.aa&&(h.T=Date.now()-o.F,h.j.info("Handshake RTT: "+h.T+"ms")),p=h;var O=o;if(p.na=ap(p,p.L?p.ba:null,p.W),O.L){xf(p.h,O);var z=O,me=p.O;me&&(z.H=me),z.D&&(tc(z),Oi(z)),p.g=O}else np(p);h.i.length>0&&Ui(h)}else Z[0]!="stop"&&Z[0]!="close"||vn(h,7);else h.I==3&&(Z[0]=="stop"||Z[0]=="close"?Z[0]=="stop"?vn(h,7):cc(h):Z[0]!="noop"&&h.l&&h.l.qa(Z),h.A=0)}}Kr(4)}catch{}}var _A=class{constructor(o,u){this.g=o,this.map=u}};function Vf(o){this.l=o||10,a.PerformanceNavigationTiming?(o=a.performance.getEntriesByType("navigation"),o=o.length>0&&(o[0].nextHopProtocol=="hq"||o[0].nextHopProtocol=="h2")):o=!!(a.chrome&&a.chrome.loadTimes&&a.chrome.loadTimes()&&a.chrome.loadTimes().wasFetchedViaSpdy),this.j=o?this.l:1,this.g=null,this.j>1&&(this.g=new Set),this.h=null,this.i=[]}function Lf(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function Mf(o){return o.h?1:o.g?o.g.size:0}function rc(o,u){return o.h?o.h==u:o.g?o.g.has(u):!1}function sc(o,u){o.g?o.g.add(u):o.h=u}function xf(o,u){o.h&&o.h==u?o.h=null:o.g&&o.g.has(u)&&o.g.delete(u)}Vf.prototype.cancel=function(){if(this.i=Uf(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(const o of this.g.values())o.cancel();this.g.clear()}};function Uf(o){if(o.h!=null)return o.i.concat(o.h.G);if(o.g!=null&&o.g.size!==0){let u=o.i;for(const h of o.g.values())u=u.concat(h.G);return u}return R(o.i)}var Ff=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function yA(o,u){if(o){o=o.split("&");for(let h=0;h<o.length;h++){const p=o[h].indexOf("=");let v,b=null;p>=0?(v=o[h].substring(0,p),b=o[h].substring(p+1)):v=o[h],u(v,b?decodeURIComponent(b.replace(/\+/g," ")):"")}}}function Qt(o){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let u;o instanceof Qt?(this.l=o.l,Zr(this,o.j),this.o=o.o,this.g=o.g,es(this,o.u),this.h=o.h,ic(this,Hf(o.i)),this.m=o.m):o&&(u=String(o).match(Ff))?(this.l=!1,Zr(this,u[1]||"",!0),this.o=ts(u[2]||""),this.g=ts(u[3]||"",!0),es(this,u[4]),this.h=ts(u[5]||"",!0),ic(this,u[6]||"",!0),this.m=ts(u[7]||"")):(this.l=!1,this.i=new rs(null,this.l))}Qt.prototype.toString=function(){const o=[];var u=this.j;u&&o.push(ns(u,Bf,!0),":");var h=this.g;return(h||u=="file")&&(o.push("//"),(u=this.o)&&o.push(ns(u,Bf,!0),"@"),o.push(Jr(h).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),h=this.u,h!=null&&o.push(":",String(h))),(h=this.h)&&(this.g&&h.charAt(0)!="/"&&o.push("/"),o.push(ns(h,h.charAt(0)=="/"?wA:TA,!0))),(h=this.i.toString())&&o.push("?",h),(h=this.m)&&o.push("#",ns(h,vA)),o.join("")},Qt.prototype.resolve=function(o){const u=mt(this);let h=!!o.j;h?Zr(u,o.j):h=!!o.o,h?u.o=o.o:h=!!o.g,h?u.g=o.g:h=o.u!=null;var p=o.h;if(h)es(u,o.u);else if(h=!!o.h){if(p.charAt(0)!="/")if(this.g&&!this.h)p="/"+p;else{var v=u.h.lastIndexOf("/");v!=-1&&(p=u.h.slice(0,v+1)+p)}if(v=p,v==".."||v==".")p="";else if(v.indexOf("./")!=-1||v.indexOf("/.")!=-1){p=v.lastIndexOf("/",0)==0,v=v.split("/");const b=[];for(let O=0;O<v.length;){const z=v[O++];z=="."?p&&O==v.length&&b.push(""):z==".."?((b.length>1||b.length==1&&b[0]!="")&&b.pop(),p&&O==v.length&&b.push("")):(b.push(z),p=!0)}p=b.join("/")}else p=v}return h?u.h=p:h=o.i.toString()!=="",h?ic(u,Hf(o.i)):h=!!o.m,h&&(u.m=o.m),u};function mt(o){return new Qt(o)}function Zr(o,u,h){o.j=h?ts(u,!0):u,o.j&&(o.j=o.j.replace(/:$/,""))}function es(o,u){if(u){if(u=Number(u),isNaN(u)||u<0)throw Error("Bad port number "+u);o.u=u}else o.u=null}function ic(o,u,h){u instanceof rs?(o.i=u,AA(o.i,o.l)):(h||(u=ns(u,IA)),o.i=new rs(u,o.l))}function ne(o,u,h){o.i.set(u,h)}function Vi(o){return ne(o,"zx",Math.floor(Math.random()*2147483648).toString(36)+Math.abs(Math.floor(Math.random()*2147483648)^Date.now()).toString(36)),o}function ts(o,u){return o?u?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function ns(o,u,h){return typeof o=="string"?(o=encodeURI(o).replace(u,EA),h&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function EA(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var Bf=/[#\/\?@]/g,TA=/[#\?:]/g,wA=/[#\?]/g,IA=/[#\?@]/g,vA=/#/g;function rs(o,u){this.h=this.g=null,this.i=o||null,this.j=!!u}function In(o){o.g||(o.g=new Map,o.h=0,o.i&&yA(o.i,function(u,h){o.add(decodeURIComponent(u.replace(/\+/g," ")),h)}))}n=rs.prototype,n.add=function(o,u){In(this),this.i=null,o=nr(this,o);let h=this.g.get(o);return h||this.g.set(o,h=[]),h.push(u),this.h+=1,this};function qf(o,u){In(o),u=nr(o,u),o.g.has(u)&&(o.i=null,o.h-=o.g.get(u).length,o.g.delete(u))}function jf(o,u){return In(o),u=nr(o,u),o.g.has(u)}n.forEach=function(o,u){In(this),this.g.forEach(function(h,p){h.forEach(function(v){o.call(u,v,p,this)},this)},this)};function $f(o,u){In(o);let h=[];if(typeof u=="string")jf(o,u)&&(h=h.concat(o.g.get(nr(o,u))));else for(o=Array.from(o.g.values()),u=0;u<o.length;u++)h=h.concat(o[u]);return h}n.set=function(o,u){return In(this),this.i=null,o=nr(this,o),jf(this,o)&&(this.h-=this.g.get(o).length),this.g.set(o,[u]),this.h+=1,this},n.get=function(o,u){return o?(o=$f(this,o),o.length>0?String(o[0]):u):u};function zf(o,u,h){qf(o,u),h.length>0&&(o.i=null,o.g.set(nr(o,u),R(h)),o.h+=h.length)}n.toString=function(){if(this.i)return this.i;if(!this.g)return"";const o=[],u=Array.from(this.g.keys());for(let p=0;p<u.length;p++){var h=u[p];const v=Jr(h);h=$f(this,h);for(let b=0;b<h.length;b++){let O=v;h[b]!==""&&(O+="="+Jr(h[b])),o.push(O)}}return this.i=o.join("&")};function Hf(o){const u=new rs;return u.i=o.i,o.g&&(u.g=new Map(o.g),u.h=o.h),u}function nr(o,u){return u=String(u),o.j&&(u=u.toLowerCase()),u}function AA(o,u){u&&!o.j&&(In(o),o.i=null,o.g.forEach(function(h,p){const v=p.toLowerCase();p!=v&&(qf(this,p),zf(this,v,h))},o)),o.j=u}function RA(o,u){const h=new Yr;if(a.Image){const p=new Image;p.onload=f(Yt,h,"TestLoadImage: loaded",!0,u,p),p.onerror=f(Yt,h,"TestLoadImage: error",!1,u,p),p.onabort=f(Yt,h,"TestLoadImage: abort",!1,u,p),p.ontimeout=f(Yt,h,"TestLoadImage: timeout",!1,u,p),a.setTimeout(function(){p.ontimeout&&p.ontimeout()},1e4),p.src=o}else u(!1)}function bA(o,u){const h=new Yr,p=new AbortController,v=setTimeout(()=>{p.abort(),Yt(h,"TestPingServer: timeout",!1,u)},1e4);fetch(o,{signal:p.signal}).then(b=>{clearTimeout(v),b.ok?Yt(h,"TestPingServer: ok",!0,u):Yt(h,"TestPingServer: server error",!1,u)}).catch(()=>{clearTimeout(v),Yt(h,"TestPingServer: error",!1,u)})}function Yt(o,u,h,p,v){try{v&&(v.onload=null,v.onerror=null,v.onabort=null,v.ontimeout=null),p(h)}catch{}}function PA(){this.g=new uA}function oc(o){this.i=o.Sb||null,this.h=o.ab||!1}m(oc,wf),oc.prototype.g=function(){return new Li(this.i,this.h)};function Li(o,u){Se.call(this),this.H=o,this.o=u,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}m(Li,Se),n=Li.prototype,n.open=function(o,u){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.F=o,this.D=u,this.readyState=1,is(this)},n.send=function(o){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;const u={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};o&&(u.body=o),(this.H||a).fetch(new Request(this.D,u)).then(this.Pa.bind(this),this.ga.bind(this))},n.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),this.readyState>=1&&this.g&&this.readyState!=4&&(this.g=!1,ss(this)),this.readyState=0},n.Pa=function(o){if(this.g&&(this.l=o,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=o.headers,this.readyState=2,is(this)),this.g&&(this.readyState=3,is(this),this.g)))if(this.responseType==="arraybuffer")o.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(typeof a.ReadableStream<"u"&&"body"in o){if(this.j=o.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.B=new TextDecoder;Wf(this)}else o.text().then(this.Oa.bind(this),this.ga.bind(this))};function Wf(o){o.j.read().then(o.Ma.bind(o)).catch(o.ga.bind(o))}n.Ma=function(o){if(this.g){if(this.o&&o.value)this.response.push(o.value);else if(!this.o){var u=o.value?o.value:new Uint8Array(0);(u=this.B.decode(u,{stream:!o.done}))&&(this.response=this.responseText+=u)}o.done?ss(this):is(this),this.readyState==3&&Wf(this)}},n.Oa=function(o){this.g&&(this.response=this.responseText=o,ss(this))},n.Na=function(o){this.g&&(this.response=o,ss(this))},n.ga=function(){this.g&&ss(this)};function ss(o){o.readyState=4,o.l=null,o.j=null,o.B=null,is(o)}n.setRequestHeader=function(o,u){this.A.append(o,u)},n.getResponseHeader=function(o){return this.h&&this.h.get(o.toLowerCase())||""},n.getAllResponseHeaders=function(){if(!this.h)return"";const o=[],u=this.h.entries();for(var h=u.next();!h.done;)h=h.value,o.push(h[0]+": "+h[1]),h=u.next();return o.join(`\r
21
- `)};function is(o){o.onreadystatechange&&o.onreadystatechange.call(o)}Object.defineProperty(Li.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(o){this.m=o?"include":"same-origin"}});function Gf(o){let u="";return Si(o,function(h,p){u+=p,u+=":",u+=h,u+=`\r
22
- `}),u}function ac(o,u,h){e:{for(p in h){var p=!1;break e}p=!0}p||(h=Gf(h),typeof o=="string"?h!=null&&Jr(h):ne(o,u,h))}function oe(o){Se.call(this),this.headers=new Map,this.L=o||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}m(oe,Se);var SA=/^https?$/i,CA=["POST","PUT"];n=oe.prototype,n.Fa=function(o){this.H=o},n.ea=function(o,u,h,p){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+o);u=u?u.toUpperCase():"GET",this.D=o,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=this.L?this.L.g():Sf.g(),this.g.onreadystatechange=g(d(this.Ca,this));try{this.B=!0,this.g.open(u,String(o),!0),this.B=!1}catch(b){Kf(this,b);return}if(o=h||"",h=new Map(this.headers),p)if(Object.getPrototypeOf(p)===Object.prototype)for(var v in p)h.set(v,p[v]);else if(typeof p.keys=="function"&&typeof p.get=="function")for(const b of p.keys())h.set(b,p.get(b));else throw Error("Unknown input type for opt_headers: "+String(p));p=Array.from(h.keys()).find(b=>b.toLowerCase()=="content-type"),v=a.FormData&&o instanceof a.FormData,!(Array.prototype.indexOf.call(CA,u,void 0)>=0)||p||v||h.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[b,O]of h)this.g.setRequestHeader(b,O);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(o),this.v=!1}catch(b){Kf(this,b)}};function Kf(o,u){o.h=!1,o.g&&(o.j=!0,o.g.abort(),o.j=!1),o.l=u,o.o=5,Qf(o),Mi(o)}function Qf(o){o.A||(o.A=!0,Ne(o,"complete"),Ne(o,"error"))}n.abort=function(o){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=o||7,Ne(this,"complete"),Ne(this,"abort"),Mi(this))},n.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Mi(this,!0)),oe.Z.N.call(this)},n.Ca=function(){this.u||(this.B||this.v||this.j?Yf(this):this.Xa())},n.Xa=function(){Yf(this)};function Yf(o){if(o.h&&typeof i<"u"){if(o.v&&Jt(o)==4)setTimeout(o.Ca.bind(o),0);else if(Ne(o,"readystatechange"),Jt(o)==4){o.h=!1;try{const b=o.ca();e:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var u=!0;break e;default:u=!1}var h;if(!(h=u)){var p;if(p=b===0){let O=String(o.D).match(Ff)[1]||null;!O&&a.self&&a.self.location&&(O=a.self.location.protocol.slice(0,-1)),p=!SA.test(O?O.toLowerCase():"")}h=p}if(h)Ne(o,"complete"),Ne(o,"success");else{o.o=6;try{var v=Jt(o)>2?o.g.statusText:""}catch{v=""}o.l=v+" ["+o.ca()+"]",Qf(o)}}finally{Mi(o)}}}}function Mi(o,u){if(o.g){o.m&&(clearTimeout(o.m),o.m=null);const h=o.g;o.g=null,u||Ne(o,"ready");try{h.onreadystatechange=null}catch{}}}n.isActive=function(){return!!this.g};function Jt(o){return o.g?o.g.readyState:0}n.ca=function(){try{return Jt(this)>2?this.g.status:-1}catch{return-1}},n.la=function(){try{return this.g?this.g.responseText:""}catch{return""}},n.La=function(o){if(this.g){var u=this.g.responseText;return o&&u.indexOf(o)==0&&(u=u.substring(o.length)),cA(u)}};function Jf(o){try{if(!o.g)return null;if("response"in o.g)return o.g.response;switch(o.F){case"":case"text":return o.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in o.g)return o.g.mozResponseArrayBuffer}return null}catch{return null}}function kA(o){const u={};o=(o.g&&Jt(o)>=2&&o.g.getAllResponseHeaders()||"").split(`\r
23
- `);for(let p=0;p<o.length;p++){if(y(o[p]))continue;var h=pA(o[p]);const v=h[0];if(h=h[1],typeof h!="string")continue;h=h.trim();const b=u[v]||[];u[v]=b,b.push(h)}nA(u,function(p){return p.join(", ")})}n.ya=function(){return this.o},n.Ha=function(){return typeof this.l=="string"?this.l:String(this.l)};function os(o,u,h){return h&&h.internalChannelParams&&h.internalChannelParams[o]||u}function Xf(o){this.za=0,this.i=[],this.j=new Yr,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=os("failFast",!1,o),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=os("baseRetryDelayMs",5e3,o),this.Za=os("retryDelaySeedMs",1e4,o),this.Ta=os("forwardChannelMaxRetries",2,o),this.va=os("forwardChannelRequestTimeoutMs",2e4,o),this.ma=o&&o.xmlHttpFactory||void 0,this.Ua=o&&o.Rb||void 0,this.Aa=o&&o.useFetchStreams||!1,this.O=void 0,this.L=o&&o.supportsCrossDomainXhr||!1,this.M="",this.h=new Vf(o&&o.concurrentRequestLimit),this.Ba=new PA,this.S=o&&o.fastHandshake||!1,this.R=o&&o.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=o&&o.Pb||!1,o&&o.ua&&this.j.ua(),o&&o.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&o&&o.detectBufferingProxy||!1,this.ia=void 0,o&&o.longPollingTimeout&&o.longPollingTimeout>0&&(this.ia=o.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}n=Xf.prototype,n.ka=8,n.I=1,n.connect=function(o,u,h,p){De(0),this.W=o,this.H=u||{},h&&p!==void 0&&(this.H.OSID=h,this.H.OAID=p),this.F=this.X,this.J=ap(this,null,this.W),Ui(this)};function cc(o){if(Zf(o),o.I==3){var u=o.V++,h=mt(o.J);if(ne(h,"SID",o.M),ne(h,"RID",u),ne(h,"TYPE","terminate"),as(o,h),u=new Kt(o,o.j,u),u.M=2,u.A=Vi(mt(h)),h=!1,a.navigator&&a.navigator.sendBeacon)try{h=a.navigator.sendBeacon(u.A.toString(),"")}catch{}!h&&a.Image&&(new Image().src=u.A,h=!0),h||(u.g=cp(u.j,null),u.g.ea(u.A)),u.F=Date.now(),Oi(u)}op(o)}function xi(o){o.g&&(lc(o),o.g.cancel(),o.g=null)}function Zf(o){xi(o),o.v&&(a.clearTimeout(o.v),o.v=null),Fi(o),o.h.cancel(),o.m&&(typeof o.m=="number"&&a.clearTimeout(o.m),o.m=null)}function Ui(o){if(!Lf(o.h)&&!o.m){o.m=!0;var u=o.Ea;_e||_(),re||(_e(),re=!0),w.add(u,o),o.D=0}}function NA(o,u){return Mf(o.h)>=o.h.j-(o.m?1:0)?!1:o.m?(o.i=u.G.concat(o.i),!0):o.I==1||o.I==2||o.D>=(o.Sa?0:o.Ta)?!1:(o.m=Qr(d(o.Ea,o,u),ip(o,o.D)),o.D++,!0)}n.Ea=function(o){if(this.m)if(this.m=null,this.I==1){if(!o){this.V=Math.floor(Math.random()*1e5),o=this.V++;const v=new Kt(this,this.j,o);let b=this.o;if(this.U&&(b?(b=hf(b),ff(b,this.U)):b=this.U),this.u!==null||this.R||(v.J=b,b=null),this.S)e:{for(var u=0,h=0;h<this.i.length;h++){t:{var p=this.i[h];if("__data__"in p.map&&(p=p.map.__data__,typeof p=="string")){p=p.length;break t}p=void 0}if(p===void 0)break;if(u+=p,u>4096){u=h;break e}if(u===4096||h===this.i.length-1){u=h+1;break e}}u=1e3}else u=1e3;u=tp(this,v,u),h=mt(this.J),ne(h,"RID",o),ne(h,"CVER",22),this.G&&ne(h,"X-HTTP-Session-Id",this.G),as(this,h),b&&(this.R?u="headers="+Jr(Gf(b))+"&"+u:this.u&&ac(h,this.u,b)),sc(this.h,v),this.Ra&&ne(h,"TYPE","init"),this.S?(ne(h,"$req",u),ne(h,"SID","null"),v.U=!0,ec(v,h,null)):ec(v,h,u),this.I=2}}else this.I==3&&(o?ep(this,o):this.i.length==0||Lf(this.h)||ep(this))};function ep(o,u){var h;u?h=u.l:h=o.V++;const p=mt(o.J);ne(p,"SID",o.M),ne(p,"RID",h),ne(p,"AID",o.K),as(o,p),o.u&&o.o&&ac(p,o.u,o.o),h=new Kt(o,o.j,h,o.D+1),o.u===null&&(h.J=o.o),u&&(o.i=u.G.concat(o.i)),u=tp(o,h,1e3),h.H=Math.round(o.va*.5)+Math.round(o.va*.5*Math.random()),sc(o.h,h),ec(h,p,u)}function as(o,u){o.H&&Si(o.H,function(h,p){ne(u,p,h)}),o.l&&Si({},function(h,p){ne(u,p,h)})}function tp(o,u,h){h=Math.min(o.i.length,h);const p=o.l?d(o.l.Ka,o.l,o):null;e:{var v=o.i;let z=-1;for(;;){const me=["count="+h];z==-1?h>0?(z=v[0].g,me.push("ofs="+z)):z=0:me.push("ofs="+z);let Z=!0;for(let ye=0;ye<h;ye++){var b=v[ye].g;const gt=v[ye].map;if(b-=z,b<0)z=Math.max(0,v[ye].g-100),Z=!1;else try{b="req"+b+"_"||"";try{var O=gt instanceof Map?gt:Object.entries(gt);for(const[An,Xt]of O){let Zt=Xt;c(Xt)&&(Zt=Qa(Xt)),me.push(b+An+"="+encodeURIComponent(Zt))}}catch(An){throw me.push(b+"type="+encodeURIComponent("_badmap")),An}}catch{p&&p(gt)}}if(Z){O=me.join("&");break e}}O=void 0}return o=o.i.splice(0,h),u.G=o,O}function np(o){if(!o.g&&!o.v){o.Y=1;var u=o.Da;_e||_(),re||(_e(),re=!0),w.add(u,o),o.A=0}}function uc(o){return o.g||o.v||o.A>=3?!1:(o.Y++,o.v=Qr(d(o.Da,o),ip(o,o.A)),o.A++,!0)}n.Da=function(){if(this.v=null,rp(this),this.aa&&!(this.P||this.g==null||this.T<=0)){var o=4*this.T;this.j.info("BP detection timer enabled: "+o),this.B=Qr(d(this.Wa,this),o)}},n.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,De(10),xi(this),rp(this))};function lc(o){o.B!=null&&(a.clearTimeout(o.B),o.B=null)}function rp(o){o.g=new Kt(o,o.j,"rpc",o.Y),o.u===null&&(o.g.J=o.o),o.g.P=0;var u=mt(o.na);ne(u,"RID","rpc"),ne(u,"SID",o.M),ne(u,"AID",o.K),ne(u,"CI",o.F?"0":"1"),!o.F&&o.ia&&ne(u,"TO",o.ia),ne(u,"TYPE","xmlhttp"),as(o,u),o.u&&o.o&&ac(u,o.u,o.o),o.O&&(o.g.H=o.O);var h=o.g;o=o.ba,h.M=1,h.A=Vi(mt(u)),h.u=null,h.R=!0,Nf(h,o)}n.Va=function(){this.C!=null&&(this.C=null,xi(this),uc(this),De(19))};function Fi(o){o.C!=null&&(a.clearTimeout(o.C),o.C=null)}function sp(o,u){var h=null;if(o.g==u){Fi(o),lc(o),o.g=null;var p=2}else if(rc(o.h,u))h=u.G,xf(o.h,u),p=1;else return;if(o.I!=0){if(u.o)if(p==1){h=u.u?u.u.length:0,u=Date.now()-u.F;var v=o.D;p=Ni(),Ne(p,new bf(p,h)),Ui(o)}else np(o);else if(v=u.m,v==3||v==0&&u.X>0||!(p==1&&NA(o,u)||p==2&&uc(o)))switch(h&&h.length>0&&(u=o.h,u.i=u.i.concat(h)),v){case 1:vn(o,5);break;case 4:vn(o,10);break;case 3:vn(o,6);break;default:vn(o,2)}}}function ip(o,u){let h=o.Qa+Math.floor(Math.random()*o.Za);return o.isActive()||(h*=2),h*u}function vn(o,u){if(o.j.info("Error code "+u),u==2){var h=d(o.bb,o),p=o.Ua;const v=!p;p=new Qt(p||"//www.google.com/images/cleardot.gif"),a.location&&a.location.protocol=="http"||Zr(p,"https"),Vi(p),v?RA(p.toString(),h):bA(p.toString(),h)}else De(2);o.I=0,o.l&&o.l.pa(u),op(o),Zf(o)}n.bb=function(o){o?(this.j.info("Successfully pinged google.com"),De(2)):(this.j.info("Failed to ping google.com"),De(1))};function op(o){if(o.I=0,o.ja=[],o.l){const u=Uf(o.h);(u.length!=0||o.i.length!=0)&&(C(o.ja,u),C(o.ja,o.i),o.h.i.length=0,R(o.i),o.i.length=0),o.l.oa()}}function ap(o,u,h){var p=h instanceof Qt?mt(h):new Qt(h);if(p.g!="")u&&(p.g=u+"."+p.g),es(p,p.u);else{var v=a.location;p=v.protocol,u=u?u+"."+v.hostname:v.hostname,v=+v.port;const b=new Qt(null);p&&Zr(b,p),u&&(b.g=u),v&&es(b,v),h&&(b.h=h),p=b}return h=o.G,u=o.wa,h&&u&&ne(p,h,u),ne(p,"VER",o.ka),as(o,p),p}function cp(o,u,h){if(u&&!o.L)throw Error("Can't create secondary domain capable XhrIo object.");return u=o.Aa&&!o.ma?new oe(new oc({ab:h})):new oe(o.ma),u.Fa(o.L),u}n.isActive=function(){return!!this.l&&this.l.isActive(this)};function up(){}n=up.prototype,n.ra=function(){},n.qa=function(){},n.pa=function(){},n.oa=function(){},n.isActive=function(){return!0},n.Ka=function(){};function Bi(){}Bi.prototype.g=function(o,u){return new qe(o,u)};function qe(o,u){Se.call(this),this.g=new Xf(u),this.l=o,this.h=u&&u.messageUrlParams||null,o=u&&u.messageHeaders||null,u&&u.clientProtocolHeaderRequired&&(o?o["X-Client-Protocol"]="webchannel":o={"X-Client-Protocol":"webchannel"}),this.g.o=o,o=u&&u.initMessageHeaders||null,u&&u.messageContentType&&(o?o["X-WebChannel-Content-Type"]=u.messageContentType:o={"X-WebChannel-Content-Type":u.messageContentType}),u&&u.sa&&(o?o["X-WebChannel-Client-Profile"]=u.sa:o={"X-WebChannel-Client-Profile":u.sa}),this.g.U=o,(o=u&&u.Qb)&&!y(o)&&(this.g.u=o),this.A=u&&u.supportsCrossDomainXhr||!1,this.v=u&&u.sendRawJson||!1,(u=u&&u.httpSessionIdParam)&&!y(u)&&(this.g.G=u,o=this.h,o!==null&&u in o&&(o=this.h,u in o&&delete o[u])),this.j=new rr(this)}m(qe,Se),qe.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},qe.prototype.close=function(){cc(this.g)},qe.prototype.o=function(o){var u=this.g;if(typeof o=="string"){var h={};h.__data__=o,o=h}else this.v&&(h={},h.__data__=Qa(o),o=h);u.i.push(new _A(u.Ya++,o)),u.I==3&&Ui(u)},qe.prototype.N=function(){this.g.l=null,delete this.j,cc(this.g),delete this.g,qe.Z.N.call(this)};function lp(o){Ya.call(this),o.__headers__&&(this.headers=o.__headers__,this.statusCode=o.__status__,delete o.__headers__,delete o.__status__);var u=o.__sm__;if(u){e:{for(const h in u){o=h;break e}o=void 0}(this.i=o)&&(o=this.i,u=u!==null&&o in u?u[o]:void 0),this.data=u}else this.data=o}m(lp,Ya);function hp(){Ja.call(this),this.status=1}m(hp,Ja);function rr(o){this.g=o}m(rr,up),rr.prototype.ra=function(){Ne(this.g,"a")},rr.prototype.qa=function(o){Ne(this.g,new lp(o))},rr.prototype.pa=function(o){Ne(this.g,new hp)},rr.prototype.oa=function(){Ne(this.g,"b")},Bi.prototype.createWebChannel=Bi.prototype.g,qe.prototype.send=qe.prototype.o,qe.prototype.open=qe.prototype.m,qe.prototype.close=qe.prototype.close,Bc=function(){return new Bi},Fc=function(){return Ni()},Uc=Tn,to={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},Di.NO_ERROR=0,Di.TIMEOUT=8,Di.HTTP_ERROR=6,ms=Di,Pf.COMPLETE="complete",xc=Pf,If.EventType=Gr,Gr.OPEN="a",Gr.CLOSE="b",Gr.ERROR="c",Gr.MESSAGE="d",Se.prototype.listen=Se.prototype.J,pr=If,oe.prototype.listenOnce=oe.prototype.K,oe.prototype.getLastError=oe.prototype.Ha,oe.prototype.getLastErrorCode=oe.prototype.ya,oe.prototype.getStatus=oe.prototype.ca,oe.prototype.getResponseJson=oe.prototype.La,oe.prototype.getResponseText=oe.prototype.la,oe.prototype.send=oe.prototype.ea,oe.prototype.setWithCredentials=oe.prototype.Fa,Mc=oe}).apply(typeof ps<"u"?ps:typeof self<"u"?self:typeof window<"u"?window:{});class Re{constructor(e){this.uid=e}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}Re.UNAUTHENTICATED=new Re(null),Re.GOOGLE_CREDENTIALS=new Re("google-credentials-uid"),Re.FIRST_PARTY=new Re("first-party-uid"),Re.MOCK_USER=new Re("mock-user");let Rn="12.8.0";function Gm(n){Rn=n}const rn=new zi("@firebase/firestore");function bn(){return rn.logLevel}function V(n,...e){if(rn.logLevel<=H.DEBUG){const t=e.map(no);rn.debug(`Firestore (${Rn}): ${n}`,...t)}}function Et(n,...e){if(rn.logLevel<=H.ERROR){const t=e.map(no);rn.error(`Firestore (${Rn}): ${n}`,...t)}}function Pn(n,...e){if(rn.logLevel<=H.WARN){const t=e.map(no);rn.warn(`Firestore (${Rn}): ${n}`,...t)}}function no(n){if(typeof n=="string")return n;try{return function(t){return JSON.stringify(t)}(n)}catch{return n}}function x(n,e,t){let r="Unexpected state";typeof e=="string"?r=e:t=e,qc(n,r,t)}function qc(n,e,t){let r=`FIRESTORE (${Rn}) INTERNAL ASSERTION FAILED: ${e} (ID: ${n.toString(16)})`;if(t!==void 0)try{r+=" CONTEXT: "+JSON.stringify(t)}catch{r+=" CONTEXT: "+t}throw Et(r),new Error(r)}function Y(n,e,t,r){let s="Unexpected state";typeof t=="string"?s=t:r=t,n||qc(e,s,r)}function U(n,e){return n}const P={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 D extends We{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class nt{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class jc{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Km{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Re.UNAUTHENTICATED))}shutdown(){}}class Qm{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 Ym{constructor(e){this.t=e,this.currentUser=Re.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){Y(this.o===void 0,42304);let r=this.i;const s=l=>this.i!==r?(r=this.i,t(l)):Promise.resolve();let i=new nt;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new nt,e.enqueueRetryable(()=>s(this.currentUser))};const a=()=>{const l=i;e.enqueueRetryable(async()=>{await l.promise,await s(this.currentUser)})},c=l=>{V("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=l,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit(l=>c(l)),setTimeout(()=>{if(!this.auth){const l=this.t.getImmediate({optional:!0});l?c(l):(V("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new nt)}},0),a()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(r=>this.i!==e?(V("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):r?(Y(typeof r.accessToken=="string",31837,{l:r}),new jc(r.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return Y(e===null||typeof e=="string",2055,{h:e}),new Re(e)}}class Jm{constructor(e,t,r){this.P=e,this.T=t,this.I=r,this.type="FirstParty",this.user=Re.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);const e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}}class Xm{constructor(e,t,r){this.P=e,this.T=t,this.I=r}getToken(){return Promise.resolve(new Jm(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(Re.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class $c{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class Zm{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,Ae(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){Y(this.o===void 0,3512);const r=i=>{i.error!=null&&V("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);const a=i.token!==this.m;return this.m=i.token,V("FirebaseAppCheckTokenProvider",`Received ${a?"new":"existing"} token.`),a?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable(()=>r(i))};const s=i=>{V("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(i=>s(i)),setTimeout(()=>{if(!this.appCheck){const i=this.V.getImmediate({optional:!0});i?s(i):V("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new $c(this.p));const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(t=>t?(Y(typeof t.token=="string",44558,{tokenResult:t}),this.m=t.token,new $c(t.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function eg(n){const e=typeof self<"u"&&(self.crypto||self.msCrypto),t=new Uint8Array(n);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let r=0;r<n;r++)t[r]=Math.floor(256*Math.random());return t}class ro{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516);let r="";for(;r.length<20;){const s=eg(40);for(let i=0;i<s.length;++i)r.length<20&&s[i]<t&&(r+=e.charAt(s[i]%62))}return r}}function W(n,e){return n<e?-1:n>e?1:0}function so(n,e){const t=Math.min(n.length,e.length);for(let r=0;r<t;r++){const s=n.charAt(r),i=e.charAt(r);if(s!==i)return io(s)===io(i)?W(s,i):io(s)?1:-1}return W(n.length,e.length)}const tg=55296,ng=57343;function io(n){const e=n.charCodeAt(0);return e>=tg&&e<=ng}function Sn(n,e,t){return n.length===e.length&&n.every((r,s)=>t(r,e[s]))}const zc="__name__";class rt{constructor(e,t,r){t===void 0?t=0:t>e.length&&x(637,{offset:t,range:e.length}),r===void 0?r=e.length-t:r>e.length-t&&x(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return rt.comparator(this,e)===0}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof rt?e.forEach(r=>{t.push(r)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=e===void 0?1:e,this.construct(this.segments,this.offset+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 this.length===0}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const r=Math.min(e.length,t.length);for(let s=0;s<r;s++){const i=rt.compareSegments(e.get(s),t.get(s));if(i!==0)return i}return W(e.length,t.length)}static compareSegments(e,t){const r=rt.isNumericId(e),s=rt.isNumericId(t);return r&&!s?-1:!r&&s?1:r&&s?rt.extractNumericId(e).compare(rt.extractNumericId(t)):so(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return kt.fromString(e.substring(4,e.length-2))}}class X extends rt{construct(e,t,r){return new X(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const r of e){if(r.indexOf("//")>=0)throw new D(P.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter(s=>s.length>0))}return new X(t)}static emptyPath(){return new X([])}}const rg=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Ee extends rt{construct(e,t,r){return new Ee(e,t,r)}static isValidIdentifier(e){return rg.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Ee.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)===zc}static keyField(){return new Ee([zc])}static fromServerFormat(e){const t=[];let r="",s=0;const i=()=>{if(r.length===0)throw new D(P.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(r),r=""};let a=!1;for(;s<e.length;){const c=e[s];if(c==="\\"){if(s+1===e.length)throw new D(P.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const l=e[s+1];if(l!=="\\"&&l!=="."&&l!=="`")throw new D(P.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=l,s+=2}else c==="`"?(a=!a,s++):c!=="."||a?(r+=c,s++):(i(),s++)}if(i(),a)throw new D(P.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Ee(t)}static emptyPath(){return new Ee([])}}class L{constructor(e){this.path=e}static fromPath(e){return new L(X.fromString(e))}static fromName(e){return new L(X.fromString(e).popFirst(5))}static empty(){return new L(X.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&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 e!==null&&X.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return X.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new L(new X(e.slice()))}}function Hc(n,e,t){if(!t)throw new D(P.INVALID_ARGUMENT,`Function ${n}() cannot be called with an empty ${e}.`)}function sg(n,e,t,r){if(e===!0&&r===!0)throw new D(P.INVALID_ARGUMENT,`${n} and ${t} cannot be used together.`)}function Wc(n){if(!L.isDocumentKey(n))throw new D(P.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${n} has ${n.length}.`)}function Gc(n){if(L.isDocumentKey(n))throw new D(P.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${n} has ${n.length}.`)}function Kc(n){return typeof n=="object"&&n!==null&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null)}function gs(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="string")return n.length>20&&(n=`${n.substring(0,20)}...`),JSON.stringify(n);if(typeof n=="number"||typeof n=="boolean")return""+n;if(typeof n=="object"){if(n instanceof Array)return"an array";{const e=function(r){return r.constructor?r.constructor.name:null}(n);return e?`a custom ${e} object`:"an object"}}return typeof n=="function"?"a function":x(12329,{type:typeof n})}function Ge(n,e){if("_delegate"in n&&(n=n._delegate),!(n instanceof e)){if(e.name===n.constructor.name)throw new D(P.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const t=gs(n);throw new D(P.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return n}function ig(n,e){if(e<=0)throw new D(P.INVALID_ARGUMENT,`Function ${n}() requires a positive number, but it was: ${e}.`)}function ue(n,e){const t={typeString:n};return e&&(t.value=e),t}function mr(n,e){if(!Kc(n))throw new D(P.INVALID_ARGUMENT,"JSON must be an object");let t;for(const r in e)if(e[r]){const s=e[r].typeString,i="value"in e[r]?{value:e[r].value}:void 0;if(!(r in n)){t=`JSON missing required field: '${r}'`;break}const a=n[r];if(s&&typeof a!==s){t=`JSON field '${r}' must be a ${s}.`;break}if(i!==void 0&&a!==i.value){t=`Expected '${r}' field to equal '${i.value}'`;break}}if(t)throw new D(P.INVALID_ARGUMENT,t);return!0}const Qc=-62135596800,Yc=1e6;class ee{static now(){return ee.fromMillis(Date.now())}static fromDate(e){return ee.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),r=Math.floor((e-1e3*t)*Yc);return new ee(t,r)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new D(P.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new D(P.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<Qc)throw new D(P.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new D(P.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/Yc}_compareTo(e){return this.seconds===e.seconds?W(this.nanoseconds,e.nanoseconds):W(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:ee._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(mr(e,ee._jsonSchema))return new ee(e.seconds,e.nanoseconds)}valueOf(){const e=this.seconds-Qc;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}ee._jsonSchemaVersion="firestore/timestamp/1.0",ee._jsonSchema={type:ue("string",ee._jsonSchemaVersion),seconds:ue("number"),nanoseconds:ue("number")};class B{static fromTimestamp(e){return new B(e)}static min(){return new B(new ee(0,0))}static max(){return new B(new ee(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}const gr=-1;function og(n,e){const t=n.toTimestamp().seconds,r=n.toTimestamp().nanoseconds+1,s=B.fromTimestamp(r===1e9?new ee(t+1,0):new ee(t,r));return new Nt(s,L.empty(),e)}function ag(n){return new Nt(n.readTime,n.key,gr)}class Nt{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new Nt(B.min(),L.empty(),gr)}static max(){return new Nt(B.max(),L.empty(),gr)}}function cg(n,e){let t=n.readTime.compareTo(e.readTime);return t!==0?t:(t=L.comparator(n.documentKey,e.documentKey),t!==0?t:W(n.largestBatchId,e.largestBatchId))}const ug="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class lg{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Cn(n){if(n.code!==P.FAILED_PRECONDITION||n.message!==ug)throw n;V("LocalStore","Unexpectedly lost primary lease")}class S{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(t=>{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)},t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&x(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new S((r,s)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(r,s)},this.catchCallback=i=>{this.wrapFailure(t,i).next(r,s)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{const t=e();return t instanceof S?t:S.resolve(t)}catch(t){return S.reject(t)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):S.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):S.reject(t)}static resolve(e){return new S((t,r)=>{t(e)})}static reject(e){return new S((t,r)=>{r(e)})}static waitFor(e){return new S((t,r)=>{let s=0,i=0,a=!1;e.forEach(c=>{++s,c.next(()=>{++i,a&&i===s&&t()},l=>r(l))}),a=!0,i===s&&t()})}static or(e){let t=S.resolve(!1);for(const r of e)t=t.next(s=>s?S.resolve(s):r());return t}static forEach(e,t){const r=[];return e.forEach((s,i)=>{r.push(t.call(this,s,i))}),this.waitFor(r)}static mapArray(e,t){return new S((r,s)=>{const i=e.length,a=new Array(i);let c=0;for(let l=0;l<i;l++){const d=l;t(e[d]).next(f=>{a[d]=f,++c,c===i&&r(a)},f=>s(f))}})}static doWhile(e,t){return new S((r,s)=>{const i=()=>{e()===!0?t().next(()=>{i()},s):r()};i()})}}function hg(n){const e=n.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function kn(n){return n.name==="IndexedDbTransactionError"}class _s{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=r=>this.ae(r),this.ue=r=>t.writeSequenceNumber(r))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.ue&&this.ue(e),e}}_s.ce=-1;const oo=-1;function ys(n){return n==null}function Es(n){return n===0&&1/n==-1/0}function dg(n){return typeof n=="number"&&Number.isInteger(n)&&!Es(n)&&n<=Number.MAX_SAFE_INTEGER&&n>=Number.MIN_SAFE_INTEGER}const Jc="";function fg(n){let e="";for(let t=0;t<n.length;t++)e.length>0&&(e=Xc(e)),e=pg(n.get(t),e);return Xc(e)}function pg(n,e){let t=e;const r=n.length;for(let s=0;s<r;s++){const i=n.charAt(s);switch(i){case"\0":t+="";break;case Jc:t+="";break;default:t+=i}}return t}function Xc(n){return n+Jc+""}function Zc(n){let e=0;for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&e++;return e}function Dt(n,e){for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&e(t,n[t])}function mg(n,e){const t=[];for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&t.push(e(n[r],r,n));return t}function eu(n){for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}class se{constructor(e,t){this.comparator=e,this.root=t||Te.EMPTY}insert(e,t){return new se(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Te.BLACK,null,null))}remove(e){return new se(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Te.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const r=this.comparator(e,t.key);if(r===0)return t.value;r<0?t=t.left:r>0&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){const s=this.comparator(e,r.key);if(s===0)return t+r.left.size;s<0?r=r.left:(t+=r.left.size+1,r=r.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,r)=>(e(t,r),!1))}toString(){const e=[];return this.inorderTraversal((t,r)=>(e.push(`${t}:${r}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new Ts(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Ts(this.root,e,this.comparator,!1)}getReverseIterator(){return new Ts(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Ts(this.root,e,this.comparator,!0)}}class Ts{constructor(e,t,r,s){this.isReverse=s,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&s&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(i===0){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const 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 this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class Te{constructor(e,t,r,s,i){this.key=e,this.value=t,this.color=r??Te.RED,this.left=s??Te.EMPTY,this.right=i??Te.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,s,i){return new Te(e??this.key,t??this.value,r??this.color,s??this.left,i??this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let s=this;const i=r(e,s.key);return s=i<0?s.copy(null,null,null,s.left.insert(e,t,r),null):i===0?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,r)),s.fixUp()}removeMin(){if(this.left.isEmpty())return Te.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 r,s=this;if(t(e,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),t(e,s.key)===0){if(s.right.isEmpty())return Te.EMPTY;r=s.right.min(),s=s.copy(r.key,r.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(e,t))}return s.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(){const e=this.copy(null,null,Te.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,Te.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const 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(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw x(43730,{key:this.key,value:this.value});if(this.right.isRed())throw x(14113,{key:this.key,value:this.value});const e=this.left.check();if(e!==this.right.check())throw x(27949);return e+(this.isRed()?0:1)}}Te.EMPTY=null,Te.RED=!0,Te.BLACK=!1,Te.EMPTY=new class{constructor(){this.size=0}get key(){throw x(57766)}get value(){throw x(16141)}get color(){throw x(16727)}get left(){throw x(29726)}get right(){throw x(36894)}copy(e,t,r,s,i){return this}insert(e,t,r){return new Te(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 fe{constructor(e){this.comparator=e,this.data=new se(this.comparator)}has(e){return this.data.get(e)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,r)=>(e(t),!1))}forEachInRange(e,t){const r=this.data.getIteratorFrom(e[0]);for(;r.hasNext();){const s=r.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.key)}}forEachWhile(e,t){let r;for(r=t!==void 0?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new tu(this.data.getIterator())}getIteratorFrom(e){return new tu(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(r=>{t=t.add(r)}),t}isEqual(e){if(!(e instanceof fe)||this.size!==e.size)return!1;const t=this.data.getIterator(),r=e.data.getIterator();for(;t.hasNext();){const s=t.getNext().key,i=r.getNext().key;if(this.comparator(s,i)!==0)return!1}return!0}toArray(){const e=[];return this.forEach(t=>{e.push(t)}),e}toString(){const e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){const t=new fe(this.comparator);return t.data=e,t}}class tu{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class Fe{constructor(e){this.fields=e,e.sort(Ee.comparator)}static empty(){return new Fe([])}unionWith(e){let t=new fe(Ee.comparator);for(const r of this.fields)t=t.add(r);for(const r of e)t=t.add(r);return new Fe(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Sn(this.fields,e.fields,(t,r)=>t.isEqual(r))}}class nu extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class we{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(s){try{return atob(s)}catch(i){throw typeof DOMException<"u"&&i instanceof DOMException?new nu("Invalid base64 string: "+i):i}}(e);return new we(t)}static fromUint8Array(e){const t=function(s){let i="";for(let a=0;a<s.length;++a)i+=String.fromCharCode(s[a]);return i}(e);return new we(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 function(t){return btoa(t)}(this.binaryString)}toUint8Array(){return function(t){const r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return W(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}we.EMPTY_BYTE_STRING=new we("");const gg=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Ot(n){if(Y(!!n,39018),typeof n=="string"){let e=0;const t=gg.exec(n);if(Y(!!t,46558,{timestamp:n}),t[1]){let s=t[1];s=(s+"000000000").substr(0,9),e=Number(s)}const r=new Date(n);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}return{seconds:ae(n.seconds),nanos:ae(n.nanos)}}function ae(n){return typeof n=="number"?n:typeof n=="string"?Number(n):0}function Vt(n){return typeof n=="string"?we.fromBase64String(n):we.fromUint8Array(n)}const ru="server_timestamp",su="__type__",iu="__previous_value__",ou="__local_write_time__";function ws(n){return(n?.mapValue?.fields||{})[su]?.stringValue===ru}function Is(n){const e=n.mapValue.fields[iu];return ws(e)?Is(e):e}function _r(n){const e=Ot(n.mapValue.fields[ou].timestampValue);return new ee(e.seconds,e.nanos)}class _g{constructor(e,t,r,s,i,a,c,l,d,f,m){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=s,this.ssl=i,this.forceLongPolling=a,this.autoDetectLongPolling=c,this.longPollingOptions=l,this.useFetchStreams=d,this.isUsingEmulator=f,this.apiKey=m}}const vs="(default)";class yr{constructor(e,t){this.projectId=e,this.database=t||vs}static empty(){return new yr("","")}get isDefaultDatabase(){return this.database===vs}isEqual(e){return e instanceof yr&&e.projectId===this.projectId&&e.database===this.database}}function yg(n,e){if(!Object.prototype.hasOwnProperty.apply(n.options,["projectId"]))throw new D(P.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new yr(n.options.projectId,e)}const au="__type__",Eg="__max__",As={mapValue:{}},cu="__vector__",Rs="value";function Lt(n){return"nullValue"in n?0:"booleanValue"in n?1:"integerValue"in n||"doubleValue"in n?2:"timestampValue"in n?3:"stringValue"in n?5:"bytesValue"in n?6:"referenceValue"in n?7:"geoPointValue"in n?8:"arrayValue"in n?9:"mapValue"in n?ws(n)?4:wg(n)?9007199254740991:Tg(n)?10:11:x(28295,{value:n})}function st(n,e){if(n===e)return!0;const t=Lt(n);if(t!==Lt(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return n.booleanValue===e.booleanValue;case 4:return _r(n).isEqual(_r(e));case 3:return function(s,i){if(typeof s.timestampValue=="string"&&typeof i.timestampValue=="string"&&s.timestampValue.length===i.timestampValue.length)return s.timestampValue===i.timestampValue;const a=Ot(s.timestampValue),c=Ot(i.timestampValue);return a.seconds===c.seconds&&a.nanos===c.nanos}(n,e);case 5:return n.stringValue===e.stringValue;case 6:return function(s,i){return Vt(s.bytesValue).isEqual(Vt(i.bytesValue))}(n,e);case 7:return n.referenceValue===e.referenceValue;case 8:return function(s,i){return ae(s.geoPointValue.latitude)===ae(i.geoPointValue.latitude)&&ae(s.geoPointValue.longitude)===ae(i.geoPointValue.longitude)}(n,e);case 2:return function(s,i){if("integerValue"in s&&"integerValue"in i)return ae(s.integerValue)===ae(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){const a=ae(s.doubleValue),c=ae(i.doubleValue);return a===c?Es(a)===Es(c):isNaN(a)&&isNaN(c)}return!1}(n,e);case 9:return Sn(n.arrayValue.values||[],e.arrayValue.values||[],st);case 10:case 11:return function(s,i){const a=s.mapValue.fields||{},c=i.mapValue.fields||{};if(Zc(a)!==Zc(c))return!1;for(const l in a)if(a.hasOwnProperty(l)&&(c[l]===void 0||!st(a[l],c[l])))return!1;return!0}(n,e);default:return x(52216,{left:n})}}function Er(n,e){return(n.values||[]).find(t=>st(t,e))!==void 0}function Nn(n,e){if(n===e)return 0;const t=Lt(n),r=Lt(e);if(t!==r)return W(t,r);switch(t){case 0:case 9007199254740991:return 0;case 1:return W(n.booleanValue,e.booleanValue);case 2:return function(i,a){const c=ae(i.integerValue||i.doubleValue),l=ae(a.integerValue||a.doubleValue);return c<l?-1:c>l?1:c===l?0:isNaN(c)?isNaN(l)?0:-1:1}(n,e);case 3:return uu(n.timestampValue,e.timestampValue);case 4:return uu(_r(n),_r(e));case 5:return so(n.stringValue,e.stringValue);case 6:return function(i,a){const c=Vt(i),l=Vt(a);return c.compareTo(l)}(n.bytesValue,e.bytesValue);case 7:return function(i,a){const c=i.split("/"),l=a.split("/");for(let d=0;d<c.length&&d<l.length;d++){const f=W(c[d],l[d]);if(f!==0)return f}return W(c.length,l.length)}(n.referenceValue,e.referenceValue);case 8:return function(i,a){const c=W(ae(i.latitude),ae(a.latitude));return c!==0?c:W(ae(i.longitude),ae(a.longitude))}(n.geoPointValue,e.geoPointValue);case 9:return lu(n.arrayValue,e.arrayValue);case 10:return function(i,a){const c=i.fields||{},l=a.fields||{},d=c[Rs]?.arrayValue,f=l[Rs]?.arrayValue,m=W(d?.values?.length||0,f?.values?.length||0);return m!==0?m:lu(d,f)}(n.mapValue,e.mapValue);case 11:return function(i,a){if(i===As.mapValue&&a===As.mapValue)return 0;if(i===As.mapValue)return 1;if(a===As.mapValue)return-1;const c=i.fields||{},l=Object.keys(c),d=a.fields||{},f=Object.keys(d);l.sort(),f.sort();for(let m=0;m<l.length&&m<f.length;++m){const g=so(l[m],f[m]);if(g!==0)return g;const R=Nn(c[l[m]],d[f[m]]);if(R!==0)return R}return W(l.length,f.length)}(n.mapValue,e.mapValue);default:throw x(23264,{he:t})}}function uu(n,e){if(typeof n=="string"&&typeof e=="string"&&n.length===e.length)return W(n,e);const t=Ot(n),r=Ot(e),s=W(t.seconds,r.seconds);return s!==0?s:W(t.nanos,r.nanos)}function lu(n,e){const t=n.values||[],r=e.values||[];for(let s=0;s<t.length&&s<r.length;++s){const i=Nn(t[s],r[s]);if(i)return i}return W(t.length,r.length)}function Dn(n){return ao(n)}function ao(n){return"nullValue"in n?"null":"booleanValue"in n?""+n.booleanValue:"integerValue"in n?""+n.integerValue:"doubleValue"in n?""+n.doubleValue:"timestampValue"in n?function(t){const r=Ot(t);return`time(${r.seconds},${r.nanos})`}(n.timestampValue):"stringValue"in n?n.stringValue:"bytesValue"in n?function(t){return Vt(t).toBase64()}(n.bytesValue):"referenceValue"in n?function(t){return L.fromName(t).toString()}(n.referenceValue):"geoPointValue"in n?function(t){return`geo(${t.latitude},${t.longitude})`}(n.geoPointValue):"arrayValue"in n?function(t){let r="[",s=!0;for(const i of t.values||[])s?s=!1:r+=",",r+=ao(i);return r+"]"}(n.arrayValue):"mapValue"in n?function(t){const r=Object.keys(t.fields||{}).sort();let s="{",i=!0;for(const a of r)i?i=!1:s+=",",s+=`${a}:${ao(t.fields[a])}`;return s+"}"}(n.mapValue):x(61005,{value:n})}function bs(n){switch(Lt(n)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const e=Is(n);return e?16+bs(e):16;case 5:return 2*n.stringValue.length;case 6:return Vt(n.bytesValue).approximateByteSize();case 7:return n.referenceValue.length;case 9:return function(r){return(r.values||[]).reduce((s,i)=>s+bs(i),0)}(n.arrayValue);case 10:case 11:return function(r){let s=0;return Dt(r.fields,(i,a)=>{s+=i.length+bs(a)}),s}(n.mapValue);default:throw x(13486,{value:n})}}function Ps(n,e){return{referenceValue:`projects/${n.projectId}/databases/${n.database}/documents/${e.path.canonicalString()}`}}function co(n){return!!n&&"integerValue"in n}function uo(n){return!!n&&"arrayValue"in n}function hu(n){return!!n&&"nullValue"in n}function du(n){return!!n&&"doubleValue"in n&&isNaN(Number(n.doubleValue))}function Ss(n){return!!n&&"mapValue"in n}function Tg(n){return(n?.mapValue?.fields||{})[au]?.stringValue===cu}function Tr(n){if(n.geoPointValue)return{geoPointValue:{...n.geoPointValue}};if(n.timestampValue&&typeof n.timestampValue=="object")return{timestampValue:{...n.timestampValue}};if(n.mapValue){const e={mapValue:{fields:{}}};return Dt(n.mapValue.fields,(t,r)=>e.mapValue.fields[t]=Tr(r)),e}if(n.arrayValue){const e={arrayValue:{values:[]}};for(let t=0;t<(n.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Tr(n.arrayValue.values[t]);return e}return{...n}}function wg(n){return(((n.mapValue||{}).fields||{}).__type__||{}).stringValue===Eg}class Ce{constructor(e){this.value=e}static empty(){return new Ce({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r<e.length-1;++r)if(t=(t.mapValue.fields||{})[e.get(r)],!Ss(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Tr(t)}setAll(e){let t=Ee.emptyPath(),r={},s=[];e.forEach((a,c)=>{if(!t.isImmediateParentOf(c)){const l=this.getFieldsMap(t);this.applyChanges(l,r,s),r={},s=[],t=c.popLast()}a?r[c.lastSegment()]=Tr(a):s.push(c.lastSegment())});const i=this.getFieldsMap(t);this.applyChanges(i,r,s)}delete(e){const t=this.field(e.popLast());Ss(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return st(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let r=0;r<e.length;++r){let s=t.mapValue.fields[e.get(r)];Ss(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(r)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,r){Dt(t,(s,i)=>e[s]=i);for(const s of r)delete e[s]}clone(){return new Ce(Tr(this.value))}}function fu(n){const e=[];return Dt(n.fields,(t,r)=>{const s=new Ee([t]);if(Ss(r)){const i=fu(r.mapValue).fields;if(i.length===0)e.push(s);else for(const a of i)e.push(s.child(a))}else e.push(s)}),new Fe(e)}class be{constructor(e,t,r,s,i,a,c){this.key=e,this.documentType=t,this.version=r,this.readTime=s,this.createTime=i,this.data=a,this.documentState=c}static newInvalidDocument(e){return new be(e,0,B.min(),B.min(),B.min(),Ce.empty(),0)}static newFoundDocument(e,t,r,s){return new be(e,1,t,B.min(),r,s,0)}static newNoDocument(e,t){return new be(e,2,t,B.min(),B.min(),Ce.empty(),0)}static newUnknownDocument(e,t){return new be(e,3,t,B.min(),B.min(),Ce.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(B.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Ce.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ce.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=B.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return this.documentState===1}get hasCommittedMutations(){return this.documentState===2}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return this.documentType!==0}isFoundDocument(){return this.documentType===1}isNoDocument(){return this.documentType===2}isUnknownDocument(){return this.documentType===3}isEqual(e){return e instanceof be&&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 be(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class On{constructor(e,t){this.position=e,this.inclusive=t}}function pu(n,e,t){let r=0;for(let s=0;s<n.position.length;s++){const i=e[s],a=n.position[s];if(i.field.isKeyField()?r=L.comparator(L.fromName(a.referenceValue),t.key):r=Nn(a,t.data.field(i.field)),i.dir==="desc"&&(r*=-1),r!==0)break}return r}function mu(n,e){if(n===null)return e===null;if(e===null||n.inclusive!==e.inclusive||n.position.length!==e.position.length)return!1;for(let t=0;t<n.position.length;t++)if(!st(n.position[t],e.position[t]))return!1;return!0}class wr{constructor(e,t="asc"){this.field=e,this.dir=t}}function Ig(n,e){return n.dir===e.dir&&n.field.isEqual(e.field)}class gu{}class le extends gu{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?t==="in"||t==="not-in"?this.createKeyFieldInFilter(e,t,r):new Ag(e,t,r):t==="array-contains"?new Pg(e,r):t==="in"?new Sg(e,r):t==="not-in"?new Cg(e,r):t==="array-contains-any"?new kg(e,r):new le(e,t,r)}static createKeyFieldInFilter(e,t,r){return t==="in"?new Rg(e,r):new bg(e,r)}matches(e){const t=e.data.field(this.field);return this.op==="!="?t!==null&&t.nullValue===void 0&&this.matchesComparison(Nn(t,this.value)):t!==null&&Lt(this.value)===Lt(t)&&this.matchesComparison(Nn(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return e===0;case"!=":return e!==0;case">":return e>0;case">=":return e>=0;default:return x(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class Ke extends gu{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new Ke(e,t)}matches(e){return _u(this)?this.filters.find(t=>!t.matches(e))===void 0:this.filters.find(t=>t.matches(e))!==void 0}getFlattenedFilters(){return this.Pe!==null||(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function _u(n){return n.op==="and"}function yu(n){return vg(n)&&_u(n)}function vg(n){for(const e of n.filters)if(e instanceof Ke)return!1;return!0}function lo(n){if(n instanceof le)return n.field.canonicalString()+n.op.toString()+Dn(n.value);if(yu(n))return n.filters.map(e=>lo(e)).join(",");{const e=n.filters.map(t=>lo(t)).join(",");return`${n.op}(${e})`}}function Eu(n,e){return n instanceof le?function(r,s){return s instanceof le&&r.op===s.op&&r.field.isEqual(s.field)&&st(r.value,s.value)}(n,e):n instanceof Ke?function(r,s){return s instanceof Ke&&r.op===s.op&&r.filters.length===s.filters.length?r.filters.reduce((i,a,c)=>i&&Eu(a,s.filters[c]),!0):!1}(n,e):void x(19439)}function Tu(n){return n instanceof le?function(t){return`${t.field.canonicalString()} ${t.op} ${Dn(t.value)}`}(n):n instanceof Ke?function(t){return t.op.toString()+" {"+t.getFilters().map(Tu).join(" ,")+"}"}(n):"Filter"}class Ag extends le{constructor(e,t,r){super(e,t,r),this.key=L.fromName(r.referenceValue)}matches(e){const t=L.comparator(e.key,this.key);return this.matchesComparison(t)}}class Rg extends le{constructor(e,t){super(e,"in",t),this.keys=wu("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class bg extends le{constructor(e,t){super(e,"not-in",t),this.keys=wu("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function wu(n,e){return(e.arrayValue?.values||[]).map(t=>L.fromName(t.referenceValue))}class Pg extends le{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return uo(t)&&Er(t.arrayValue,this.value)}}class Sg extends le{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return t!==null&&Er(this.value.arrayValue,t)}}class Cg extends le{constructor(e,t){super(e,"not-in",t)}matches(e){if(Er(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return t!==null&&t.nullValue===void 0&&!Er(this.value.arrayValue,t)}}class kg extends le{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!uo(t)||!t.arrayValue.values)&&t.arrayValue.values.some(r=>Er(this.value.arrayValue,r))}}class Ng{constructor(e,t=null,r=[],s=[],i=null,a=null,c=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=s,this.limit=i,this.startAt=a,this.endAt=c,this.Te=null}}function Iu(n,e=null,t=[],r=[],s=null,i=null,a=null){return new Ng(n,e,t,r,s,i,a)}function ho(n){const e=U(n);if(e.Te===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(r=>lo(r)).join(","),t+="|ob:",t+=e.orderBy.map(r=>function(i){return i.field.canonicalString()+i.dir}(r)).join(","),ys(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(r=>Dn(r)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(r=>Dn(r)).join(",")),e.Te=t}return e.Te}function fo(n,e){if(n.limit!==e.limit||n.orderBy.length!==e.orderBy.length)return!1;for(let t=0;t<n.orderBy.length;t++)if(!Ig(n.orderBy[t],e.orderBy[t]))return!1;if(n.filters.length!==e.filters.length)return!1;for(let t=0;t<n.filters.length;t++)if(!Eu(n.filters[t],e.filters[t]))return!1;return n.collectionGroup===e.collectionGroup&&!!n.path.isEqual(e.path)&&!!mu(n.startAt,e.startAt)&&mu(n.endAt,e.endAt)}function po(n){return L.isDocumentKey(n.path)&&n.collectionGroup===null&&n.filters.length===0}class sn{constructor(e,t=null,r=[],s=[],i=null,a="F",c=null,l=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=s,this.limit=i,this.limitType=a,this.startAt=c,this.endAt=l,this.Ie=null,this.Ee=null,this.Re=null,this.startAt,this.endAt}}function Dg(n,e,t,r,s,i,a,c){return new sn(n,e,t,r,s,i,a,c)}function Cs(n){return new sn(n)}function vu(n){return n.filters.length===0&&n.limit===null&&n.startAt==null&&n.endAt==null&&(n.explicitOrderBy.length===0||n.explicitOrderBy.length===1&&n.explicitOrderBy[0].field.isKeyField())}function Og(n){return L.isDocumentKey(n.path)&&n.collectionGroup===null&&n.filters.length===0}function mo(n){return n.collectionGroup!==null}function Vn(n){const e=U(n);if(e.Ie===null){e.Ie=[];const t=new Set;for(const i of e.explicitOrderBy)e.Ie.push(i),t.add(i.field.canonicalString());const r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(a){let c=new fe(Ee.comparator);return a.filters.forEach(l=>{l.getFlattenedFilters().forEach(d=>{d.isInequality()&&(c=c.add(d.field))})}),c})(e).forEach(i=>{t.has(i.canonicalString())||i.isKeyField()||e.Ie.push(new wr(i,r))}),t.has(Ee.keyField().canonicalString())||e.Ie.push(new wr(Ee.keyField(),r))}return e.Ie}function it(n){const e=U(n);return e.Ee||(e.Ee=Au(e,Vn(n))),e.Ee}function Vg(n){const e=U(n);return e.Re||(e.Re=Au(e,n.explicitOrderBy)),e.Re}function Au(n,e){if(n.limitType==="F")return Iu(n.path,n.collectionGroup,e,n.filters,n.limit,n.startAt,n.endAt);{e=e.map(s=>{const i=s.dir==="desc"?"asc":"desc";return new wr(s.field,i)});const t=n.endAt?new On(n.endAt.position,n.endAt.inclusive):null,r=n.startAt?new On(n.startAt.position,n.startAt.inclusive):null;return Iu(n.path,n.collectionGroup,e,n.filters,n.limit,t,r)}}function go(n,e){const t=n.filters.concat([e]);return new sn(n.path,n.collectionGroup,n.explicitOrderBy.slice(),t,n.limit,n.limitType,n.startAt,n.endAt)}function Lg(n,e){const t=n.explicitOrderBy.concat([e]);return new sn(n.path,n.collectionGroup,t,n.filters.slice(),n.limit,n.limitType,n.startAt,n.endAt)}function ks(n,e,t){return new sn(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),e,t,n.startAt,n.endAt)}function Mg(n,e){return new sn(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),n.limit,n.limitType,e,n.endAt)}function Ns(n,e){return fo(it(n),it(e))&&n.limitType===e.limitType}function Ru(n){return`${ho(it(n))}|lt:${n.limitType}`}function Ln(n){return`Query(target=${function(t){let r=t.path.canonicalString();return t.collectionGroup!==null&&(r+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(r+=`, filters: [${t.filters.map(s=>Tu(s)).join(", ")}]`),ys(t.limit)||(r+=", limit: "+t.limit),t.orderBy.length>0&&(r+=`, orderBy: [${t.orderBy.map(s=>function(a){return`${a.field.canonicalString()} (${a.dir})`}(s)).join(", ")}]`),t.startAt&&(r+=", startAt: ",r+=t.startAt.inclusive?"b:":"a:",r+=t.startAt.position.map(s=>Dn(s)).join(",")),t.endAt&&(r+=", endAt: ",r+=t.endAt.inclusive?"a:":"b:",r+=t.endAt.position.map(s=>Dn(s)).join(",")),`Target(${r})`}(it(n))}; limitType=${n.limitType})`}function Ds(n,e){return e.isFoundDocument()&&function(r,s){const i=s.key.path;return r.collectionGroup!==null?s.key.hasCollectionId(r.collectionGroup)&&r.path.isPrefixOf(i):L.isDocumentKey(r.path)?r.path.isEqual(i):r.path.isImmediateParentOf(i)}(n,e)&&function(r,s){for(const i of Vn(r))if(!i.field.isKeyField()&&s.data.field(i.field)===null)return!1;return!0}(n,e)&&function(r,s){for(const i of r.filters)if(!i.matches(s))return!1;return!0}(n,e)&&function(r,s){return!(r.startAt&&!function(a,c,l){const d=pu(a,c,l);return a.inclusive?d<=0:d<0}(r.startAt,Vn(r),s)||r.endAt&&!function(a,c,l){const d=pu(a,c,l);return a.inclusive?d>=0:d>0}(r.endAt,Vn(r),s))}(n,e)}function xg(n){return n.collectionGroup||(n.path.length%2==1?n.path.lastSegment():n.path.get(n.path.length-2))}function bu(n){return(e,t)=>{let r=!1;for(const s of Vn(n)){const i=Ug(s,e,t);if(i!==0)return i;r=r||s.field.isKeyField()}return 0}}function Ug(n,e,t){const r=n.field.isKeyField()?L.comparator(e.key,t.key):function(i,a,c){const l=a.data.field(i),d=c.data.field(i);return l!==null&&d!==null?Nn(l,d):x(42886)}(n.field,e,t);switch(n.dir){case"asc":return r;case"desc":return-1*r;default:return x(19790,{direction:n.dir})}}class on{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),r=this.inner[t];if(r!==void 0){for(const[s,i]of r)if(this.equalsFn(s,e))return i}}has(e){return this.get(e)!==void 0}set(e,t){const r=this.mapKeyFn(e),s=this.inner[r];if(s===void 0)return this.inner[r]=[[e,t]],void this.innerSize++;for(let i=0;i<s.length;i++)if(this.equalsFn(s[i][0],e))return void(s[i]=[e,t]);s.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),r=this.inner[t];if(r===void 0)return!1;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],e))return r.length===1?delete this.inner[t]:r.splice(s,1),this.innerSize--,!0;return!1}forEach(e){Dt(this.inner,(t,r)=>{for(const[s,i]of r)e(s,i)})}isEmpty(){return eu(this.inner)}size(){return this.innerSize}}const Fg=new se(L.comparator);function Tt(){return Fg}const Pu=new se(L.comparator);function Ir(...n){let e=Pu;for(const t of n)e=e.insert(t.key,t);return e}function Su(n){let e=Pu;return n.forEach((t,r)=>e=e.insert(t,r.overlayedDocument)),e}function an(){return vr()}function Cu(){return vr()}function vr(){return new on(n=>n.toString(),(n,e)=>n.isEqual(e))}const Bg=new se(L.comparator),qg=new fe(L.comparator);function G(...n){let e=qg;for(const t of n)e=e.add(t);return e}const jg=new fe(W);function $g(){return jg}function _o(n,e){if(n.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Es(e)?"-0":e}}function ku(n){return{integerValue:""+n}}function zg(n,e){return dg(e)?ku(e):_o(n,e)}class Os{constructor(){this._=void 0}}function Hg(n,e,t){return n instanceof Vs?function(s,i){const a={fields:{[su]:{stringValue:ru},[ou]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&ws(i)&&(i=Is(i)),i&&(a.fields[iu]=i),{mapValue:a}}(t,e):n instanceof Ar?Du(n,e):n instanceof Rr?Ou(n,e):function(s,i){const a=Nu(s,i),c=Vu(a)+Vu(s.Ae);return co(a)&&co(s.Ae)?ku(c):_o(s.serializer,c)}(n,e)}function Wg(n,e,t){return n instanceof Ar?Du(n,e):n instanceof Rr?Ou(n,e):t}function Nu(n,e){return n instanceof Ls?function(r){return co(r)||function(i){return!!i&&"doubleValue"in i}(r)}(e)?e:{integerValue:0}:null}class Vs extends Os{}class Ar extends Os{constructor(e){super(),this.elements=e}}function Du(n,e){const t=Lu(e);for(const r of n.elements)t.some(s=>st(s,r))||t.push(r);return{arrayValue:{values:t}}}class Rr extends Os{constructor(e){super(),this.elements=e}}function Ou(n,e){let t=Lu(e);for(const r of n.elements)t=t.filter(s=>!st(s,r));return{arrayValue:{values:t}}}class Ls extends Os{constructor(e,t){super(),this.serializer=e,this.Ae=t}}function Vu(n){return ae(n.integerValue||n.doubleValue)}function Lu(n){return uo(n)&&n.arrayValue.values?n.arrayValue.values.slice():[]}function Gg(n,e){return n.field.isEqual(e.field)&&function(r,s){return r instanceof Ar&&s instanceof Ar||r instanceof Rr&&s instanceof Rr?Sn(r.elements,s.elements,st):r instanceof Ls&&s instanceof Ls?st(r.Ae,s.Ae):r instanceof Vs&&s instanceof Vs}(n.transform,e.transform)}class Kg{constructor(e,t){this.version=e,this.transformResults=t}}class $e{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new $e}static exists(e){return new $e(void 0,e)}static updateTime(e){return new $e(e)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Ms(n,e){return n.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(n.updateTime):n.exists===void 0||n.exists===e.isFoundDocument()}class xs{}function Mu(n,e){if(!n.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return n.isNoDocument()?new Us(n.key,$e.none()):new Pr(n.key,n.data,$e.none());{const t=n.data,r=Ce.empty();let s=new fe(Ee.comparator);for(let i of e.fields)if(!s.has(i)){let a=t.field(i);a===null&&i.length>1&&(i=i.popLast(),a=t.field(i)),a===null?r.delete(i):r.set(i,a),s=s.add(i)}return new Mt(n.key,r,new Fe(s.toArray()),$e.none())}}function Qg(n,e,t){n instanceof Pr?function(s,i,a){const c=s.value.clone(),l=Fu(s.fieldTransforms,i,a.transformResults);c.setAll(l),i.convertToFoundDocument(a.version,c).setHasCommittedMutations()}(n,e,t):n instanceof Mt?function(s,i,a){if(!Ms(s.precondition,i))return void i.convertToUnknownDocument(a.version);const c=Fu(s.fieldTransforms,i,a.transformResults),l=i.data;l.setAll(Uu(s)),l.setAll(c),i.convertToFoundDocument(a.version,l).setHasCommittedMutations()}(n,e,t):function(s,i,a){i.convertToNoDocument(a.version).setHasCommittedMutations()}(0,e,t)}function br(n,e,t,r){return n instanceof Pr?function(i,a,c,l){if(!Ms(i.precondition,a))return c;const d=i.value.clone(),f=Bu(i.fieldTransforms,l,a);return d.setAll(f),a.convertToFoundDocument(a.version,d).setHasLocalMutations(),null}(n,e,t,r):n instanceof Mt?function(i,a,c,l){if(!Ms(i.precondition,a))return c;const d=Bu(i.fieldTransforms,l,a),f=a.data;return f.setAll(Uu(i)),f.setAll(d),a.convertToFoundDocument(a.version,f).setHasLocalMutations(),c===null?null:c.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map(m=>m.field))}(n,e,t,r):function(i,a,c){return Ms(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):c}(n,e,t)}function Yg(n,e){let t=null;for(const r of n.fieldTransforms){const s=e.data.field(r.field),i=Nu(r.transform,s||null);i!=null&&(t===null&&(t=Ce.empty()),t.set(r.field,i))}return t||null}function xu(n,e){return n.type===e.type&&!!n.key.isEqual(e.key)&&!!n.precondition.isEqual(e.precondition)&&!!function(r,s){return r===void 0&&s===void 0||!(!r||!s)&&Sn(r,s,(i,a)=>Gg(i,a))}(n.fieldTransforms,e.fieldTransforms)&&(n.type===0?n.value.isEqual(e.value):n.type!==1||n.data.isEqual(e.data)&&n.fieldMask.isEqual(e.fieldMask))}class Pr extends xs{constructor(e,t,r,s=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class Mt extends xs{constructor(e,t,r,s,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=s,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Uu(n){const e=new Map;return n.fieldMask.fields.forEach(t=>{if(!t.isEmpty()){const r=n.data.field(t);e.set(t,r)}}),e}function Fu(n,e,t){const r=new Map;Y(n.length===t.length,32656,{Ve:t.length,de:n.length});for(let s=0;s<t.length;s++){const i=n[s],a=i.transform,c=e.data.field(i.field);r.set(i.field,Wg(a,c,t[s]))}return r}function Bu(n,e,t){const r=new Map;for(const s of n){const i=s.transform,a=t.data.field(s.field);r.set(s.field,Hg(i,a,e))}return r}class Us extends xs{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Jg extends xs{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Xg{constructor(e,t,r,s){this.batchId=e,this.localWriteTime=t,this.baseMutations=r,this.mutations=s}applyToRemoteDocument(e,t){const r=t.mutationResults;for(let s=0;s<this.mutations.length;s++){const i=this.mutations[s];i.key.isEqual(e.key)&&Qg(i,e,r[s])}}applyToLocalView(e,t){for(const r of this.baseMutations)r.key.isEqual(e.key)&&(t=br(r,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=br(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const r=Cu();return this.mutations.forEach(s=>{const i=e.get(s.key),a=i.overlayedDocument;let c=this.applyToLocalView(a,i.mutatedFields);c=t.has(s.key)?null:c;const l=Mu(a,c);l!==null&&r.set(s.key,l),a.isValidDocument()||a.convertToNoDocument(B.min())}),r}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),G())}isEqual(e){return this.batchId===e.batchId&&Sn(this.mutations,e.mutations,(t,r)=>xu(t,r))&&Sn(this.baseMutations,e.baseMutations,(t,r)=>xu(t,r))}}class yo{constructor(e,t,r,s){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=s}static from(e,t,r){Y(e.mutations.length===r.length,58842,{me:e.mutations.length,fe:r.length});let s=function(){return Bg}();const i=e.mutations;for(let a=0;a<i.length;a++)s=s.insert(i[a].key,r[a].version);return new yo(e,t,r,s)}}class Zg{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return e!==null&&this.mutation===e.mutation}toString(){return`Overlay{
19
+ `+b+" "+O})}function tr(o,u,h,p){o.info(function(){return"XMLHTTP TEXT ("+u+"): "+fA(o,h)+(p?" "+p:"")})}function dA(o,u){o.info(function(){return"TIMEOUT: "+u})}Yr.prototype.info=function(){};function fA(o,u){if(!o.g)return u;if(!u)return null;try{const b=JSON.parse(u);if(b){for(o=0;o<b.length;o++)if(Array.isArray(b[o])){var h=b[o];if(!(h.length<2)){var p=h[1];if(Array.isArray(p)&&!(p.length<1)){var v=p[0];if(v!="noop"&&v!="stop"&&v!="close")for(let O=1;O<p.length;O++)p[O]=""}}}}return Qa(b)}catch{return u}}var Di={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},Pf={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"},Cf;function Xa(){}m(Xa,wf),Xa.prototype.g=function(){return new XMLHttpRequest},Cf=new Xa;function Jr(o){return encodeURIComponent(String(o))}function pA(o){var u=1;o=o.split(":");const h=[];for(;u>0&&o.length;)h.push(o.shift()),u--;return o.length&&h.push(o.join(":")),h}function Kt(o,u,h,p){this.j=o,this.i=u,this.l=h,this.S=p||1,this.V=new Wr(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new Sf}function Sf(){this.i=null,this.g="",this.h=!1}var kf={},Za={};function ec(o,u,h){o.M=1,o.A=Vi(mt(u)),o.u=h,o.R=!0,Nf(o,null)}function Nf(o,u){o.F=Date.now(),Oi(o),o.B=mt(o.A);var h=o.B,p=o.S;Array.isArray(p)||(p=[String(p)]),zf(h.i,"t",p),o.C=0,h=o.j.L,o.h=new Sf,o.g=cp(o.j,h?u:null,!o.u),o.P>0&&(o.O=new aA(d(o.Y,o,o.g),o.P)),u=o.V,h=o.g,p=o.ba;var v="readystatechange";Array.isArray(v)||(v&&(Ef[0]=v.toString()),v=Ef);for(let b=0;b<v.length;b++){const O=pf(h,v[b],p||u.handleEvent,!1,u.h||u);if(!O)break;u.g[O.key]=O}u=o.J?hf(o.J):{},o.u?(o.v||(o.v="POST"),u["Content-Type"]="application/x-www-form-urlencoded",o.g.ea(o.B,o.v,o.u,u)):(o.v="GET",o.g.ea(o.B,o.v,null,u)),Kr(),lA(o.i,o.v,o.B,o.l,o.S,o.u)}Kt.prototype.ba=function(o){o=o.target;const u=this.O;u&&Jt(o)==3?u.j():this.Y(o)},Kt.prototype.Y=function(o){try{if(o==this.g)e:{const z=Jt(this.g),me=this.g.ya(),Z=this.g.ca();if(!(z<3)&&(z!=3||this.g&&(this.h.h||this.g.la()||Jf(this.g)))){this.K||z!=4||me==7||(me==8||Z<=0?Kr(3):Kr(2)),tc(this);var u=this.g.ca();this.X=u;var h=mA(this);if(this.o=u==200,hA(this.i,this.v,this.B,this.l,this.S,z,u),this.o){if(this.U&&!this.L){t:{if(this.g){var p,v=this.g;if((p=v.g?v.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!y(p)){var b=p;break t}}b=null}if(o=b)tr(this.i,this.l,o,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,nc(this,o);else{this.o=!1,this.m=3,De(12),In(this),Xr(this);break e}}if(this.R){o=!0;let ye;for(;!this.K&&this.C<h.length;)if(ye=gA(this,h),ye==Za){z==4&&(this.m=4,De(14),o=!1),tr(this.i,this.l,null,"[Incomplete Response]");break}else if(ye==kf){this.m=4,De(15),tr(this.i,this.l,h,"[Invalid Chunk]"),o=!1;break}else tr(this.i,this.l,ye,null),nc(this,ye);if(Df(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),z!=4||h.length!=0||this.h.h||(this.m=1,De(16),o=!1),this.o=this.o&&o,!o)tr(this.i,this.l,h,"[Invalid Chunked Response]"),In(this),Xr(this);else if(h.length>0&&!this.W){this.W=!0;var O=this.j;O.g==this&&O.aa&&!O.P&&(O.j.info("Great, no buffering proxy detected. Bytes received: "+h.length),lc(O),O.P=!0,De(11))}}else tr(this.i,this.l,h,null),nc(this,h);z==4&&In(this),this.o&&!this.K&&(z==4?sp(this.j,this):(this.o=!1,Oi(this)))}else kA(this.g),u==400&&h.indexOf("Unknown SID")>0?(this.m=3,De(12)):(this.m=0,De(13)),In(this),Xr(this)}}}catch{}finally{}};function mA(o){if(!Df(o))return o.g.la();const u=Jf(o.g);if(u==="")return"";let h="";const p=u.length,v=Jt(o.g)==4;if(!o.h.i){if(typeof TextDecoder>"u")return In(o),Xr(o),"";o.h.i=new a.TextDecoder}for(let b=0;b<p;b++)o.h.h=!0,h+=o.h.i.decode(u[b],{stream:!(v&&b==p-1)});return u.length=0,o.h.g+=h,o.C=0,o.h.g}function Df(o){return o.g?o.v=="GET"&&o.M!=2&&o.j.Aa:!1}function gA(o,u){var h=o.C,p=u.indexOf(`
20
+ `,h);return p==-1?Za:(h=Number(u.substring(h,p)),isNaN(h)?kf:(p+=1,p+h>u.length?Za:(u=u.slice(p,p+h),o.C=p+h,u)))}Kt.prototype.cancel=function(){this.K=!0,In(this)};function Oi(o){o.T=Date.now()+o.H,Of(o,o.H)}function Of(o,u){if(o.D!=null)throw Error("WatchDog timer not null");o.D=Qr(d(o.aa,o),u)}function tc(o){o.D&&(a.clearTimeout(o.D),o.D=null)}Kt.prototype.aa=function(){this.D=null;const o=Date.now();o-this.T>=0?(dA(this.i,this.B),this.M!=2&&(Kr(),De(17)),In(this),this.m=2,Xr(this)):Of(this,this.T-o)};function Xr(o){o.j.I==0||o.K||sp(o.j,o)}function In(o){tc(o);var u=o.O;u&&typeof u.dispose=="function"&&u.dispose(),o.O=null,Tf(o.V),o.g&&(u=o.g,o.g=null,u.abort(),u.dispose())}function nc(o,u){try{var h=o.j;if(h.I!=0&&(h.g==o||rc(h.h,o))){if(!o.L&&rc(h.h,o)&&h.I==3){try{var p=h.Ba.g.parse(u)}catch{p=null}if(Array.isArray(p)&&p.length==3){var v=p;if(v[0]==0){e:if(!h.v){if(h.g)if(h.g.F+3e3<o.F)Fi(h),xi(h);else break e;uc(h),De(18)}}else h.xa=v[1],0<h.xa-h.K&&v[2]<37500&&h.F&&h.A==0&&!h.C&&(h.C=Qr(d(h.Va,h),6e3));Mf(h.h)<=1&&h.ta&&(h.ta=void 0)}else An(h,11)}else if((o.L||h.g==o)&&Fi(h),!y(u))for(v=h.Ba.g.parse(u),u=0;u<v.length;u++){let Z=v[u];const ye=Z[0];if(!(ye<=h.K))if(h.K=ye,Z=Z[1],h.I==2)if(Z[0]=="c"){h.M=Z[1],h.ba=Z[2];const gt=Z[3];gt!=null&&(h.ka=gt,h.j.info("VER="+h.ka));const Rn=Z[4];Rn!=null&&(h.za=Rn,h.j.info("SVER="+h.za));const Xt=Z[5];Xt!=null&&typeof Xt=="number"&&Xt>0&&(p=1.5*Xt,h.O=p,h.j.info("backChannelRequestTimeoutMs_="+p)),p=h;const Zt=o.g;if(Zt){const qi=Zt.g?Zt.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(qi){var b=p.h;b.g||qi.indexOf("spdy")==-1&&qi.indexOf("quic")==-1&&qi.indexOf("h2")==-1||(b.j=b.l,b.g=new Set,b.h&&(sc(b,b.h),b.h=null))}if(p.G){const hc=Zt.g?Zt.g.getResponseHeader("X-HTTP-Session-Id"):null;hc&&(p.wa=hc,ne(p.J,p.G,hc))}}h.I=3,h.l&&h.l.ra(),h.aa&&(h.T=Date.now()-o.F,h.j.info("Handshake RTT: "+h.T+"ms")),p=h;var O=o;if(p.na=ap(p,p.L?p.ba:null,p.W),O.L){xf(p.h,O);var z=O,me=p.O;me&&(z.H=me),z.D&&(tc(z),Oi(z)),p.g=O}else np(p);h.i.length>0&&Ui(h)}else Z[0]!="stop"&&Z[0]!="close"||An(h,7);else h.I==3&&(Z[0]=="stop"||Z[0]=="close"?Z[0]=="stop"?An(h,7):cc(h):Z[0]!="noop"&&h.l&&h.l.qa(Z),h.A=0)}}Kr(4)}catch{}}var _A=class{constructor(o,u){this.g=o,this.map=u}};function Vf(o){this.l=o||10,a.PerformanceNavigationTiming?(o=a.performance.getEntriesByType("navigation"),o=o.length>0&&(o[0].nextHopProtocol=="hq"||o[0].nextHopProtocol=="h2")):o=!!(a.chrome&&a.chrome.loadTimes&&a.chrome.loadTimes()&&a.chrome.loadTimes().wasFetchedViaSpdy),this.j=o?this.l:1,this.g=null,this.j>1&&(this.g=new Set),this.h=null,this.i=[]}function Lf(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function Mf(o){return o.h?1:o.g?o.g.size:0}function rc(o,u){return o.h?o.h==u:o.g?o.g.has(u):!1}function sc(o,u){o.g?o.g.add(u):o.h=u}function xf(o,u){o.h&&o.h==u?o.h=null:o.g&&o.g.has(u)&&o.g.delete(u)}Vf.prototype.cancel=function(){if(this.i=Uf(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(const o of this.g.values())o.cancel();this.g.clear()}};function Uf(o){if(o.h!=null)return o.i.concat(o.h.G);if(o.g!=null&&o.g.size!==0){let u=o.i;for(const h of o.g.values())u=u.concat(h.G);return u}return R(o.i)}var Ff=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function yA(o,u){if(o){o=o.split("&");for(let h=0;h<o.length;h++){const p=o[h].indexOf("=");let v,b=null;p>=0?(v=o[h].substring(0,p),b=o[h].substring(p+1)):v=o[h],u(v,b?decodeURIComponent(b.replace(/\+/g," ")):"")}}}function Qt(o){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let u;o instanceof Qt?(this.l=o.l,Zr(this,o.j),this.o=o.o,this.g=o.g,es(this,o.u),this.h=o.h,ic(this,Hf(o.i)),this.m=o.m):o&&(u=String(o).match(Ff))?(this.l=!1,Zr(this,u[1]||"",!0),this.o=ts(u[2]||""),this.g=ts(u[3]||"",!0),es(this,u[4]),this.h=ts(u[5]||"",!0),ic(this,u[6]||"",!0),this.m=ts(u[7]||"")):(this.l=!1,this.i=new rs(null,this.l))}Qt.prototype.toString=function(){const o=[];var u=this.j;u&&o.push(ns(u,Bf,!0),":");var h=this.g;return(h||u=="file")&&(o.push("//"),(u=this.o)&&o.push(ns(u,Bf,!0),"@"),o.push(Jr(h).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),h=this.u,h!=null&&o.push(":",String(h))),(h=this.h)&&(this.g&&h.charAt(0)!="/"&&o.push("/"),o.push(ns(h,h.charAt(0)=="/"?wA:TA,!0))),(h=this.i.toString())&&o.push("?",h),(h=this.m)&&o.push("#",ns(h,vA)),o.join("")},Qt.prototype.resolve=function(o){const u=mt(this);let h=!!o.j;h?Zr(u,o.j):h=!!o.o,h?u.o=o.o:h=!!o.g,h?u.g=o.g:h=o.u!=null;var p=o.h;if(h)es(u,o.u);else if(h=!!o.h){if(p.charAt(0)!="/")if(this.g&&!this.h)p="/"+p;else{var v=u.h.lastIndexOf("/");v!=-1&&(p=u.h.slice(0,v+1)+p)}if(v=p,v==".."||v==".")p="";else if(v.indexOf("./")!=-1||v.indexOf("/.")!=-1){p=v.lastIndexOf("/",0)==0,v=v.split("/");const b=[];for(let O=0;O<v.length;){const z=v[O++];z=="."?p&&O==v.length&&b.push(""):z==".."?((b.length>1||b.length==1&&b[0]!="")&&b.pop(),p&&O==v.length&&b.push("")):(b.push(z),p=!0)}p=b.join("/")}else p=v}return h?u.h=p:h=o.i.toString()!=="",h?ic(u,Hf(o.i)):h=!!o.m,h&&(u.m=o.m),u};function mt(o){return new Qt(o)}function Zr(o,u,h){o.j=h?ts(u,!0):u,o.j&&(o.j=o.j.replace(/:$/,""))}function es(o,u){if(u){if(u=Number(u),isNaN(u)||u<0)throw Error("Bad port number "+u);o.u=u}else o.u=null}function ic(o,u,h){u instanceof rs?(o.i=u,AA(o.i,o.l)):(h||(u=ns(u,IA)),o.i=new rs(u,o.l))}function ne(o,u,h){o.i.set(u,h)}function Vi(o){return ne(o,"zx",Math.floor(Math.random()*2147483648).toString(36)+Math.abs(Math.floor(Math.random()*2147483648)^Date.now()).toString(36)),o}function ts(o,u){return o?u?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function ns(o,u,h){return typeof o=="string"?(o=encodeURI(o).replace(u,EA),h&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function EA(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var Bf=/[#\/\?@]/g,TA=/[#\?:]/g,wA=/[#\?]/g,IA=/[#\?@]/g,vA=/#/g;function rs(o,u){this.h=this.g=null,this.i=o||null,this.j=!!u}function vn(o){o.g||(o.g=new Map,o.h=0,o.i&&yA(o.i,function(u,h){o.add(decodeURIComponent(u.replace(/\+/g," ")),h)}))}n=rs.prototype,n.add=function(o,u){vn(this),this.i=null,o=nr(this,o);let h=this.g.get(o);return h||this.g.set(o,h=[]),h.push(u),this.h+=1,this};function qf(o,u){vn(o),u=nr(o,u),o.g.has(u)&&(o.i=null,o.h-=o.g.get(u).length,o.g.delete(u))}function jf(o,u){return vn(o),u=nr(o,u),o.g.has(u)}n.forEach=function(o,u){vn(this),this.g.forEach(function(h,p){h.forEach(function(v){o.call(u,v,p,this)},this)},this)};function $f(o,u){vn(o);let h=[];if(typeof u=="string")jf(o,u)&&(h=h.concat(o.g.get(nr(o,u))));else for(o=Array.from(o.g.values()),u=0;u<o.length;u++)h=h.concat(o[u]);return h}n.set=function(o,u){return vn(this),this.i=null,o=nr(this,o),jf(this,o)&&(this.h-=this.g.get(o).length),this.g.set(o,[u]),this.h+=1,this},n.get=function(o,u){return o?(o=$f(this,o),o.length>0?String(o[0]):u):u};function zf(o,u,h){qf(o,u),h.length>0&&(o.i=null,o.g.set(nr(o,u),R(h)),o.h+=h.length)}n.toString=function(){if(this.i)return this.i;if(!this.g)return"";const o=[],u=Array.from(this.g.keys());for(let p=0;p<u.length;p++){var h=u[p];const v=Jr(h);h=$f(this,h);for(let b=0;b<h.length;b++){let O=v;h[b]!==""&&(O+="="+Jr(h[b])),o.push(O)}}return this.i=o.join("&")};function Hf(o){const u=new rs;return u.i=o.i,o.g&&(u.g=new Map(o.g),u.h=o.h),u}function nr(o,u){return u=String(u),o.j&&(u=u.toLowerCase()),u}function AA(o,u){u&&!o.j&&(vn(o),o.i=null,o.g.forEach(function(h,p){const v=p.toLowerCase();p!=v&&(qf(this,p),zf(this,v,h))},o)),o.j=u}function RA(o,u){const h=new Yr;if(a.Image){const p=new Image;p.onload=f(Yt,h,"TestLoadImage: loaded",!0,u,p),p.onerror=f(Yt,h,"TestLoadImage: error",!1,u,p),p.onabort=f(Yt,h,"TestLoadImage: abort",!1,u,p),p.ontimeout=f(Yt,h,"TestLoadImage: timeout",!1,u,p),a.setTimeout(function(){p.ontimeout&&p.ontimeout()},1e4),p.src=o}else u(!1)}function bA(o,u){const h=new Yr,p=new AbortController,v=setTimeout(()=>{p.abort(),Yt(h,"TestPingServer: timeout",!1,u)},1e4);fetch(o,{signal:p.signal}).then(b=>{clearTimeout(v),b.ok?Yt(h,"TestPingServer: ok",!0,u):Yt(h,"TestPingServer: server error",!1,u)}).catch(()=>{clearTimeout(v),Yt(h,"TestPingServer: error",!1,u)})}function Yt(o,u,h,p,v){try{v&&(v.onload=null,v.onerror=null,v.onabort=null,v.ontimeout=null),p(h)}catch{}}function PA(){this.g=new uA}function oc(o){this.i=o.Sb||null,this.h=o.ab||!1}m(oc,wf),oc.prototype.g=function(){return new Li(this.i,this.h)};function Li(o,u){Ce.call(this),this.H=o,this.o=u,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}m(Li,Ce),n=Li.prototype,n.open=function(o,u){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.F=o,this.D=u,this.readyState=1,is(this)},n.send=function(o){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;const u={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};o&&(u.body=o),(this.H||a).fetch(new Request(this.D,u)).then(this.Pa.bind(this),this.ga.bind(this))},n.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),this.readyState>=1&&this.g&&this.readyState!=4&&(this.g=!1,ss(this)),this.readyState=0},n.Pa=function(o){if(this.g&&(this.l=o,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=o.headers,this.readyState=2,is(this)),this.g&&(this.readyState=3,is(this),this.g)))if(this.responseType==="arraybuffer")o.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(typeof a.ReadableStream<"u"&&"body"in o){if(this.j=o.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.B=new TextDecoder;Wf(this)}else o.text().then(this.Oa.bind(this),this.ga.bind(this))};function Wf(o){o.j.read().then(o.Ma.bind(o)).catch(o.ga.bind(o))}n.Ma=function(o){if(this.g){if(this.o&&o.value)this.response.push(o.value);else if(!this.o){var u=o.value?o.value:new Uint8Array(0);(u=this.B.decode(u,{stream:!o.done}))&&(this.response=this.responseText+=u)}o.done?ss(this):is(this),this.readyState==3&&Wf(this)}},n.Oa=function(o){this.g&&(this.response=this.responseText=o,ss(this))},n.Na=function(o){this.g&&(this.response=o,ss(this))},n.ga=function(){this.g&&ss(this)};function ss(o){o.readyState=4,o.l=null,o.j=null,o.B=null,is(o)}n.setRequestHeader=function(o,u){this.A.append(o,u)},n.getResponseHeader=function(o){return this.h&&this.h.get(o.toLowerCase())||""},n.getAllResponseHeaders=function(){if(!this.h)return"";const o=[],u=this.h.entries();for(var h=u.next();!h.done;)h=h.value,o.push(h[0]+": "+h[1]),h=u.next();return o.join(`\r
21
+ `)};function is(o){o.onreadystatechange&&o.onreadystatechange.call(o)}Object.defineProperty(Li.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(o){this.m=o?"include":"same-origin"}});function Gf(o){let u="";return Ci(o,function(h,p){u+=p,u+=":",u+=h,u+=`\r
22
+ `}),u}function ac(o,u,h){e:{for(p in h){var p=!1;break e}p=!0}p||(h=Gf(h),typeof o=="string"?h!=null&&Jr(h):ne(o,u,h))}function oe(o){Ce.call(this),this.headers=new Map,this.L=o||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}m(oe,Ce);var CA=/^https?$/i,SA=["POST","PUT"];n=oe.prototype,n.Fa=function(o){this.H=o},n.ea=function(o,u,h,p){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+o);u=u?u.toUpperCase():"GET",this.D=o,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=this.L?this.L.g():Cf.g(),this.g.onreadystatechange=_(d(this.Ca,this));try{this.B=!0,this.g.open(u,String(o),!0),this.B=!1}catch(b){Kf(this,b);return}if(o=h||"",h=new Map(this.headers),p)if(Object.getPrototypeOf(p)===Object.prototype)for(var v in p)h.set(v,p[v]);else if(typeof p.keys=="function"&&typeof p.get=="function")for(const b of p.keys())h.set(b,p.get(b));else throw Error("Unknown input type for opt_headers: "+String(p));p=Array.from(h.keys()).find(b=>b.toLowerCase()=="content-type"),v=a.FormData&&o instanceof a.FormData,!(Array.prototype.indexOf.call(SA,u,void 0)>=0)||p||v||h.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[b,O]of h)this.g.setRequestHeader(b,O);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(o),this.v=!1}catch(b){Kf(this,b)}};function Kf(o,u){o.h=!1,o.g&&(o.j=!0,o.g.abort(),o.j=!1),o.l=u,o.o=5,Qf(o),Mi(o)}function Qf(o){o.A||(o.A=!0,Ne(o,"complete"),Ne(o,"error"))}n.abort=function(o){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=o||7,Ne(this,"complete"),Ne(this,"abort"),Mi(this))},n.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Mi(this,!0)),oe.Z.N.call(this)},n.Ca=function(){this.u||(this.B||this.v||this.j?Yf(this):this.Xa())},n.Xa=function(){Yf(this)};function Yf(o){if(o.h&&typeof i<"u"){if(o.v&&Jt(o)==4)setTimeout(o.Ca.bind(o),0);else if(Ne(o,"readystatechange"),Jt(o)==4){o.h=!1;try{const b=o.ca();e:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var u=!0;break e;default:u=!1}var h;if(!(h=u)){var p;if(p=b===0){let O=String(o.D).match(Ff)[1]||null;!O&&a.self&&a.self.location&&(O=a.self.location.protocol.slice(0,-1)),p=!CA.test(O?O.toLowerCase():"")}h=p}if(h)Ne(o,"complete"),Ne(o,"success");else{o.o=6;try{var v=Jt(o)>2?o.g.statusText:""}catch{v=""}o.l=v+" ["+o.ca()+"]",Qf(o)}}finally{Mi(o)}}}}function Mi(o,u){if(o.g){o.m&&(clearTimeout(o.m),o.m=null);const h=o.g;o.g=null,u||Ne(o,"ready");try{h.onreadystatechange=null}catch{}}}n.isActive=function(){return!!this.g};function Jt(o){return o.g?o.g.readyState:0}n.ca=function(){try{return Jt(this)>2?this.g.status:-1}catch{return-1}},n.la=function(){try{return this.g?this.g.responseText:""}catch{return""}},n.La=function(o){if(this.g){var u=this.g.responseText;return o&&u.indexOf(o)==0&&(u=u.substring(o.length)),cA(u)}};function Jf(o){try{if(!o.g)return null;if("response"in o.g)return o.g.response;switch(o.F){case"":case"text":return o.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in o.g)return o.g.mozResponseArrayBuffer}return null}catch{return null}}function kA(o){const u={};o=(o.g&&Jt(o)>=2&&o.g.getAllResponseHeaders()||"").split(`\r
23
+ `);for(let p=0;p<o.length;p++){if(y(o[p]))continue;var h=pA(o[p]);const v=h[0];if(h=h[1],typeof h!="string")continue;h=h.trim();const b=u[v]||[];u[v]=b,b.push(h)}nA(u,function(p){return p.join(", ")})}n.ya=function(){return this.o},n.Ha=function(){return typeof this.l=="string"?this.l:String(this.l)};function os(o,u,h){return h&&h.internalChannelParams&&h.internalChannelParams[o]||u}function Xf(o){this.za=0,this.i=[],this.j=new Yr,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=os("failFast",!1,o),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=os("baseRetryDelayMs",5e3,o),this.Za=os("retryDelaySeedMs",1e4,o),this.Ta=os("forwardChannelMaxRetries",2,o),this.va=os("forwardChannelRequestTimeoutMs",2e4,o),this.ma=o&&o.xmlHttpFactory||void 0,this.Ua=o&&o.Rb||void 0,this.Aa=o&&o.useFetchStreams||!1,this.O=void 0,this.L=o&&o.supportsCrossDomainXhr||!1,this.M="",this.h=new Vf(o&&o.concurrentRequestLimit),this.Ba=new PA,this.S=o&&o.fastHandshake||!1,this.R=o&&o.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=o&&o.Pb||!1,o&&o.ua&&this.j.ua(),o&&o.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&o&&o.detectBufferingProxy||!1,this.ia=void 0,o&&o.longPollingTimeout&&o.longPollingTimeout>0&&(this.ia=o.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}n=Xf.prototype,n.ka=8,n.I=1,n.connect=function(o,u,h,p){De(0),this.W=o,this.H=u||{},h&&p!==void 0&&(this.H.OSID=h,this.H.OAID=p),this.F=this.X,this.J=ap(this,null,this.W),Ui(this)};function cc(o){if(Zf(o),o.I==3){var u=o.V++,h=mt(o.J);if(ne(h,"SID",o.M),ne(h,"RID",u),ne(h,"TYPE","terminate"),as(o,h),u=new Kt(o,o.j,u),u.M=2,u.A=Vi(mt(h)),h=!1,a.navigator&&a.navigator.sendBeacon)try{h=a.navigator.sendBeacon(u.A.toString(),"")}catch{}!h&&a.Image&&(new Image().src=u.A,h=!0),h||(u.g=cp(u.j,null),u.g.ea(u.A)),u.F=Date.now(),Oi(u)}op(o)}function xi(o){o.g&&(lc(o),o.g.cancel(),o.g=null)}function Zf(o){xi(o),o.v&&(a.clearTimeout(o.v),o.v=null),Fi(o),o.h.cancel(),o.m&&(typeof o.m=="number"&&a.clearTimeout(o.m),o.m=null)}function Ui(o){if(!Lf(o.h)&&!o.m){o.m=!0;var u=o.Ea;_e||g(),re||(_e(),re=!0),w.add(u,o),o.D=0}}function NA(o,u){return Mf(o.h)>=o.h.j-(o.m?1:0)?!1:o.m?(o.i=u.G.concat(o.i),!0):o.I==1||o.I==2||o.D>=(o.Sa?0:o.Ta)?!1:(o.m=Qr(d(o.Ea,o,u),ip(o,o.D)),o.D++,!0)}n.Ea=function(o){if(this.m)if(this.m=null,this.I==1){if(!o){this.V=Math.floor(Math.random()*1e5),o=this.V++;const v=new Kt(this,this.j,o);let b=this.o;if(this.U&&(b?(b=hf(b),ff(b,this.U)):b=this.U),this.u!==null||this.R||(v.J=b,b=null),this.S)e:{for(var u=0,h=0;h<this.i.length;h++){t:{var p=this.i[h];if("__data__"in p.map&&(p=p.map.__data__,typeof p=="string")){p=p.length;break t}p=void 0}if(p===void 0)break;if(u+=p,u>4096){u=h;break e}if(u===4096||h===this.i.length-1){u=h+1;break e}}u=1e3}else u=1e3;u=tp(this,v,u),h=mt(this.J),ne(h,"RID",o),ne(h,"CVER",22),this.G&&ne(h,"X-HTTP-Session-Id",this.G),as(this,h),b&&(this.R?u="headers="+Jr(Gf(b))+"&"+u:this.u&&ac(h,this.u,b)),sc(this.h,v),this.Ra&&ne(h,"TYPE","init"),this.S?(ne(h,"$req",u),ne(h,"SID","null"),v.U=!0,ec(v,h,null)):ec(v,h,u),this.I=2}}else this.I==3&&(o?ep(this,o):this.i.length==0||Lf(this.h)||ep(this))};function ep(o,u){var h;u?h=u.l:h=o.V++;const p=mt(o.J);ne(p,"SID",o.M),ne(p,"RID",h),ne(p,"AID",o.K),as(o,p),o.u&&o.o&&ac(p,o.u,o.o),h=new Kt(o,o.j,h,o.D+1),o.u===null&&(h.J=o.o),u&&(o.i=u.G.concat(o.i)),u=tp(o,h,1e3),h.H=Math.round(o.va*.5)+Math.round(o.va*.5*Math.random()),sc(o.h,h),ec(h,p,u)}function as(o,u){o.H&&Ci(o.H,function(h,p){ne(u,p,h)}),o.l&&Ci({},function(h,p){ne(u,p,h)})}function tp(o,u,h){h=Math.min(o.i.length,h);const p=o.l?d(o.l.Ka,o.l,o):null;e:{var v=o.i;let z=-1;for(;;){const me=["count="+h];z==-1?h>0?(z=v[0].g,me.push("ofs="+z)):z=0:me.push("ofs="+z);let Z=!0;for(let ye=0;ye<h;ye++){var b=v[ye].g;const gt=v[ye].map;if(b-=z,b<0)z=Math.max(0,v[ye].g-100),Z=!1;else try{b="req"+b+"_"||"";try{var O=gt instanceof Map?gt:Object.entries(gt);for(const[Rn,Xt]of O){let Zt=Xt;c(Xt)&&(Zt=Qa(Xt)),me.push(b+Rn+"="+encodeURIComponent(Zt))}}catch(Rn){throw me.push(b+"type="+encodeURIComponent("_badmap")),Rn}}catch{p&&p(gt)}}if(Z){O=me.join("&");break e}}O=void 0}return o=o.i.splice(0,h),u.G=o,O}function np(o){if(!o.g&&!o.v){o.Y=1;var u=o.Da;_e||g(),re||(_e(),re=!0),w.add(u,o),o.A=0}}function uc(o){return o.g||o.v||o.A>=3?!1:(o.Y++,o.v=Qr(d(o.Da,o),ip(o,o.A)),o.A++,!0)}n.Da=function(){if(this.v=null,rp(this),this.aa&&!(this.P||this.g==null||this.T<=0)){var o=4*this.T;this.j.info("BP detection timer enabled: "+o),this.B=Qr(d(this.Wa,this),o)}},n.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,De(10),xi(this),rp(this))};function lc(o){o.B!=null&&(a.clearTimeout(o.B),o.B=null)}function rp(o){o.g=new Kt(o,o.j,"rpc",o.Y),o.u===null&&(o.g.J=o.o),o.g.P=0;var u=mt(o.na);ne(u,"RID","rpc"),ne(u,"SID",o.M),ne(u,"AID",o.K),ne(u,"CI",o.F?"0":"1"),!o.F&&o.ia&&ne(u,"TO",o.ia),ne(u,"TYPE","xmlhttp"),as(o,u),o.u&&o.o&&ac(u,o.u,o.o),o.O&&(o.g.H=o.O);var h=o.g;o=o.ba,h.M=1,h.A=Vi(mt(u)),h.u=null,h.R=!0,Nf(h,o)}n.Va=function(){this.C!=null&&(this.C=null,xi(this),uc(this),De(19))};function Fi(o){o.C!=null&&(a.clearTimeout(o.C),o.C=null)}function sp(o,u){var h=null;if(o.g==u){Fi(o),lc(o),o.g=null;var p=2}else if(rc(o.h,u))h=u.G,xf(o.h,u),p=1;else return;if(o.I!=0){if(u.o)if(p==1){h=u.u?u.u.length:0,u=Date.now()-u.F;var v=o.D;p=Ni(),Ne(p,new bf(p,h)),Ui(o)}else np(o);else if(v=u.m,v==3||v==0&&u.X>0||!(p==1&&NA(o,u)||p==2&&uc(o)))switch(h&&h.length>0&&(u=o.h,u.i=u.i.concat(h)),v){case 1:An(o,5);break;case 4:An(o,10);break;case 3:An(o,6);break;default:An(o,2)}}}function ip(o,u){let h=o.Qa+Math.floor(Math.random()*o.Za);return o.isActive()||(h*=2),h*u}function An(o,u){if(o.j.info("Error code "+u),u==2){var h=d(o.bb,o),p=o.Ua;const v=!p;p=new Qt(p||"//www.google.com/images/cleardot.gif"),a.location&&a.location.protocol=="http"||Zr(p,"https"),Vi(p),v?RA(p.toString(),h):bA(p.toString(),h)}else De(2);o.I=0,o.l&&o.l.pa(u),op(o),Zf(o)}n.bb=function(o){o?(this.j.info("Successfully pinged google.com"),De(2)):(this.j.info("Failed to ping google.com"),De(1))};function op(o){if(o.I=0,o.ja=[],o.l){const u=Uf(o.h);(u.length!=0||o.i.length!=0)&&(S(o.ja,u),S(o.ja,o.i),o.h.i.length=0,R(o.i),o.i.length=0),o.l.oa()}}function ap(o,u,h){var p=h instanceof Qt?mt(h):new Qt(h);if(p.g!="")u&&(p.g=u+"."+p.g),es(p,p.u);else{var v=a.location;p=v.protocol,u=u?u+"."+v.hostname:v.hostname,v=+v.port;const b=new Qt(null);p&&Zr(b,p),u&&(b.g=u),v&&es(b,v),h&&(b.h=h),p=b}return h=o.G,u=o.wa,h&&u&&ne(p,h,u),ne(p,"VER",o.ka),as(o,p),p}function cp(o,u,h){if(u&&!o.L)throw Error("Can't create secondary domain capable XhrIo object.");return u=o.Aa&&!o.ma?new oe(new oc({ab:h})):new oe(o.ma),u.Fa(o.L),u}n.isActive=function(){return!!this.l&&this.l.isActive(this)};function up(){}n=up.prototype,n.ra=function(){},n.qa=function(){},n.pa=function(){},n.oa=function(){},n.isActive=function(){return!0},n.Ka=function(){};function Bi(){}Bi.prototype.g=function(o,u){return new qe(o,u)};function qe(o,u){Ce.call(this),this.g=new Xf(u),this.l=o,this.h=u&&u.messageUrlParams||null,o=u&&u.messageHeaders||null,u&&u.clientProtocolHeaderRequired&&(o?o["X-Client-Protocol"]="webchannel":o={"X-Client-Protocol":"webchannel"}),this.g.o=o,o=u&&u.initMessageHeaders||null,u&&u.messageContentType&&(o?o["X-WebChannel-Content-Type"]=u.messageContentType:o={"X-WebChannel-Content-Type":u.messageContentType}),u&&u.sa&&(o?o["X-WebChannel-Client-Profile"]=u.sa:o={"X-WebChannel-Client-Profile":u.sa}),this.g.U=o,(o=u&&u.Qb)&&!y(o)&&(this.g.u=o),this.A=u&&u.supportsCrossDomainXhr||!1,this.v=u&&u.sendRawJson||!1,(u=u&&u.httpSessionIdParam)&&!y(u)&&(this.g.G=u,o=this.h,o!==null&&u in o&&(o=this.h,u in o&&delete o[u])),this.j=new rr(this)}m(qe,Ce),qe.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},qe.prototype.close=function(){cc(this.g)},qe.prototype.o=function(o){var u=this.g;if(typeof o=="string"){var h={};h.__data__=o,o=h}else this.v&&(h={},h.__data__=Qa(o),o=h);u.i.push(new _A(u.Ya++,o)),u.I==3&&Ui(u)},qe.prototype.N=function(){this.g.l=null,delete this.j,cc(this.g),delete this.g,qe.Z.N.call(this)};function lp(o){Ya.call(this),o.__headers__&&(this.headers=o.__headers__,this.statusCode=o.__status__,delete o.__headers__,delete o.__status__);var u=o.__sm__;if(u){e:{for(const h in u){o=h;break e}o=void 0}(this.i=o)&&(o=this.i,u=u!==null&&o in u?u[o]:void 0),this.data=u}else this.data=o}m(lp,Ya);function hp(){Ja.call(this),this.status=1}m(hp,Ja);function rr(o){this.g=o}m(rr,up),rr.prototype.ra=function(){Ne(this.g,"a")},rr.prototype.qa=function(o){Ne(this.g,new lp(o))},rr.prototype.pa=function(o){Ne(this.g,new hp)},rr.prototype.oa=function(){Ne(this.g,"b")},Bi.prototype.createWebChannel=Bi.prototype.g,qe.prototype.send=qe.prototype.o,qe.prototype.open=qe.prototype.m,qe.prototype.close=qe.prototype.close,Bc=function(){return new Bi},Fc=function(){return Ni()},Uc=wn,to={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},Di.NO_ERROR=0,Di.TIMEOUT=8,Di.HTTP_ERROR=6,ms=Di,Pf.COMPLETE="complete",xc=Pf,If.EventType=Gr,Gr.OPEN="a",Gr.CLOSE="b",Gr.ERROR="c",Gr.MESSAGE="d",Ce.prototype.listen=Ce.prototype.J,pr=If,oe.prototype.listenOnce=oe.prototype.K,oe.prototype.getLastError=oe.prototype.Ha,oe.prototype.getLastErrorCode=oe.prototype.ya,oe.prototype.getStatus=oe.prototype.ca,oe.prototype.getResponseJson=oe.prototype.La,oe.prototype.getResponseText=oe.prototype.la,oe.prototype.send=oe.prototype.ea,oe.prototype.setWithCredentials=oe.prototype.Fa,Mc=oe}).apply(typeof ps<"u"?ps:typeof self<"u"?self:typeof window<"u"?window:{});class Re{constructor(e){this.uid=e}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}Re.UNAUTHENTICATED=new Re(null),Re.GOOGLE_CREDENTIALS=new Re("google-credentials-uid"),Re.FIRST_PARTY=new Re("first-party-uid"),Re.MOCK_USER=new Re("mock-user");let bn="12.10.0";function Gm(n){bn=n}const rn=new zi("@firebase/firestore");function Pn(){return rn.logLevel}function V(n,...e){if(rn.logLevel<=H.DEBUG){const t=e.map(no);rn.debug(`Firestore (${bn}): ${n}`,...t)}}function Et(n,...e){if(rn.logLevel<=H.ERROR){const t=e.map(no);rn.error(`Firestore (${bn}): ${n}`,...t)}}function sn(n,...e){if(rn.logLevel<=H.WARN){const t=e.map(no);rn.warn(`Firestore (${bn}): ${n}`,...t)}}function no(n){if(typeof n=="string")return n;try{return function(t){return JSON.stringify(t)}(n)}catch{return n}}function x(n,e,t){let r="Unexpected state";typeof e=="string"?r=e:t=e,qc(n,r,t)}function qc(n,e,t){let r=`FIRESTORE (${bn}) INTERNAL ASSERTION FAILED: ${e} (ID: ${n.toString(16)})`;if(t!==void 0)try{r+=" CONTEXT: "+JSON.stringify(t)}catch{r+=" CONTEXT: "+t}throw Et(r),new Error(r)}function J(n,e,t,r){let s="Unexpected state";typeof t=="string"?s=t:r=t,n||qc(e,s,r)}function F(n,e){return n}const P={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 D extends We{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class nt{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class jc{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Km{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Re.UNAUTHENTICATED))}shutdown(){}}class Qm{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 Ym{constructor(e){this.t=e,this.currentUser=Re.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){J(this.o===void 0,42304);let r=this.i;const s=l=>this.i!==r?(r=this.i,t(l)):Promise.resolve();let i=new nt;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new nt,e.enqueueRetryable(()=>s(this.currentUser))};const a=()=>{const l=i;e.enqueueRetryable(async()=>{await l.promise,await s(this.currentUser)})},c=l=>{V("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=l,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit(l=>c(l)),setTimeout(()=>{if(!this.auth){const l=this.t.getImmediate({optional:!0});l?c(l):(V("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new nt)}},0),a()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(r=>this.i!==e?(V("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):r?(J(typeof r.accessToken=="string",31837,{l:r}),new jc(r.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return J(e===null||typeof e=="string",2055,{h:e}),new Re(e)}}class Jm{constructor(e,t,r){this.P=e,this.T=t,this.I=r,this.type="FirstParty",this.user=Re.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);const e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}}class Xm{constructor(e,t,r){this.P=e,this.T=t,this.I=r}getToken(){return Promise.resolve(new Jm(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(Re.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class $c{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class Zm{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,Ae(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){J(this.o===void 0,3512);const r=i=>{i.error!=null&&V("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);const a=i.token!==this.m;return this.m=i.token,V("FirebaseAppCheckTokenProvider",`Received ${a?"new":"existing"} token.`),a?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable(()=>r(i))};const s=i=>{V("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(i=>s(i)),setTimeout(()=>{if(!this.appCheck){const i=this.V.getImmediate({optional:!0});i?s(i):V("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new $c(this.p));const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(t=>t?(J(typeof t.token=="string",44558,{tokenResult:t}),this.m=t.token,new $c(t.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function eg(n){const e=typeof self<"u"&&(self.crypto||self.msCrypto),t=new Uint8Array(n);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let r=0;r<n;r++)t[r]=Math.floor(256*Math.random());return t}class ro{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516);let r="";for(;r.length<20;){const s=eg(40);for(let i=0;i<s.length;++i)r.length<20&&s[i]<t&&(r+=e.charAt(s[i]%62))}return r}}function W(n,e){return n<e?-1:n>e?1:0}function so(n,e){const t=Math.min(n.length,e.length);for(let r=0;r<t;r++){const s=n.charAt(r),i=e.charAt(r);if(s!==i)return io(s)===io(i)?W(s,i):io(s)?1:-1}return W(n.length,e.length)}const tg=55296,ng=57343;function io(n){const e=n.charCodeAt(0);return e>=tg&&e<=ng}function Cn(n,e,t){return n.length===e.length&&n.every((r,s)=>t(r,e[s]))}const zc="__name__";class rt{constructor(e,t,r){t===void 0?t=0:t>e.length&&x(637,{offset:t,range:e.length}),r===void 0?r=e.length-t:r>e.length-t&&x(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return rt.comparator(this,e)===0}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof rt?e.forEach(r=>{t.push(r)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=e===void 0?1:e,this.construct(this.segments,this.offset+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 this.length===0}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const r=Math.min(e.length,t.length);for(let s=0;s<r;s++){const i=rt.compareSegments(e.get(s),t.get(s));if(i!==0)return i}return W(e.length,t.length)}static compareSegments(e,t){const r=rt.isNumericId(e),s=rt.isNumericId(t);return r&&!s?-1:!r&&s?1:r&&s?rt.extractNumericId(e).compare(rt.extractNumericId(t)):so(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return kt.fromString(e.substring(4,e.length-2))}}class X extends rt{construct(e,t,r){return new X(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const r of e){if(r.indexOf("//")>=0)throw new D(P.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter(s=>s.length>0))}return new X(t)}static emptyPath(){return new X([])}}const rg=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Ee extends rt{construct(e,t,r){return new Ee(e,t,r)}static isValidIdentifier(e){return rg.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Ee.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)===zc}static keyField(){return new Ee([zc])}static fromServerFormat(e){const t=[];let r="",s=0;const i=()=>{if(r.length===0)throw new D(P.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(r),r=""};let a=!1;for(;s<e.length;){const c=e[s];if(c==="\\"){if(s+1===e.length)throw new D(P.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const l=e[s+1];if(l!=="\\"&&l!=="."&&l!=="`")throw new D(P.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=l,s+=2}else c==="`"?(a=!a,s++):c!=="."||a?(r+=c,s++):(i(),s++)}if(i(),a)throw new D(P.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Ee(t)}static emptyPath(){return new Ee([])}}class L{constructor(e){this.path=e}static fromPath(e){return new L(X.fromString(e))}static fromName(e){return new L(X.fromString(e).popFirst(5))}static empty(){return new L(X.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&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 e!==null&&X.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return X.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new L(new X(e.slice()))}}function Hc(n,e,t){if(!t)throw new D(P.INVALID_ARGUMENT,`Function ${n}() cannot be called with an empty ${e}.`)}function sg(n,e,t,r){if(e===!0&&r===!0)throw new D(P.INVALID_ARGUMENT,`${n} and ${t} cannot be used together.`)}function Wc(n){if(!L.isDocumentKey(n))throw new D(P.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${n} has ${n.length}.`)}function Gc(n){if(L.isDocumentKey(n))throw new D(P.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${n} has ${n.length}.`)}function Kc(n){return typeof n=="object"&&n!==null&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null)}function gs(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="string")return n.length>20&&(n=`${n.substring(0,20)}...`),JSON.stringify(n);if(typeof n=="number"||typeof n=="boolean")return""+n;if(typeof n=="object"){if(n instanceof Array)return"an array";{const e=function(r){return r.constructor?r.constructor.name:null}(n);return e?`a custom ${e} object`:"an object"}}return typeof n=="function"?"a function":x(12329,{type:typeof n})}function Ge(n,e){if("_delegate"in n&&(n=n._delegate),!(n instanceof e)){if(e.name===n.constructor.name)throw new D(P.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const t=gs(n);throw new D(P.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return n}function ig(n,e){if(e<=0)throw new D(P.INVALID_ARGUMENT,`Function ${n}() requires a positive number, but it was: ${e}.`)}function ue(n,e){const t={typeString:n};return e&&(t.value=e),t}function mr(n,e){if(!Kc(n))throw new D(P.INVALID_ARGUMENT,"JSON must be an object");let t;for(const r in e)if(e[r]){const s=e[r].typeString,i="value"in e[r]?{value:e[r].value}:void 0;if(!(r in n)){t=`JSON missing required field: '${r}'`;break}const a=n[r];if(s&&typeof a!==s){t=`JSON field '${r}' must be a ${s}.`;break}if(i!==void 0&&a!==i.value){t=`Expected '${r}' field to equal '${i.value}'`;break}}if(t)throw new D(P.INVALID_ARGUMENT,t);return!0}const Qc=-62135596800,Yc=1e6;class ee{static now(){return ee.fromMillis(Date.now())}static fromDate(e){return ee.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),r=Math.floor((e-1e3*t)*Yc);return new ee(t,r)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new D(P.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new D(P.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<Qc)throw new D(P.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new D(P.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/Yc}_compareTo(e){return this.seconds===e.seconds?W(this.nanoseconds,e.nanoseconds):W(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:ee._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(mr(e,ee._jsonSchema))return new ee(e.seconds,e.nanoseconds)}valueOf(){const e=this.seconds-Qc;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}ee._jsonSchemaVersion="firestore/timestamp/1.0",ee._jsonSchema={type:ue("string",ee._jsonSchemaVersion),seconds:ue("number"),nanoseconds:ue("number")};class B{static fromTimestamp(e){return new B(e)}static min(){return new B(new ee(0,0))}static max(){return new B(new ee(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}const gr=-1;function og(n,e){const t=n.toTimestamp().seconds,r=n.toTimestamp().nanoseconds+1,s=B.fromTimestamp(r===1e9?new ee(t+1,0):new ee(t,r));return new Nt(s,L.empty(),e)}function ag(n){return new Nt(n.readTime,n.key,gr)}class Nt{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new Nt(B.min(),L.empty(),gr)}static max(){return new Nt(B.max(),L.empty(),gr)}}function cg(n,e){let t=n.readTime.compareTo(e.readTime);return t!==0?t:(t=L.comparator(n.documentKey,e.documentKey),t!==0?t:W(n.largestBatchId,e.largestBatchId))}const ug="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class lg{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Sn(n){if(n.code!==P.FAILED_PRECONDITION||n.message!==ug)throw n;V("LocalStore","Unexpectedly lost primary lease")}class C{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(t=>{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)},t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&x(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new C((r,s)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(r,s)},this.catchCallback=i=>{this.wrapFailure(t,i).next(r,s)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{const t=e();return t instanceof C?t:C.resolve(t)}catch(t){return C.reject(t)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):C.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):C.reject(t)}static resolve(e){return new C((t,r)=>{t(e)})}static reject(e){return new C((t,r)=>{r(e)})}static waitFor(e){return new C((t,r)=>{let s=0,i=0,a=!1;e.forEach(c=>{++s,c.next(()=>{++i,a&&i===s&&t()},l=>r(l))}),a=!0,i===s&&t()})}static or(e){let t=C.resolve(!1);for(const r of e)t=t.next(s=>s?C.resolve(s):r());return t}static forEach(e,t){const r=[];return e.forEach((s,i)=>{r.push(t.call(this,s,i))}),this.waitFor(r)}static mapArray(e,t){return new C((r,s)=>{const i=e.length,a=new Array(i);let c=0;for(let l=0;l<i;l++){const d=l;t(e[d]).next(f=>{a[d]=f,++c,c===i&&r(a)},f=>s(f))}})}static doWhile(e,t){return new C((r,s)=>{const i=()=>{e()===!0?t().next(()=>{i()},s):r()};i()})}}function hg(n){const e=n.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function kn(n){return n.name==="IndexedDbTransactionError"}class _s{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=r=>this.ae(r),this.ue=r=>t.writeSequenceNumber(r))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.ue&&this.ue(e),e}}_s.ce=-1;const oo=-1;function ys(n){return n==null}function Es(n){return n===0&&1/n==-1/0}function dg(n){return typeof n=="number"&&Number.isInteger(n)&&!Es(n)&&n<=Number.MAX_SAFE_INTEGER&&n>=Number.MIN_SAFE_INTEGER}const Jc="";function fg(n){let e="";for(let t=0;t<n.length;t++)e.length>0&&(e=Xc(e)),e=pg(n.get(t),e);return Xc(e)}function pg(n,e){let t=e;const r=n.length;for(let s=0;s<r;s++){const i=n.charAt(s);switch(i){case"\0":t+="";break;case Jc:t+="";break;default:t+=i}}return t}function Xc(n){return n+Jc+""}function Zc(n){let e=0;for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&e++;return e}function Dt(n,e){for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&e(t,n[t])}function mg(n,e){const t=[];for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&t.push(e(n[r],r,n));return t}function eu(n){for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}class se{constructor(e,t){this.comparator=e,this.root=t||Te.EMPTY}insert(e,t){return new se(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Te.BLACK,null,null))}remove(e){return new se(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Te.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const r=this.comparator(e,t.key);if(r===0)return t.value;r<0?t=t.left:r>0&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){const s=this.comparator(e,r.key);if(s===0)return t+r.left.size;s<0?r=r.left:(t+=r.left.size+1,r=r.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,r)=>(e(t,r),!1))}toString(){const e=[];return this.inorderTraversal((t,r)=>(e.push(`${t}:${r}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new Ts(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Ts(this.root,e,this.comparator,!1)}getReverseIterator(){return new Ts(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Ts(this.root,e,this.comparator,!0)}}class Ts{constructor(e,t,r,s){this.isReverse=s,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&s&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(i===0){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const 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 this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class Te{constructor(e,t,r,s,i){this.key=e,this.value=t,this.color=r??Te.RED,this.left=s??Te.EMPTY,this.right=i??Te.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,s,i){return new Te(e??this.key,t??this.value,r??this.color,s??this.left,i??this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let s=this;const i=r(e,s.key);return s=i<0?s.copy(null,null,null,s.left.insert(e,t,r),null):i===0?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,r)),s.fixUp()}removeMin(){if(this.left.isEmpty())return Te.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 r,s=this;if(t(e,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),t(e,s.key)===0){if(s.right.isEmpty())return Te.EMPTY;r=s.right.min(),s=s.copy(r.key,r.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(e,t))}return s.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(){const e=this.copy(null,null,Te.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,Te.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const 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(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw x(43730,{key:this.key,value:this.value});if(this.right.isRed())throw x(14113,{key:this.key,value:this.value});const e=this.left.check();if(e!==this.right.check())throw x(27949);return e+(this.isRed()?0:1)}}Te.EMPTY=null,Te.RED=!0,Te.BLACK=!1,Te.EMPTY=new class{constructor(){this.size=0}get key(){throw x(57766)}get value(){throw x(16141)}get color(){throw x(16727)}get left(){throw x(29726)}get right(){throw x(36894)}copy(e,t,r,s,i){return this}insert(e,t,r){return new Te(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 fe{constructor(e){this.comparator=e,this.data=new se(this.comparator)}has(e){return this.data.get(e)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,r)=>(e(t),!1))}forEachInRange(e,t){const r=this.data.getIteratorFrom(e[0]);for(;r.hasNext();){const s=r.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.key)}}forEachWhile(e,t){let r;for(r=t!==void 0?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new tu(this.data.getIterator())}getIteratorFrom(e){return new tu(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(r=>{t=t.add(r)}),t}isEqual(e){if(!(e instanceof fe)||this.size!==e.size)return!1;const t=this.data.getIterator(),r=e.data.getIterator();for(;t.hasNext();){const s=t.getNext().key,i=r.getNext().key;if(this.comparator(s,i)!==0)return!1}return!0}toArray(){const e=[];return this.forEach(t=>{e.push(t)}),e}toString(){const e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){const t=new fe(this.comparator);return t.data=e,t}}class tu{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class Fe{constructor(e){this.fields=e,e.sort(Ee.comparator)}static empty(){return new Fe([])}unionWith(e){let t=new fe(Ee.comparator);for(const r of this.fields)t=t.add(r);for(const r of e)t=t.add(r);return new Fe(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Cn(this.fields,e.fields,(t,r)=>t.isEqual(r))}}class nu extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class we{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(s){try{return atob(s)}catch(i){throw typeof DOMException<"u"&&i instanceof DOMException?new nu("Invalid base64 string: "+i):i}}(e);return new we(t)}static fromUint8Array(e){const t=function(s){let i="";for(let a=0;a<s.length;++a)i+=String.fromCharCode(s[a]);return i}(e);return new we(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 function(t){return btoa(t)}(this.binaryString)}toUint8Array(){return function(t){const r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return W(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}we.EMPTY_BYTE_STRING=new we("");const gg=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Ot(n){if(J(!!n,39018),typeof n=="string"){let e=0;const t=gg.exec(n);if(J(!!t,46558,{timestamp:n}),t[1]){let s=t[1];s=(s+"000000000").substr(0,9),e=Number(s)}const r=new Date(n);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}return{seconds:ae(n.seconds),nanos:ae(n.nanos)}}function ae(n){return typeof n=="number"?n:typeof n=="string"?Number(n):0}function Vt(n){return typeof n=="string"?we.fromBase64String(n):we.fromUint8Array(n)}const ru="server_timestamp",su="__type__",iu="__previous_value__",ou="__local_write_time__";function ws(n){return(n?.mapValue?.fields||{})[su]?.stringValue===ru}function Is(n){const e=n.mapValue.fields[iu];return ws(e)?Is(e):e}function _r(n){const e=Ot(n.mapValue.fields[ou].timestampValue);return new ee(e.seconds,e.nanos)}class _g{constructor(e,t,r,s,i,a,c,l,d,f,m){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=s,this.ssl=i,this.forceLongPolling=a,this.autoDetectLongPolling=c,this.longPollingOptions=l,this.useFetchStreams=d,this.isUsingEmulator=f,this.apiKey=m}}const vs="(default)";class yr{constructor(e,t){this.projectId=e,this.database=t||vs}static empty(){return new yr("","")}get isDefaultDatabase(){return this.database===vs}isEqual(e){return e instanceof yr&&e.projectId===this.projectId&&e.database===this.database}}function yg(n,e){if(!Object.prototype.hasOwnProperty.apply(n.options,["projectId"]))throw new D(P.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new yr(n.options.projectId,e)}const au="__type__",Eg="__max__",As={mapValue:{}},cu="__vector__",Rs="value";function Lt(n){return"nullValue"in n?0:"booleanValue"in n?1:"integerValue"in n||"doubleValue"in n?2:"timestampValue"in n?3:"stringValue"in n?5:"bytesValue"in n?6:"referenceValue"in n?7:"geoPointValue"in n?8:"arrayValue"in n?9:"mapValue"in n?ws(n)?4:wg(n)?9007199254740991:Tg(n)?10:11:x(28295,{value:n})}function st(n,e){if(n===e)return!0;const t=Lt(n);if(t!==Lt(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return n.booleanValue===e.booleanValue;case 4:return _r(n).isEqual(_r(e));case 3:return function(s,i){if(typeof s.timestampValue=="string"&&typeof i.timestampValue=="string"&&s.timestampValue.length===i.timestampValue.length)return s.timestampValue===i.timestampValue;const a=Ot(s.timestampValue),c=Ot(i.timestampValue);return a.seconds===c.seconds&&a.nanos===c.nanos}(n,e);case 5:return n.stringValue===e.stringValue;case 6:return function(s,i){return Vt(s.bytesValue).isEqual(Vt(i.bytesValue))}(n,e);case 7:return n.referenceValue===e.referenceValue;case 8:return function(s,i){return ae(s.geoPointValue.latitude)===ae(i.geoPointValue.latitude)&&ae(s.geoPointValue.longitude)===ae(i.geoPointValue.longitude)}(n,e);case 2:return function(s,i){if("integerValue"in s&&"integerValue"in i)return ae(s.integerValue)===ae(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){const a=ae(s.doubleValue),c=ae(i.doubleValue);return a===c?Es(a)===Es(c):isNaN(a)&&isNaN(c)}return!1}(n,e);case 9:return Cn(n.arrayValue.values||[],e.arrayValue.values||[],st);case 10:case 11:return function(s,i){const a=s.mapValue.fields||{},c=i.mapValue.fields||{};if(Zc(a)!==Zc(c))return!1;for(const l in a)if(a.hasOwnProperty(l)&&(c[l]===void 0||!st(a[l],c[l])))return!1;return!0}(n,e);default:return x(52216,{left:n})}}function Er(n,e){return(n.values||[]).find(t=>st(t,e))!==void 0}function Nn(n,e){if(n===e)return 0;const t=Lt(n),r=Lt(e);if(t!==r)return W(t,r);switch(t){case 0:case 9007199254740991:return 0;case 1:return W(n.booleanValue,e.booleanValue);case 2:return function(i,a){const c=ae(i.integerValue||i.doubleValue),l=ae(a.integerValue||a.doubleValue);return c<l?-1:c>l?1:c===l?0:isNaN(c)?isNaN(l)?0:-1:1}(n,e);case 3:return uu(n.timestampValue,e.timestampValue);case 4:return uu(_r(n),_r(e));case 5:return so(n.stringValue,e.stringValue);case 6:return function(i,a){const c=Vt(i),l=Vt(a);return c.compareTo(l)}(n.bytesValue,e.bytesValue);case 7:return function(i,a){const c=i.split("/"),l=a.split("/");for(let d=0;d<c.length&&d<l.length;d++){const f=W(c[d],l[d]);if(f!==0)return f}return W(c.length,l.length)}(n.referenceValue,e.referenceValue);case 8:return function(i,a){const c=W(ae(i.latitude),ae(a.latitude));return c!==0?c:W(ae(i.longitude),ae(a.longitude))}(n.geoPointValue,e.geoPointValue);case 9:return lu(n.arrayValue,e.arrayValue);case 10:return function(i,a){const c=i.fields||{},l=a.fields||{},d=c[Rs]?.arrayValue,f=l[Rs]?.arrayValue,m=W(d?.values?.length||0,f?.values?.length||0);return m!==0?m:lu(d,f)}(n.mapValue,e.mapValue);case 11:return function(i,a){if(i===As.mapValue&&a===As.mapValue)return 0;if(i===As.mapValue)return 1;if(a===As.mapValue)return-1;const c=i.fields||{},l=Object.keys(c),d=a.fields||{},f=Object.keys(d);l.sort(),f.sort();for(let m=0;m<l.length&&m<f.length;++m){const _=so(l[m],f[m]);if(_!==0)return _;const R=Nn(c[l[m]],d[f[m]]);if(R!==0)return R}return W(l.length,f.length)}(n.mapValue,e.mapValue);default:throw x(23264,{he:t})}}function uu(n,e){if(typeof n=="string"&&typeof e=="string"&&n.length===e.length)return W(n,e);const t=Ot(n),r=Ot(e),s=W(t.seconds,r.seconds);return s!==0?s:W(t.nanos,r.nanos)}function lu(n,e){const t=n.values||[],r=e.values||[];for(let s=0;s<t.length&&s<r.length;++s){const i=Nn(t[s],r[s]);if(i)return i}return W(t.length,r.length)}function Dn(n){return ao(n)}function ao(n){return"nullValue"in n?"null":"booleanValue"in n?""+n.booleanValue:"integerValue"in n?""+n.integerValue:"doubleValue"in n?""+n.doubleValue:"timestampValue"in n?function(t){const r=Ot(t);return`time(${r.seconds},${r.nanos})`}(n.timestampValue):"stringValue"in n?n.stringValue:"bytesValue"in n?function(t){return Vt(t).toBase64()}(n.bytesValue):"referenceValue"in n?function(t){return L.fromName(t).toString()}(n.referenceValue):"geoPointValue"in n?function(t){return`geo(${t.latitude},${t.longitude})`}(n.geoPointValue):"arrayValue"in n?function(t){let r="[",s=!0;for(const i of t.values||[])s?s=!1:r+=",",r+=ao(i);return r+"]"}(n.arrayValue):"mapValue"in n?function(t){const r=Object.keys(t.fields||{}).sort();let s="{",i=!0;for(const a of r)i?i=!1:s+=",",s+=`${a}:${ao(t.fields[a])}`;return s+"}"}(n.mapValue):x(61005,{value:n})}function bs(n){switch(Lt(n)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const e=Is(n);return e?16+bs(e):16;case 5:return 2*n.stringValue.length;case 6:return Vt(n.bytesValue).approximateByteSize();case 7:return n.referenceValue.length;case 9:return function(r){return(r.values||[]).reduce((s,i)=>s+bs(i),0)}(n.arrayValue);case 10:case 11:return function(r){let s=0;return Dt(r.fields,(i,a)=>{s+=i.length+bs(a)}),s}(n.mapValue);default:throw x(13486,{value:n})}}function Ps(n,e){return{referenceValue:`projects/${n.projectId}/databases/${n.database}/documents/${e.path.canonicalString()}`}}function co(n){return!!n&&"integerValue"in n}function uo(n){return!!n&&"arrayValue"in n}function hu(n){return!!n&&"nullValue"in n}function du(n){return!!n&&"doubleValue"in n&&isNaN(Number(n.doubleValue))}function Cs(n){return!!n&&"mapValue"in n}function Tg(n){return(n?.mapValue?.fields||{})[au]?.stringValue===cu}function Tr(n){if(n.geoPointValue)return{geoPointValue:{...n.geoPointValue}};if(n.timestampValue&&typeof n.timestampValue=="object")return{timestampValue:{...n.timestampValue}};if(n.mapValue){const e={mapValue:{fields:{}}};return Dt(n.mapValue.fields,(t,r)=>e.mapValue.fields[t]=Tr(r)),e}if(n.arrayValue){const e={arrayValue:{values:[]}};for(let t=0;t<(n.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Tr(n.arrayValue.values[t]);return e}return{...n}}function wg(n){return(((n.mapValue||{}).fields||{}).__type__||{}).stringValue===Eg}class Se{constructor(e){this.value=e}static empty(){return new Se({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r<e.length-1;++r)if(t=(t.mapValue.fields||{})[e.get(r)],!Cs(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Tr(t)}setAll(e){let t=Ee.emptyPath(),r={},s=[];e.forEach((a,c)=>{if(!t.isImmediateParentOf(c)){const l=this.getFieldsMap(t);this.applyChanges(l,r,s),r={},s=[],t=c.popLast()}a?r[c.lastSegment()]=Tr(a):s.push(c.lastSegment())});const i=this.getFieldsMap(t);this.applyChanges(i,r,s)}delete(e){const t=this.field(e.popLast());Cs(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return st(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let r=0;r<e.length;++r){let s=t.mapValue.fields[e.get(r)];Cs(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(r)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,r){Dt(t,(s,i)=>e[s]=i);for(const s of r)delete e[s]}clone(){return new Se(Tr(this.value))}}function fu(n){const e=[];return Dt(n.fields,(t,r)=>{const s=new Ee([t]);if(Cs(r)){const i=fu(r.mapValue).fields;if(i.length===0)e.push(s);else for(const a of i)e.push(s.child(a))}else e.push(s)}),new Fe(e)}class be{constructor(e,t,r,s,i,a,c){this.key=e,this.documentType=t,this.version=r,this.readTime=s,this.createTime=i,this.data=a,this.documentState=c}static newInvalidDocument(e){return new be(e,0,B.min(),B.min(),B.min(),Se.empty(),0)}static newFoundDocument(e,t,r,s){return new be(e,1,t,B.min(),r,s,0)}static newNoDocument(e,t){return new be(e,2,t,B.min(),B.min(),Se.empty(),0)}static newUnknownDocument(e,t){return new be(e,3,t,B.min(),B.min(),Se.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(B.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Se.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Se.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=B.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return this.documentState===1}get hasCommittedMutations(){return this.documentState===2}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return this.documentType!==0}isFoundDocument(){return this.documentType===1}isNoDocument(){return this.documentType===2}isUnknownDocument(){return this.documentType===3}isEqual(e){return e instanceof be&&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 be(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class On{constructor(e,t){this.position=e,this.inclusive=t}}function pu(n,e,t){let r=0;for(let s=0;s<n.position.length;s++){const i=e[s],a=n.position[s];if(i.field.isKeyField()?r=L.comparator(L.fromName(a.referenceValue),t.key):r=Nn(a,t.data.field(i.field)),i.dir==="desc"&&(r*=-1),r!==0)break}return r}function mu(n,e){if(n===null)return e===null;if(e===null||n.inclusive!==e.inclusive||n.position.length!==e.position.length)return!1;for(let t=0;t<n.position.length;t++)if(!st(n.position[t],e.position[t]))return!1;return!0}class wr{constructor(e,t="asc"){this.field=e,this.dir=t}}function Ig(n,e){return n.dir===e.dir&&n.field.isEqual(e.field)}class gu{}class le extends gu{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?t==="in"||t==="not-in"?this.createKeyFieldInFilter(e,t,r):new Ag(e,t,r):t==="array-contains"?new Pg(e,r):t==="in"?new Cg(e,r):t==="not-in"?new Sg(e,r):t==="array-contains-any"?new kg(e,r):new le(e,t,r)}static createKeyFieldInFilter(e,t,r){return t==="in"?new Rg(e,r):new bg(e,r)}matches(e){const t=e.data.field(this.field);return this.op==="!="?t!==null&&t.nullValue===void 0&&this.matchesComparison(Nn(t,this.value)):t!==null&&Lt(this.value)===Lt(t)&&this.matchesComparison(Nn(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return e===0;case"!=":return e!==0;case">":return e>0;case">=":return e>=0;default:return x(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class Ke extends gu{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new Ke(e,t)}matches(e){return _u(this)?this.filters.find(t=>!t.matches(e))===void 0:this.filters.find(t=>t.matches(e))!==void 0}getFlattenedFilters(){return this.Pe!==null||(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function _u(n){return n.op==="and"}function yu(n){return vg(n)&&_u(n)}function vg(n){for(const e of n.filters)if(e instanceof Ke)return!1;return!0}function lo(n){if(n instanceof le)return n.field.canonicalString()+n.op.toString()+Dn(n.value);if(yu(n))return n.filters.map(e=>lo(e)).join(",");{const e=n.filters.map(t=>lo(t)).join(",");return`${n.op}(${e})`}}function Eu(n,e){return n instanceof le?function(r,s){return s instanceof le&&r.op===s.op&&r.field.isEqual(s.field)&&st(r.value,s.value)}(n,e):n instanceof Ke?function(r,s){return s instanceof Ke&&r.op===s.op&&r.filters.length===s.filters.length?r.filters.reduce((i,a,c)=>i&&Eu(a,s.filters[c]),!0):!1}(n,e):void x(19439)}function Tu(n){return n instanceof le?function(t){return`${t.field.canonicalString()} ${t.op} ${Dn(t.value)}`}(n):n instanceof Ke?function(t){return t.op.toString()+" {"+t.getFilters().map(Tu).join(" ,")+"}"}(n):"Filter"}class Ag extends le{constructor(e,t,r){super(e,t,r),this.key=L.fromName(r.referenceValue)}matches(e){const t=L.comparator(e.key,this.key);return this.matchesComparison(t)}}class Rg extends le{constructor(e,t){super(e,"in",t),this.keys=wu("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class bg extends le{constructor(e,t){super(e,"not-in",t),this.keys=wu("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function wu(n,e){return(e.arrayValue?.values||[]).map(t=>L.fromName(t.referenceValue))}class Pg extends le{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return uo(t)&&Er(t.arrayValue,this.value)}}class Cg extends le{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return t!==null&&Er(this.value.arrayValue,t)}}class Sg extends le{constructor(e,t){super(e,"not-in",t)}matches(e){if(Er(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return t!==null&&t.nullValue===void 0&&!Er(this.value.arrayValue,t)}}class kg extends le{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!uo(t)||!t.arrayValue.values)&&t.arrayValue.values.some(r=>Er(this.value.arrayValue,r))}}class Ng{constructor(e,t=null,r=[],s=[],i=null,a=null,c=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=s,this.limit=i,this.startAt=a,this.endAt=c,this.Te=null}}function Iu(n,e=null,t=[],r=[],s=null,i=null,a=null){return new Ng(n,e,t,r,s,i,a)}function ho(n){const e=F(n);if(e.Te===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(r=>lo(r)).join(","),t+="|ob:",t+=e.orderBy.map(r=>function(i){return i.field.canonicalString()+i.dir}(r)).join(","),ys(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(r=>Dn(r)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(r=>Dn(r)).join(",")),e.Te=t}return e.Te}function fo(n,e){if(n.limit!==e.limit||n.orderBy.length!==e.orderBy.length)return!1;for(let t=0;t<n.orderBy.length;t++)if(!Ig(n.orderBy[t],e.orderBy[t]))return!1;if(n.filters.length!==e.filters.length)return!1;for(let t=0;t<n.filters.length;t++)if(!Eu(n.filters[t],e.filters[t]))return!1;return n.collectionGroup===e.collectionGroup&&!!n.path.isEqual(e.path)&&!!mu(n.startAt,e.startAt)&&mu(n.endAt,e.endAt)}function po(n){return L.isDocumentKey(n.path)&&n.collectionGroup===null&&n.filters.length===0}class on{constructor(e,t=null,r=[],s=[],i=null,a="F",c=null,l=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=s,this.limit=i,this.limitType=a,this.startAt=c,this.endAt=l,this.Ie=null,this.Ee=null,this.Re=null,this.startAt,this.endAt}}function Dg(n,e,t,r,s,i,a,c){return new on(n,e,t,r,s,i,a,c)}function Ss(n){return new on(n)}function vu(n){return n.filters.length===0&&n.limit===null&&n.startAt==null&&n.endAt==null&&(n.explicitOrderBy.length===0||n.explicitOrderBy.length===1&&n.explicitOrderBy[0].field.isKeyField())}function Og(n){return L.isDocumentKey(n.path)&&n.collectionGroup===null&&n.filters.length===0}function mo(n){return n.collectionGroup!==null}function Vn(n){const e=F(n);if(e.Ie===null){e.Ie=[];const t=new Set;for(const i of e.explicitOrderBy)e.Ie.push(i),t.add(i.field.canonicalString());const r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(a){let c=new fe(Ee.comparator);return a.filters.forEach(l=>{l.getFlattenedFilters().forEach(d=>{d.isInequality()&&(c=c.add(d.field))})}),c})(e).forEach(i=>{t.has(i.canonicalString())||i.isKeyField()||e.Ie.push(new wr(i,r))}),t.has(Ee.keyField().canonicalString())||e.Ie.push(new wr(Ee.keyField(),r))}return e.Ie}function it(n){const e=F(n);return e.Ee||(e.Ee=Au(e,Vn(n))),e.Ee}function Vg(n){const e=F(n);return e.Re||(e.Re=Au(e,n.explicitOrderBy)),e.Re}function Au(n,e){if(n.limitType==="F")return Iu(n.path,n.collectionGroup,e,n.filters,n.limit,n.startAt,n.endAt);{e=e.map(s=>{const i=s.dir==="desc"?"asc":"desc";return new wr(s.field,i)});const t=n.endAt?new On(n.endAt.position,n.endAt.inclusive):null,r=n.startAt?new On(n.startAt.position,n.startAt.inclusive):null;return Iu(n.path,n.collectionGroup,e,n.filters,n.limit,t,r)}}function go(n,e){const t=n.filters.concat([e]);return new on(n.path,n.collectionGroup,n.explicitOrderBy.slice(),t,n.limit,n.limitType,n.startAt,n.endAt)}function Lg(n,e){const t=n.explicitOrderBy.concat([e]);return new on(n.path,n.collectionGroup,t,n.filters.slice(),n.limit,n.limitType,n.startAt,n.endAt)}function ks(n,e,t){return new on(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),e,t,n.startAt,n.endAt)}function Mg(n,e){return new on(n.path,n.collectionGroup,n.explicitOrderBy.slice(),n.filters.slice(),n.limit,n.limitType,e,n.endAt)}function Ns(n,e){return fo(it(n),it(e))&&n.limitType===e.limitType}function Ru(n){return`${ho(it(n))}|lt:${n.limitType}`}function Ln(n){return`Query(target=${function(t){let r=t.path.canonicalString();return t.collectionGroup!==null&&(r+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(r+=`, filters: [${t.filters.map(s=>Tu(s)).join(", ")}]`),ys(t.limit)||(r+=", limit: "+t.limit),t.orderBy.length>0&&(r+=`, orderBy: [${t.orderBy.map(s=>function(a){return`${a.field.canonicalString()} (${a.dir})`}(s)).join(", ")}]`),t.startAt&&(r+=", startAt: ",r+=t.startAt.inclusive?"b:":"a:",r+=t.startAt.position.map(s=>Dn(s)).join(",")),t.endAt&&(r+=", endAt: ",r+=t.endAt.inclusive?"a:":"b:",r+=t.endAt.position.map(s=>Dn(s)).join(",")),`Target(${r})`}(it(n))}; limitType=${n.limitType})`}function Ds(n,e){return e.isFoundDocument()&&function(r,s){const i=s.key.path;return r.collectionGroup!==null?s.key.hasCollectionId(r.collectionGroup)&&r.path.isPrefixOf(i):L.isDocumentKey(r.path)?r.path.isEqual(i):r.path.isImmediateParentOf(i)}(n,e)&&function(r,s){for(const i of Vn(r))if(!i.field.isKeyField()&&s.data.field(i.field)===null)return!1;return!0}(n,e)&&function(r,s){for(const i of r.filters)if(!i.matches(s))return!1;return!0}(n,e)&&function(r,s){return!(r.startAt&&!function(a,c,l){const d=pu(a,c,l);return a.inclusive?d<=0:d<0}(r.startAt,Vn(r),s)||r.endAt&&!function(a,c,l){const d=pu(a,c,l);return a.inclusive?d>=0:d>0}(r.endAt,Vn(r),s))}(n,e)}function xg(n){return n.collectionGroup||(n.path.length%2==1?n.path.lastSegment():n.path.get(n.path.length-2))}function bu(n){return(e,t)=>{let r=!1;for(const s of Vn(n)){const i=Ug(s,e,t);if(i!==0)return i;r=r||s.field.isKeyField()}return 0}}function Ug(n,e,t){const r=n.field.isKeyField()?L.comparator(e.key,t.key):function(i,a,c){const l=a.data.field(i),d=c.data.field(i);return l!==null&&d!==null?Nn(l,d):x(42886)}(n.field,e,t);switch(n.dir){case"asc":return r;case"desc":return-1*r;default:return x(19790,{direction:n.dir})}}class an{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),r=this.inner[t];if(r!==void 0){for(const[s,i]of r)if(this.equalsFn(s,e))return i}}has(e){return this.get(e)!==void 0}set(e,t){const r=this.mapKeyFn(e),s=this.inner[r];if(s===void 0)return this.inner[r]=[[e,t]],void this.innerSize++;for(let i=0;i<s.length;i++)if(this.equalsFn(s[i][0],e))return void(s[i]=[e,t]);s.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),r=this.inner[t];if(r===void 0)return!1;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],e))return r.length===1?delete this.inner[t]:r.splice(s,1),this.innerSize--,!0;return!1}forEach(e){Dt(this.inner,(t,r)=>{for(const[s,i]of r)e(s,i)})}isEmpty(){return eu(this.inner)}size(){return this.innerSize}}const Fg=new se(L.comparator);function Tt(){return Fg}const Pu=new se(L.comparator);function Ir(...n){let e=Pu;for(const t of n)e=e.insert(t.key,t);return e}function Cu(n){let e=Pu;return n.forEach((t,r)=>e=e.insert(t,r.overlayedDocument)),e}function cn(){return vr()}function Su(){return vr()}function vr(){return new an(n=>n.toString(),(n,e)=>n.isEqual(e))}const Bg=new se(L.comparator),qg=new fe(L.comparator);function G(...n){let e=qg;for(const t of n)e=e.add(t);return e}const jg=new fe(W);function $g(){return jg}function _o(n,e){if(n.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Es(e)?"-0":e}}function ku(n){return{integerValue:""+n}}function zg(n,e){return dg(e)?ku(e):_o(n,e)}class Os{constructor(){this._=void 0}}function Hg(n,e,t){return n instanceof Vs?function(s,i){const a={fields:{[su]:{stringValue:ru},[ou]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&ws(i)&&(i=Is(i)),i&&(a.fields[iu]=i),{mapValue:a}}(t,e):n instanceof Ar?Du(n,e):n instanceof Rr?Ou(n,e):function(s,i){const a=Nu(s,i),c=Vu(a)+Vu(s.Ae);return co(a)&&co(s.Ae)?ku(c):_o(s.serializer,c)}(n,e)}function Wg(n,e,t){return n instanceof Ar?Du(n,e):n instanceof Rr?Ou(n,e):t}function Nu(n,e){return n instanceof Ls?function(r){return co(r)||function(i){return!!i&&"doubleValue"in i}(r)}(e)?e:{integerValue:0}:null}class Vs extends Os{}class Ar extends Os{constructor(e){super(),this.elements=e}}function Du(n,e){const t=Lu(e);for(const r of n.elements)t.some(s=>st(s,r))||t.push(r);return{arrayValue:{values:t}}}class Rr extends Os{constructor(e){super(),this.elements=e}}function Ou(n,e){let t=Lu(e);for(const r of n.elements)t=t.filter(s=>!st(s,r));return{arrayValue:{values:t}}}class Ls extends Os{constructor(e,t){super(),this.serializer=e,this.Ae=t}}function Vu(n){return ae(n.integerValue||n.doubleValue)}function Lu(n){return uo(n)&&n.arrayValue.values?n.arrayValue.values.slice():[]}function Gg(n,e){return n.field.isEqual(e.field)&&function(r,s){return r instanceof Ar&&s instanceof Ar||r instanceof Rr&&s instanceof Rr?Cn(r.elements,s.elements,st):r instanceof Ls&&s instanceof Ls?st(r.Ae,s.Ae):r instanceof Vs&&s instanceof Vs}(n.transform,e.transform)}class Kg{constructor(e,t){this.version=e,this.transformResults=t}}class $e{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new $e}static exists(e){return new $e(void 0,e)}static updateTime(e){return new $e(e)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Ms(n,e){return n.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(n.updateTime):n.exists===void 0||n.exists===e.isFoundDocument()}class xs{}function Mu(n,e){if(!n.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return n.isNoDocument()?new Us(n.key,$e.none()):new Pr(n.key,n.data,$e.none());{const t=n.data,r=Se.empty();let s=new fe(Ee.comparator);for(let i of e.fields)if(!s.has(i)){let a=t.field(i);a===null&&i.length>1&&(i=i.popLast(),a=t.field(i)),a===null?r.delete(i):r.set(i,a),s=s.add(i)}return new Mt(n.key,r,new Fe(s.toArray()),$e.none())}}function Qg(n,e,t){n instanceof Pr?function(s,i,a){const c=s.value.clone(),l=Fu(s.fieldTransforms,i,a.transformResults);c.setAll(l),i.convertToFoundDocument(a.version,c).setHasCommittedMutations()}(n,e,t):n instanceof Mt?function(s,i,a){if(!Ms(s.precondition,i))return void i.convertToUnknownDocument(a.version);const c=Fu(s.fieldTransforms,i,a.transformResults),l=i.data;l.setAll(Uu(s)),l.setAll(c),i.convertToFoundDocument(a.version,l).setHasCommittedMutations()}(n,e,t):function(s,i,a){i.convertToNoDocument(a.version).setHasCommittedMutations()}(0,e,t)}function br(n,e,t,r){return n instanceof Pr?function(i,a,c,l){if(!Ms(i.precondition,a))return c;const d=i.value.clone(),f=Bu(i.fieldTransforms,l,a);return d.setAll(f),a.convertToFoundDocument(a.version,d).setHasLocalMutations(),null}(n,e,t,r):n instanceof Mt?function(i,a,c,l){if(!Ms(i.precondition,a))return c;const d=Bu(i.fieldTransforms,l,a),f=a.data;return f.setAll(Uu(i)),f.setAll(d),a.convertToFoundDocument(a.version,f).setHasLocalMutations(),c===null?null:c.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map(m=>m.field))}(n,e,t,r):function(i,a,c){return Ms(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):c}(n,e,t)}function Yg(n,e){let t=null;for(const r of n.fieldTransforms){const s=e.data.field(r.field),i=Nu(r.transform,s||null);i!=null&&(t===null&&(t=Se.empty()),t.set(r.field,i))}return t||null}function xu(n,e){return n.type===e.type&&!!n.key.isEqual(e.key)&&!!n.precondition.isEqual(e.precondition)&&!!function(r,s){return r===void 0&&s===void 0||!(!r||!s)&&Cn(r,s,(i,a)=>Gg(i,a))}(n.fieldTransforms,e.fieldTransforms)&&(n.type===0?n.value.isEqual(e.value):n.type!==1||n.data.isEqual(e.data)&&n.fieldMask.isEqual(e.fieldMask))}class Pr extends xs{constructor(e,t,r,s=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class Mt extends xs{constructor(e,t,r,s,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=s,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Uu(n){const e=new Map;return n.fieldMask.fields.forEach(t=>{if(!t.isEmpty()){const r=n.data.field(t);e.set(t,r)}}),e}function Fu(n,e,t){const r=new Map;J(n.length===t.length,32656,{Ve:t.length,de:n.length});for(let s=0;s<t.length;s++){const i=n[s],a=i.transform,c=e.data.field(i.field);r.set(i.field,Wg(a,c,t[s]))}return r}function Bu(n,e,t){const r=new Map;for(const s of n){const i=s.transform,a=t.data.field(s.field);r.set(s.field,Hg(i,a,e))}return r}class Us extends xs{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Jg extends xs{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Xg{constructor(e,t,r,s){this.batchId=e,this.localWriteTime=t,this.baseMutations=r,this.mutations=s}applyToRemoteDocument(e,t){const r=t.mutationResults;for(let s=0;s<this.mutations.length;s++){const i=this.mutations[s];i.key.isEqual(e.key)&&Qg(i,e,r[s])}}applyToLocalView(e,t){for(const r of this.baseMutations)r.key.isEqual(e.key)&&(t=br(r,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=br(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const r=Su();return this.mutations.forEach(s=>{const i=e.get(s.key),a=i.overlayedDocument;let c=this.applyToLocalView(a,i.mutatedFields);c=t.has(s.key)?null:c;const l=Mu(a,c);l!==null&&r.set(s.key,l),a.isValidDocument()||a.convertToNoDocument(B.min())}),r}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),G())}isEqual(e){return this.batchId===e.batchId&&Cn(this.mutations,e.mutations,(t,r)=>xu(t,r))&&Cn(this.baseMutations,e.baseMutations,(t,r)=>xu(t,r))}}class yo{constructor(e,t,r,s){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=s}static from(e,t,r){J(e.mutations.length===r.length,58842,{me:e.mutations.length,fe:r.length});let s=function(){return Bg}();const i=e.mutations;for(let a=0;a<i.length;a++)s=s.insert(i[a].key,r[a].version);return new yo(e,t,r,s)}}class Zg{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return e!==null&&this.mutation===e.mutation}toString(){return`Overlay{
24
24
  largestBatchId: ${this.largestBatchId},
25
25
  mutation: ${this.mutation.toString()}
26
- }`}}class e_{constructor(e,t,r){this.alias=e,this.aggregateType=t,this.fieldPath=r}}class t_{constructor(e,t){this.count=e,this.unchangedNames=t}}var he,K;function n_(n){switch(n){case P.OK:return x(64938);case P.CANCELLED:case P.UNKNOWN:case P.DEADLINE_EXCEEDED:case P.RESOURCE_EXHAUSTED:case P.INTERNAL:case P.UNAVAILABLE:case P.UNAUTHENTICATED:return!1;case P.INVALID_ARGUMENT:case P.NOT_FOUND:case P.ALREADY_EXISTS:case P.PERMISSION_DENIED:case P.FAILED_PRECONDITION:case P.ABORTED:case P.OUT_OF_RANGE:case P.UNIMPLEMENTED:case P.DATA_LOSS:return!0;default:return x(15467,{code:n})}}function qu(n){if(n===void 0)return Et("GRPC error has no .code"),P.UNKNOWN;switch(n){case he.OK:return P.OK;case he.CANCELLED:return P.CANCELLED;case he.UNKNOWN:return P.UNKNOWN;case he.DEADLINE_EXCEEDED:return P.DEADLINE_EXCEEDED;case he.RESOURCE_EXHAUSTED:return P.RESOURCE_EXHAUSTED;case he.INTERNAL:return P.INTERNAL;case he.UNAVAILABLE:return P.UNAVAILABLE;case he.UNAUTHENTICATED:return P.UNAUTHENTICATED;case he.INVALID_ARGUMENT:return P.INVALID_ARGUMENT;case he.NOT_FOUND:return P.NOT_FOUND;case he.ALREADY_EXISTS:return P.ALREADY_EXISTS;case he.PERMISSION_DENIED:return P.PERMISSION_DENIED;case he.FAILED_PRECONDITION:return P.FAILED_PRECONDITION;case he.ABORTED:return P.ABORTED;case he.OUT_OF_RANGE:return P.OUT_OF_RANGE;case he.UNIMPLEMENTED:return P.UNIMPLEMENTED;case he.DATA_LOSS:return P.DATA_LOSS;default:return x(39323,{code:n})}}(K=he||(he={}))[K.OK=0]="OK",K[K.CANCELLED=1]="CANCELLED",K[K.UNKNOWN=2]="UNKNOWN",K[K.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",K[K.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",K[K.NOT_FOUND=5]="NOT_FOUND",K[K.ALREADY_EXISTS=6]="ALREADY_EXISTS",K[K.PERMISSION_DENIED=7]="PERMISSION_DENIED",K[K.UNAUTHENTICATED=16]="UNAUTHENTICATED",K[K.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",K[K.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",K[K.ABORTED=10]="ABORTED",K[K.OUT_OF_RANGE=11]="OUT_OF_RANGE",K[K.UNIMPLEMENTED=12]="UNIMPLEMENTED",K[K.INTERNAL=13]="INTERNAL",K[K.UNAVAILABLE=14]="UNAVAILABLE",K[K.DATA_LOSS=15]="DATA_LOSS";function r_(){return new TextEncoder}const s_=new kt([4294967295,4294967295],0);function ju(n){const e=r_().encode(n),t=new Lc;return t.update(e),new Uint8Array(t.digest())}function $u(n){const e=new DataView(n.buffer),t=e.getUint32(0,!0),r=e.getUint32(4,!0),s=e.getUint32(8,!0),i=e.getUint32(12,!0);return[new kt([t,r],0),new kt([s,i],0)]}class Eo{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||t>=8)throw new Sr(`Invalid padding: ${t}`);if(r<0)throw new Sr(`Invalid hash count: ${r}`);if(e.length>0&&this.hashCount===0)throw new Sr(`Invalid hash count: ${r}`);if(e.length===0&&t!==0)throw new Sr(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.pe=kt.fromNumber(this.ge)}ye(e,t,r){let s=e.add(t.multiply(kt.fromNumber(r)));return s.compare(s_)===1&&(s=new kt([s.getBits(0),s.getBits(1)],0)),s.modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(this.ge===0)return!1;const t=ju(e),[r,s]=$u(t);for(let i=0;i<this.hashCount;i++){const a=this.ye(r,s,i);if(!this.we(a))return!1}return!0}static create(e,t,r){const s=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),a=new Eo(i,s,t);return r.forEach(c=>a.insert(c)),a}insert(e){if(this.ge===0)return;const t=ju(e),[r,s]=$u(t);for(let i=0;i<this.hashCount;i++){const a=this.ye(r,s,i);this.be(a)}}be(e){const t=Math.floor(e/8),r=e%8;this.bitmap[t]|=1<<r}}class Sr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Fs{constructor(e,t,r,s,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=r,this.documentUpdates=s,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,r){const s=new Map;return s.set(e,Cr.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new Fs(B.min(),s,new se(W),Tt(),G())}}class Cr{constructor(e,t,r,s,i){this.resumeToken=e,this.current=t,this.addedDocuments=r,this.modifiedDocuments=s,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,r){return new Cr(r,t,G(),G(),G())}}class Bs{constructor(e,t,r,s){this.Se=e,this.removedTargetIds=t,this.key=r,this.De=s}}class zu{constructor(e,t){this.targetId=e,this.Ce=t}}class Hu{constructor(e,t,r=we.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=s}}class Wu{constructor(){this.ve=0,this.Fe=Gu(),this.Me=we.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return this.ve!==0}get Be(){return this.Oe}Le(e){e.approximateByteSize()>0&&(this.Oe=!0,this.Me=e)}ke(){let e=G(),t=G(),r=G();return this.Fe.forEach((s,i)=>{switch(i){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:r=r.add(s);break;default:x(38017,{changeType:i})}}),new Cr(this.Me,this.xe,e,t,r)}Ke(){this.Oe=!1,this.Fe=Gu()}qe(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}Ue(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}$e(){this.ve+=1}We(){this.ve-=1,Y(this.ve>=0,3241,{ve:this.ve})}Qe(){this.Oe=!0,this.xe=!0}}class i_{constructor(e){this.Ge=e,this.ze=new Map,this.je=Tt(),this.He=qs(),this.Je=qs(),this.Ze=new se(W)}Xe(e){for(const t of e.Se)e.De&&e.De.isFoundDocument()?this.Ye(t,e.De):this.et(t,e.key,e.De);for(const t of e.removedTargetIds)this.et(t,e.key,e.De)}tt(e){this.forEachTarget(e,t=>{const r=this.nt(t);switch(e.state){case 0:this.rt(t)&&r.Le(e.resumeToken);break;case 1:r.We(),r.Ne||r.Ke(),r.Le(e.resumeToken);break;case 2:r.We(),r.Ne||this.removeTarget(t);break;case 3:this.rt(t)&&(r.Qe(),r.Le(e.resumeToken));break;case 4:this.rt(t)&&(this.it(t),r.Le(e.resumeToken));break;default:x(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ze.forEach((r,s)=>{this.rt(s)&&t(s)})}st(e){const t=e.targetId,r=e.Ce.count,s=this.ot(t);if(s){const i=s.target;if(po(i))if(r===0){const a=new L(i.path);this.et(t,a,be.newNoDocument(a,B.min()))}else Y(r===1,20013,{expectedCount:r});else{const a=this._t(t);if(a!==r){const c=this.ut(e),l=c?this.ct(c,e,a):1;if(l!==0){this.it(t);const d=l===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ze=this.Ze.insert(t,d)}}}}}ut(e){const t=e.Ce.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:r="",padding:s=0},hashCount:i=0}=t;let a,c;try{a=Vt(r).toUint8Array()}catch(l){if(l instanceof nu)return Pn("Decoding the base64 bloom filter in existence filter failed ("+l.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw l}try{c=new Eo(a,s,i)}catch(l){return Pn(l instanceof Sr?"BloomFilter error: ":"Applying bloom filter failed: ",l),null}return c.ge===0?null:c}ct(e,t,r){return t.Ce.count===r-this.Pt(e,t.targetId)?0:2}Pt(e,t){const r=this.Ge.getRemoteKeysForTarget(t);let s=0;return r.forEach(i=>{const a=this.Ge.ht(),c=`projects/${a.projectId}/databases/${a.database}/documents/${i.path.canonicalString()}`;e.mightContain(c)||(this.et(t,i,null),s++)}),s}Tt(e){const t=new Map;this.ze.forEach((i,a)=>{const c=this.ot(a);if(c){if(i.current&&po(c.target)){const l=new L(c.target.path);this.It(l).has(a)||this.Et(a,l)||this.et(a,l,be.newNoDocument(l,e))}i.Be&&(t.set(a,i.ke()),i.Ke())}});let r=G();this.Je.forEach((i,a)=>{let c=!0;a.forEachWhile(l=>{const d=this.ot(l);return!d||d.purpose==="TargetPurposeLimboResolution"||(c=!1,!1)}),c&&(r=r.add(i))}),this.je.forEach((i,a)=>a.setReadTime(e));const s=new Fs(e,t,this.Ze,this.je,r);return this.je=Tt(),this.He=qs(),this.Je=qs(),this.Ze=new se(W),s}Ye(e,t){if(!this.rt(e))return;const r=this.Et(e,t.key)?2:0;this.nt(e).qe(t.key,r),this.je=this.je.insert(t.key,t),this.He=this.He.insert(t.key,this.It(t.key).add(e)),this.Je=this.Je.insert(t.key,this.Rt(t.key).add(e))}et(e,t,r){if(!this.rt(e))return;const s=this.nt(e);this.Et(e,t)?s.qe(t,1):s.Ue(t),this.Je=this.Je.insert(t,this.Rt(t).delete(e)),this.Je=this.Je.insert(t,this.Rt(t).add(e)),r&&(this.je=this.je.insert(t,r))}removeTarget(e){this.ze.delete(e)}_t(e){const t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.nt(e).$e()}nt(e){let t=this.ze.get(e);return t||(t=new Wu,this.ze.set(e,t)),t}Rt(e){let t=this.Je.get(e);return t||(t=new fe(W),this.Je=this.Je.insert(e,t)),t}It(e){let t=this.He.get(e);return t||(t=new fe(W),this.He=this.He.insert(e,t)),t}rt(e){const t=this.ot(e)!==null;return t||V("WatchChangeAggregator","Detected inactive target",e),t}ot(e){const t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(e){this.ze.set(e,new Wu),this.Ge.getRemoteKeysForTarget(e).forEach(t=>{this.et(e,t,null)})}Et(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}}function qs(){return new se(L.comparator)}function Gu(){return new se(L.comparator)}const o_={asc:"ASCENDING",desc:"DESCENDING"},a_={"<":"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"},c_={and:"AND",or:"OR"};class u_{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function To(n,e){return n.useProto3Json||ys(e)?e:{value:e}}function js(n,e){return n.useProto3Json?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function Ku(n,e){return n.useProto3Json?e.toBase64():e.toUint8Array()}function l_(n,e){return js(n,e.toTimestamp())}function ot(n){return Y(!!n,49232),B.fromTimestamp(function(t){const r=Ot(t);return new ee(r.seconds,r.nanos)}(n))}function wo(n,e){return Io(n,e).canonicalString()}function Io(n,e){const t=function(s){return new X(["projects",s.projectId,"databases",s.database])}(n).child("documents");return e===void 0?t:t.child(e)}function Qu(n){const e=X.fromString(n);return Y(nl(e),10190,{key:e.toString()}),e}function vo(n,e){return wo(n.databaseId,e.path)}function Ao(n,e){const t=Qu(e);if(t.get(1)!==n.databaseId.projectId)throw new D(P.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+t.get(1)+" vs "+n.databaseId.projectId);if(t.get(3)!==n.databaseId.database)throw new D(P.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+n.databaseId.database);return new L(Ju(t))}function Yu(n,e){return wo(n.databaseId,e)}function h_(n){const e=Qu(n);return e.length===4?X.emptyPath():Ju(e)}function Ro(n){return new X(["projects",n.databaseId.projectId,"databases",n.databaseId.database]).canonicalString()}function Ju(n){return Y(n.length>4&&n.get(4)==="documents",29091,{key:n.toString()}),n.popFirst(5)}function Xu(n,e,t){return{name:vo(n,e),fields:t.value.mapValue.fields}}function d_(n,e){let t;if("targetChange"in e){e.targetChange;const r=function(d){return d==="NO_CHANGE"?0:d==="ADD"?1:d==="REMOVE"?2:d==="CURRENT"?3:d==="RESET"?4:x(39313,{state:d})}(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=function(d,f){return d.useProto3Json?(Y(f===void 0||typeof f=="string",58123),we.fromBase64String(f||"")):(Y(f===void 0||f instanceof Buffer||f instanceof Uint8Array,16193),we.fromUint8Array(f||new Uint8Array))}(n,e.targetChange.resumeToken),a=e.targetChange.cause,c=a&&function(d){const f=d.code===void 0?P.UNKNOWN:qu(d.code);return new D(f,d.message||"")}(a);t=new Hu(r,s,i,c||null)}else if("documentChange"in e){e.documentChange;const r=e.documentChange;r.document,r.document.name,r.document.updateTime;const s=Ao(n,r.document.name),i=ot(r.document.updateTime),a=r.document.createTime?ot(r.document.createTime):B.min(),c=new Ce({mapValue:{fields:r.document.fields}}),l=be.newFoundDocument(s,i,a,c),d=r.targetIds||[],f=r.removedTargetIds||[];t=new Bs(d,f,l.key,l)}else if("documentDelete"in e){e.documentDelete;const r=e.documentDelete;r.document;const s=Ao(n,r.document),i=r.readTime?ot(r.readTime):B.min(),a=be.newNoDocument(s,i),c=r.removedTargetIds||[];t=new Bs([],c,a.key,a)}else if("documentRemove"in e){e.documentRemove;const r=e.documentRemove;r.document;const s=Ao(n,r.document),i=r.removedTargetIds||[];t=new Bs([],i,s,null)}else{if(!("filter"in e))return x(11601,{Vt:e});{e.filter;const r=e.filter;r.targetId;const{count:s=0,unchangedNames:i}=r,a=new t_(s,i),c=r.targetId;t=new zu(c,a)}}return t}function f_(n,e){let t;if(e instanceof Pr)t={update:Xu(n,e.key,e.value)};else if(e instanceof Us)t={delete:vo(n,e.key)};else if(e instanceof Mt)t={update:Xu(n,e.key,e.data),updateMask:I_(e.fieldMask)};else{if(!(e instanceof Jg))return x(16599,{dt:e.type});t={verify:vo(n,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(r=>function(i,a){const c=a.transform;if(c instanceof Vs)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(c instanceof Ar)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:c.elements}};if(c instanceof Rr)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:c.elements}};if(c instanceof Ls)return{fieldPath:a.field.canonicalString(),increment:c.Ae};throw x(20930,{transform:a.transform})}(0,r))),e.precondition.isNone||(t.currentDocument=function(s,i){return i.updateTime!==void 0?{updateTime:l_(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:x(27497)}(n,e.precondition)),t}function p_(n,e){return n&&n.length>0?(Y(e!==void 0,14353),n.map(t=>function(s,i){let a=s.updateTime?ot(s.updateTime):ot(i);return a.isEqual(B.min())&&(a=ot(i)),new Kg(a,s.transformResults||[])}(t,e))):[]}function m_(n,e){return{documents:[Yu(n,e.path)]}}function Zu(n,e){const t={structuredQuery:{}},r=e.path;let s;e.collectionGroup!==null?(s=r,t.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(s=r.popLast(),t.structuredQuery.from=[{collectionId:r.lastSegment()}]),t.parent=Yu(n,s);const i=function(d){if(d.length!==0)return tl(Ke.create(d,"and"))}(e.filters);i&&(t.structuredQuery.where=i);const a=function(d){if(d.length!==0)return d.map(f=>function(g){return{field:xt(g.field),direction:E_(g.dir)}}(f))}(e.orderBy);a&&(t.structuredQuery.orderBy=a);const c=To(n,e.limit);return c!==null&&(t.structuredQuery.limit=c),e.startAt&&(t.structuredQuery.startAt=function(d){return{before:d.inclusive,values:d.position}}(e.startAt)),e.endAt&&(t.structuredQuery.endAt=function(d){return{before:!d.inclusive,values:d.position}}(e.endAt)),{ft:t,parent:s}}function g_(n,e,t,r){const{ft:s,parent:i}=Zu(n,e),a={},c=[];let l=0;return t.forEach(d=>{const f="aggregate_"+l++;a[f]=d.alias,d.aggregateType==="count"?c.push({alias:f,count:{}}):d.aggregateType==="avg"?c.push({alias:f,avg:{field:xt(d.fieldPath)}}):d.aggregateType==="sum"&&c.push({alias:f,sum:{field:xt(d.fieldPath)}})}),{request:{structuredAggregationQuery:{aggregations:c,structuredQuery:s.structuredQuery},parent:s.parent},gt:a,parent:i}}function __(n){let e=h_(n.parent);const t=n.structuredQuery,r=t.from?t.from.length:0;let s=null;if(r>0){Y(r===1,65062);const f=t.from[0];f.allDescendants?s=f.collectionId:e=e.child(f.collectionId)}let i=[];t.where&&(i=function(m){const g=el(m);return g instanceof Ke&&yu(g)?g.getFilters():[g]}(t.where));let a=[];t.orderBy&&(a=function(m){return m.map(g=>function(C){return new wr(Mn(C.field),function(k){switch(k){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(C.direction))}(g))}(t.orderBy));let c=null;t.limit&&(c=function(m){let g;return g=typeof m=="object"?m.value:m,ys(g)?null:g}(t.limit));let l=null;t.startAt&&(l=function(m){const g=!!m.before,R=m.values||[];return new On(R,g)}(t.startAt));let d=null;return t.endAt&&(d=function(m){const g=!m.before,R=m.values||[];return new On(R,g)}(t.endAt)),Dg(e,s,a,i,c,"F",l,d)}function y_(n,e){const t=function(s){switch(s){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return x(28987,{purpose:s})}}(e.purpose);return t==null?null:{"goog-listen-tags":t}}function el(n){return n.unaryFilter!==void 0?function(t){switch(t.unaryFilter.op){case"IS_NAN":const r=Mn(t.unaryFilter.field);return le.create(r,"==",{doubleValue:NaN});case"IS_NULL":const s=Mn(t.unaryFilter.field);return le.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const i=Mn(t.unaryFilter.field);return le.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const a=Mn(t.unaryFilter.field);return le.create(a,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return x(61313);default:return x(60726)}}(n):n.fieldFilter!==void 0?function(t){return le.create(Mn(t.fieldFilter.field),function(s){switch(s){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return x(58110);default:return x(50506)}}(t.fieldFilter.op),t.fieldFilter.value)}(n):n.compositeFilter!==void 0?function(t){return Ke.create(t.compositeFilter.filters.map(r=>el(r)),function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return x(1026)}}(t.compositeFilter.op))}(n):x(30097,{filter:n})}function E_(n){return o_[n]}function T_(n){return a_[n]}function w_(n){return c_[n]}function xt(n){return{fieldPath:n.canonicalString()}}function Mn(n){return Ee.fromServerFormat(n.fieldPath)}function tl(n){return n instanceof le?function(t){if(t.op==="=="){if(du(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NAN"}};if(hu(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(du(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NOT_NAN"}};if(hu(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:xt(t.field),op:T_(t.op),value:t.value}}}(n):n instanceof Ke?function(t){const r=t.getFilters().map(s=>tl(s));return r.length===1?r[0]:{compositeFilter:{op:w_(t.op),filters:r}}}(n):x(54877,{filter:n})}function I_(n){const e=[];return n.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function nl(n){return n.length>=4&&n.get(0)==="projects"&&n.get(2)==="databases"}function rl(n){return!!n&&typeof n._toProto=="function"&&n._protoValueType==="ProtoValue"}class Ut{constructor(e,t,r,s,i=B.min(),a=B.min(),c=we.EMPTY_BYTE_STRING,l=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=a,this.resumeToken=c,this.expectedCount=l}withSequenceNumber(e){return new Ut(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Ut(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Ut(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Ut(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class v_{constructor(e){this.yt=e}}function A_(n){const e=__({parent:n.parent,structuredQuery:n.structuredQuery});return n.limitType==="LAST"?ks(e,e.limit,"L"):e}class R_{constructor(){this.Sn=new b_}addToCollectionParentIndex(e,t){return this.Sn.add(t),S.resolve()}getCollectionParents(e,t){return S.resolve(this.Sn.getEntries(t))}addFieldIndex(e,t){return S.resolve()}deleteFieldIndex(e,t){return S.resolve()}deleteAllFieldIndexes(e){return S.resolve()}createTargetIndexes(e,t){return S.resolve()}getDocumentsMatchingTarget(e,t){return S.resolve(null)}getIndexType(e,t){return S.resolve(0)}getFieldIndexes(e,t){return S.resolve([])}getNextCollectionGroupToUpdate(e){return S.resolve(null)}getMinOffset(e,t){return S.resolve(Nt.min())}getMinOffsetFromCollectionGroup(e,t){return S.resolve(Nt.min())}updateCollectionGroup(e,t,r){return S.resolve()}updateIndexEntries(e,t){return S.resolve()}}class b_{constructor(){this.index={}}add(e){const t=e.lastSegment(),r=e.popLast(),s=this.index[t]||new fe(X.comparator),i=!s.has(r);return this.index[t]=s.add(r),i}has(e){const t=e.lastSegment(),r=e.popLast(),s=this.index[t];return s&&s.has(r)}getEntries(e){return(this.index[e]||new fe(X.comparator)).toArray()}}const sl={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},il=41943040;class Oe{static withCacheSize(e){return new Oe(e,Oe.DEFAULT_COLLECTION_PERCENTILE,Oe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}Oe.DEFAULT_COLLECTION_PERCENTILE=10,Oe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Oe.DEFAULT=new Oe(il,Oe.DEFAULT_COLLECTION_PERCENTILE,Oe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Oe.DISABLED=new Oe(-1,0,0);class xn{constructor(e){this.sr=e}next(){return this.sr+=2,this.sr}static _r(){return new xn(0)}static ar(){return new xn(-1)}}const ol="LruGarbageCollector",P_=1048576;function al([n,e],[t,r]){const s=W(n,t);return s===0?W(e,r):s}class S_{constructor(e){this.Pr=e,this.buffer=new fe(al),this.Tr=0}Ir(){return++this.Tr}Er(e){const t=[e,this.Ir()];if(this.buffer.size<this.Pr)this.buffer=this.buffer.add(t);else{const r=this.buffer.last();al(t,r)<0&&(this.buffer=this.buffer.delete(r).add(t))}}get maxValue(){return this.buffer.last()[0]}}class C_{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.Rr=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.Ar(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return this.Rr!==null}Ar(e){V(ol,`Garbage collection scheduled in ${e}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){kn(t)?V(ol,"Ignoring IndexedDB error during garbage collection: ",t):await Cn(t)}await this.Ar(3e5)})}}class k_{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.dr(e).next(r=>Math.floor(t/100*r))}nthSequenceNumber(e,t){if(t===0)return S.resolve(_s.ce);const r=new S_(t);return this.Vr.forEachTarget(e,s=>r.Er(s.sequenceNumber)).next(()=>this.Vr.mr(e,s=>r.Er(s))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.Vr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(V("LruGarbageCollector","Garbage collection skipped; disabled"),S.resolve(sl)):this.getCacheSize(e).next(r=>r<this.params.cacheSizeCollectionThreshold?(V("LruGarbageCollector",`Garbage collection skipped; Cache size ${r} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),sl):this.gr(e,t))}getCacheSize(e){return this.Vr.getCacheSize(e)}gr(e,t){let r,s,i,a,c,l,d;const f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(m=>(m>this.params.maximumSequenceNumbersToCollect?(V("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${m}`),s=this.params.maximumSequenceNumbersToCollect):s=m,a=Date.now(),this.nthSequenceNumber(e,s))).next(m=>(r=m,c=Date.now(),this.removeTargets(e,r,t))).next(m=>(i=m,l=Date.now(),this.removeOrphanedDocuments(e,r))).next(m=>(d=Date.now(),bn()<=H.DEBUG&&V("LruGarbageCollector",`LRU Garbage Collection
26
+ }`}}class e_{constructor(e,t,r){this.alias=e,this.aggregateType=t,this.fieldPath=r}}class t_{constructor(e,t){this.count=e,this.unchangedNames=t}}var he,K;function n_(n){switch(n){case P.OK:return x(64938);case P.CANCELLED:case P.UNKNOWN:case P.DEADLINE_EXCEEDED:case P.RESOURCE_EXHAUSTED:case P.INTERNAL:case P.UNAVAILABLE:case P.UNAUTHENTICATED:return!1;case P.INVALID_ARGUMENT:case P.NOT_FOUND:case P.ALREADY_EXISTS:case P.PERMISSION_DENIED:case P.FAILED_PRECONDITION:case P.ABORTED:case P.OUT_OF_RANGE:case P.UNIMPLEMENTED:case P.DATA_LOSS:return!0;default:return x(15467,{code:n})}}function qu(n){if(n===void 0)return Et("GRPC error has no .code"),P.UNKNOWN;switch(n){case he.OK:return P.OK;case he.CANCELLED:return P.CANCELLED;case he.UNKNOWN:return P.UNKNOWN;case he.DEADLINE_EXCEEDED:return P.DEADLINE_EXCEEDED;case he.RESOURCE_EXHAUSTED:return P.RESOURCE_EXHAUSTED;case he.INTERNAL:return P.INTERNAL;case he.UNAVAILABLE:return P.UNAVAILABLE;case he.UNAUTHENTICATED:return P.UNAUTHENTICATED;case he.INVALID_ARGUMENT:return P.INVALID_ARGUMENT;case he.NOT_FOUND:return P.NOT_FOUND;case he.ALREADY_EXISTS:return P.ALREADY_EXISTS;case he.PERMISSION_DENIED:return P.PERMISSION_DENIED;case he.FAILED_PRECONDITION:return P.FAILED_PRECONDITION;case he.ABORTED:return P.ABORTED;case he.OUT_OF_RANGE:return P.OUT_OF_RANGE;case he.UNIMPLEMENTED:return P.UNIMPLEMENTED;case he.DATA_LOSS:return P.DATA_LOSS;default:return x(39323,{code:n})}}(K=he||(he={}))[K.OK=0]="OK",K[K.CANCELLED=1]="CANCELLED",K[K.UNKNOWN=2]="UNKNOWN",K[K.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",K[K.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",K[K.NOT_FOUND=5]="NOT_FOUND",K[K.ALREADY_EXISTS=6]="ALREADY_EXISTS",K[K.PERMISSION_DENIED=7]="PERMISSION_DENIED",K[K.UNAUTHENTICATED=16]="UNAUTHENTICATED",K[K.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",K[K.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",K[K.ABORTED=10]="ABORTED",K[K.OUT_OF_RANGE=11]="OUT_OF_RANGE",K[K.UNIMPLEMENTED=12]="UNIMPLEMENTED",K[K.INTERNAL=13]="INTERNAL",K[K.UNAVAILABLE=14]="UNAVAILABLE",K[K.DATA_LOSS=15]="DATA_LOSS";function r_(){return new TextEncoder}const s_=new kt([4294967295,4294967295],0);function ju(n){const e=r_().encode(n),t=new Lc;return t.update(e),new Uint8Array(t.digest())}function $u(n){const e=new DataView(n.buffer),t=e.getUint32(0,!0),r=e.getUint32(4,!0),s=e.getUint32(8,!0),i=e.getUint32(12,!0);return[new kt([t,r],0),new kt([s,i],0)]}class Eo{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||t>=8)throw new Cr(`Invalid padding: ${t}`);if(r<0)throw new Cr(`Invalid hash count: ${r}`);if(e.length>0&&this.hashCount===0)throw new Cr(`Invalid hash count: ${r}`);if(e.length===0&&t!==0)throw new Cr(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.pe=kt.fromNumber(this.ge)}ye(e,t,r){let s=e.add(t.multiply(kt.fromNumber(r)));return s.compare(s_)===1&&(s=new kt([s.getBits(0),s.getBits(1)],0)),s.modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(this.ge===0)return!1;const t=ju(e),[r,s]=$u(t);for(let i=0;i<this.hashCount;i++){const a=this.ye(r,s,i);if(!this.we(a))return!1}return!0}static create(e,t,r){const s=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),a=new Eo(i,s,t);return r.forEach(c=>a.insert(c)),a}insert(e){if(this.ge===0)return;const t=ju(e),[r,s]=$u(t);for(let i=0;i<this.hashCount;i++){const a=this.ye(r,s,i);this.be(a)}}be(e){const t=Math.floor(e/8),r=e%8;this.bitmap[t]|=1<<r}}class Cr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Fs{constructor(e,t,r,s,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=r,this.documentUpdates=s,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,r){const s=new Map;return s.set(e,Sr.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new Fs(B.min(),s,new se(W),Tt(),G())}}class Sr{constructor(e,t,r,s,i){this.resumeToken=e,this.current=t,this.addedDocuments=r,this.modifiedDocuments=s,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,r){return new Sr(r,t,G(),G(),G())}}class Bs{constructor(e,t,r,s){this.Se=e,this.removedTargetIds=t,this.key=r,this.De=s}}class zu{constructor(e,t){this.targetId=e,this.Ce=t}}class Hu{constructor(e,t,r=we.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=s}}class Wu{constructor(){this.ve=0,this.Fe=Gu(),this.Me=we.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return this.ve!==0}get Be(){return this.Oe}Le(e){e.approximateByteSize()>0&&(this.Oe=!0,this.Me=e)}ke(){let e=G(),t=G(),r=G();return this.Fe.forEach((s,i)=>{switch(i){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:r=r.add(s);break;default:x(38017,{changeType:i})}}),new Sr(this.Me,this.xe,e,t,r)}Ke(){this.Oe=!1,this.Fe=Gu()}qe(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}Ue(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}$e(){this.ve+=1}We(){this.ve-=1,J(this.ve>=0,3241,{ve:this.ve})}Qe(){this.Oe=!0,this.xe=!0}}class i_{constructor(e){this.Ge=e,this.ze=new Map,this.je=Tt(),this.He=qs(),this.Je=qs(),this.Ze=new se(W)}Xe(e){for(const t of e.Se)e.De&&e.De.isFoundDocument()?this.Ye(t,e.De):this.et(t,e.key,e.De);for(const t of e.removedTargetIds)this.et(t,e.key,e.De)}tt(e){this.forEachTarget(e,t=>{const r=this.nt(t);switch(e.state){case 0:this.rt(t)&&r.Le(e.resumeToken);break;case 1:r.We(),r.Ne||r.Ke(),r.Le(e.resumeToken);break;case 2:r.We(),r.Ne||this.removeTarget(t);break;case 3:this.rt(t)&&(r.Qe(),r.Le(e.resumeToken));break;case 4:this.rt(t)&&(this.it(t),r.Le(e.resumeToken));break;default:x(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ze.forEach((r,s)=>{this.rt(s)&&t(s)})}st(e){const t=e.targetId,r=e.Ce.count,s=this.ot(t);if(s){const i=s.target;if(po(i))if(r===0){const a=new L(i.path);this.et(t,a,be.newNoDocument(a,B.min()))}else J(r===1,20013,{expectedCount:r});else{const a=this._t(t);if(a!==r){const c=this.ut(e),l=c?this.ct(c,e,a):1;if(l!==0){this.it(t);const d=l===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ze=this.Ze.insert(t,d)}}}}}ut(e){const t=e.Ce.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:r="",padding:s=0},hashCount:i=0}=t;let a,c;try{a=Vt(r).toUint8Array()}catch(l){if(l instanceof nu)return sn("Decoding the base64 bloom filter in existence filter failed ("+l.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw l}try{c=new Eo(a,s,i)}catch(l){return sn(l instanceof Cr?"BloomFilter error: ":"Applying bloom filter failed: ",l),null}return c.ge===0?null:c}ct(e,t,r){return t.Ce.count===r-this.Pt(e,t.targetId)?0:2}Pt(e,t){const r=this.Ge.getRemoteKeysForTarget(t);let s=0;return r.forEach(i=>{const a=this.Ge.ht(),c=`projects/${a.projectId}/databases/${a.database}/documents/${i.path.canonicalString()}`;e.mightContain(c)||(this.et(t,i,null),s++)}),s}Tt(e){const t=new Map;this.ze.forEach((i,a)=>{const c=this.ot(a);if(c){if(i.current&&po(c.target)){const l=new L(c.target.path);this.It(l).has(a)||this.Et(a,l)||this.et(a,l,be.newNoDocument(l,e))}i.Be&&(t.set(a,i.ke()),i.Ke())}});let r=G();this.Je.forEach((i,a)=>{let c=!0;a.forEachWhile(l=>{const d=this.ot(l);return!d||d.purpose==="TargetPurposeLimboResolution"||(c=!1,!1)}),c&&(r=r.add(i))}),this.je.forEach((i,a)=>a.setReadTime(e));const s=new Fs(e,t,this.Ze,this.je,r);return this.je=Tt(),this.He=qs(),this.Je=qs(),this.Ze=new se(W),s}Ye(e,t){if(!this.rt(e))return;const r=this.Et(e,t.key)?2:0;this.nt(e).qe(t.key,r),this.je=this.je.insert(t.key,t),this.He=this.He.insert(t.key,this.It(t.key).add(e)),this.Je=this.Je.insert(t.key,this.Rt(t.key).add(e))}et(e,t,r){if(!this.rt(e))return;const s=this.nt(e);this.Et(e,t)?s.qe(t,1):s.Ue(t),this.Je=this.Je.insert(t,this.Rt(t).delete(e)),this.Je=this.Je.insert(t,this.Rt(t).add(e)),r&&(this.je=this.je.insert(t,r))}removeTarget(e){this.ze.delete(e)}_t(e){const t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.nt(e).$e()}nt(e){let t=this.ze.get(e);return t||(t=new Wu,this.ze.set(e,t)),t}Rt(e){let t=this.Je.get(e);return t||(t=new fe(W),this.Je=this.Je.insert(e,t)),t}It(e){let t=this.He.get(e);return t||(t=new fe(W),this.He=this.He.insert(e,t)),t}rt(e){const t=this.ot(e)!==null;return t||V("WatchChangeAggregator","Detected inactive target",e),t}ot(e){const t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(e){this.ze.set(e,new Wu),this.Ge.getRemoteKeysForTarget(e).forEach(t=>{this.et(e,t,null)})}Et(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}}function qs(){return new se(L.comparator)}function Gu(){return new se(L.comparator)}const o_={asc:"ASCENDING",desc:"DESCENDING"},a_={"<":"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"},c_={and:"AND",or:"OR"};class u_{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function To(n,e){return n.useProto3Json||ys(e)?e:{value:e}}function js(n,e){return n.useProto3Json?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function Ku(n,e){return n.useProto3Json?e.toBase64():e.toUint8Array()}function l_(n,e){return js(n,e.toTimestamp())}function ot(n){return J(!!n,49232),B.fromTimestamp(function(t){const r=Ot(t);return new ee(r.seconds,r.nanos)}(n))}function wo(n,e){return Io(n,e).canonicalString()}function Io(n,e){const t=function(s){return new X(["projects",s.projectId,"databases",s.database])}(n).child("documents");return e===void 0?t:t.child(e)}function Qu(n){const e=X.fromString(n);return J(nl(e),10190,{key:e.toString()}),e}function vo(n,e){return wo(n.databaseId,e.path)}function Ao(n,e){const t=Qu(e);if(t.get(1)!==n.databaseId.projectId)throw new D(P.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+t.get(1)+" vs "+n.databaseId.projectId);if(t.get(3)!==n.databaseId.database)throw new D(P.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+n.databaseId.database);return new L(Ju(t))}function Yu(n,e){return wo(n.databaseId,e)}function h_(n){const e=Qu(n);return e.length===4?X.emptyPath():Ju(e)}function Ro(n){return new X(["projects",n.databaseId.projectId,"databases",n.databaseId.database]).canonicalString()}function Ju(n){return J(n.length>4&&n.get(4)==="documents",29091,{key:n.toString()}),n.popFirst(5)}function Xu(n,e,t){return{name:vo(n,e),fields:t.value.mapValue.fields}}function d_(n,e){let t;if("targetChange"in e){e.targetChange;const r=function(d){return d==="NO_CHANGE"?0:d==="ADD"?1:d==="REMOVE"?2:d==="CURRENT"?3:d==="RESET"?4:x(39313,{state:d})}(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=function(d,f){return d.useProto3Json?(J(f===void 0||typeof f=="string",58123),we.fromBase64String(f||"")):(J(f===void 0||f instanceof Buffer||f instanceof Uint8Array,16193),we.fromUint8Array(f||new Uint8Array))}(n,e.targetChange.resumeToken),a=e.targetChange.cause,c=a&&function(d){const f=d.code===void 0?P.UNKNOWN:qu(d.code);return new D(f,d.message||"")}(a);t=new Hu(r,s,i,c||null)}else if("documentChange"in e){e.documentChange;const r=e.documentChange;r.document,r.document.name,r.document.updateTime;const s=Ao(n,r.document.name),i=ot(r.document.updateTime),a=r.document.createTime?ot(r.document.createTime):B.min(),c=new Se({mapValue:{fields:r.document.fields}}),l=be.newFoundDocument(s,i,a,c),d=r.targetIds||[],f=r.removedTargetIds||[];t=new Bs(d,f,l.key,l)}else if("documentDelete"in e){e.documentDelete;const r=e.documentDelete;r.document;const s=Ao(n,r.document),i=r.readTime?ot(r.readTime):B.min(),a=be.newNoDocument(s,i),c=r.removedTargetIds||[];t=new Bs([],c,a.key,a)}else if("documentRemove"in e){e.documentRemove;const r=e.documentRemove;r.document;const s=Ao(n,r.document),i=r.removedTargetIds||[];t=new Bs([],i,s,null)}else{if(!("filter"in e))return x(11601,{Vt:e});{e.filter;const r=e.filter;r.targetId;const{count:s=0,unchangedNames:i}=r,a=new t_(s,i),c=r.targetId;t=new zu(c,a)}}return t}function f_(n,e){let t;if(e instanceof Pr)t={update:Xu(n,e.key,e.value)};else if(e instanceof Us)t={delete:vo(n,e.key)};else if(e instanceof Mt)t={update:Xu(n,e.key,e.data),updateMask:I_(e.fieldMask)};else{if(!(e instanceof Jg))return x(16599,{dt:e.type});t={verify:vo(n,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(r=>function(i,a){const c=a.transform;if(c instanceof Vs)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(c instanceof Ar)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:c.elements}};if(c instanceof Rr)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:c.elements}};if(c instanceof Ls)return{fieldPath:a.field.canonicalString(),increment:c.Ae};throw x(20930,{transform:a.transform})}(0,r))),e.precondition.isNone||(t.currentDocument=function(s,i){return i.updateTime!==void 0?{updateTime:l_(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:x(27497)}(n,e.precondition)),t}function p_(n,e){return n&&n.length>0?(J(e!==void 0,14353),n.map(t=>function(s,i){let a=s.updateTime?ot(s.updateTime):ot(i);return a.isEqual(B.min())&&(a=ot(i)),new Kg(a,s.transformResults||[])}(t,e))):[]}function m_(n,e){return{documents:[Yu(n,e.path)]}}function Zu(n,e){const t={structuredQuery:{}},r=e.path;let s;e.collectionGroup!==null?(s=r,t.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(s=r.popLast(),t.structuredQuery.from=[{collectionId:r.lastSegment()}]),t.parent=Yu(n,s);const i=function(d){if(d.length!==0)return tl(Ke.create(d,"and"))}(e.filters);i&&(t.structuredQuery.where=i);const a=function(d){if(d.length!==0)return d.map(f=>function(_){return{field:xt(_.field),direction:E_(_.dir)}}(f))}(e.orderBy);a&&(t.structuredQuery.orderBy=a);const c=To(n,e.limit);return c!==null&&(t.structuredQuery.limit=c),e.startAt&&(t.structuredQuery.startAt=function(d){return{before:d.inclusive,values:d.position}}(e.startAt)),e.endAt&&(t.structuredQuery.endAt=function(d){return{before:!d.inclusive,values:d.position}}(e.endAt)),{ft:t,parent:s}}function g_(n,e,t,r){const{ft:s,parent:i}=Zu(n,e),a={},c=[];let l=0;return t.forEach(d=>{const f="aggregate_"+l++;a[f]=d.alias,d.aggregateType==="count"?c.push({alias:f,count:{}}):d.aggregateType==="avg"?c.push({alias:f,avg:{field:xt(d.fieldPath)}}):d.aggregateType==="sum"&&c.push({alias:f,sum:{field:xt(d.fieldPath)}})}),{request:{structuredAggregationQuery:{aggregations:c,structuredQuery:s.structuredQuery},parent:s.parent},gt:a,parent:i}}function __(n){let e=h_(n.parent);const t=n.structuredQuery,r=t.from?t.from.length:0;let s=null;if(r>0){J(r===1,65062);const f=t.from[0];f.allDescendants?s=f.collectionId:e=e.child(f.collectionId)}let i=[];t.where&&(i=function(m){const _=el(m);return _ instanceof Ke&&yu(_)?_.getFilters():[_]}(t.where));let a=[];t.orderBy&&(a=function(m){return m.map(_=>function(S){return new wr(Mn(S.field),function(k){switch(k){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(S.direction))}(_))}(t.orderBy));let c=null;t.limit&&(c=function(m){let _;return _=typeof m=="object"?m.value:m,ys(_)?null:_}(t.limit));let l=null;t.startAt&&(l=function(m){const _=!!m.before,R=m.values||[];return new On(R,_)}(t.startAt));let d=null;return t.endAt&&(d=function(m){const _=!m.before,R=m.values||[];return new On(R,_)}(t.endAt)),Dg(e,s,a,i,c,"F",l,d)}function y_(n,e){const t=function(s){switch(s){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return x(28987,{purpose:s})}}(e.purpose);return t==null?null:{"goog-listen-tags":t}}function el(n){return n.unaryFilter!==void 0?function(t){switch(t.unaryFilter.op){case"IS_NAN":const r=Mn(t.unaryFilter.field);return le.create(r,"==",{doubleValue:NaN});case"IS_NULL":const s=Mn(t.unaryFilter.field);return le.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const i=Mn(t.unaryFilter.field);return le.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const a=Mn(t.unaryFilter.field);return le.create(a,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return x(61313);default:return x(60726)}}(n):n.fieldFilter!==void 0?function(t){return le.create(Mn(t.fieldFilter.field),function(s){switch(s){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return x(58110);default:return x(50506)}}(t.fieldFilter.op),t.fieldFilter.value)}(n):n.compositeFilter!==void 0?function(t){return Ke.create(t.compositeFilter.filters.map(r=>el(r)),function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return x(1026)}}(t.compositeFilter.op))}(n):x(30097,{filter:n})}function E_(n){return o_[n]}function T_(n){return a_[n]}function w_(n){return c_[n]}function xt(n){return{fieldPath:n.canonicalString()}}function Mn(n){return Ee.fromServerFormat(n.fieldPath)}function tl(n){return n instanceof le?function(t){if(t.op==="=="){if(du(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NAN"}};if(hu(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(du(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NOT_NAN"}};if(hu(t.value))return{unaryFilter:{field:xt(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:xt(t.field),op:T_(t.op),value:t.value}}}(n):n instanceof Ke?function(t){const r=t.getFilters().map(s=>tl(s));return r.length===1?r[0]:{compositeFilter:{op:w_(t.op),filters:r}}}(n):x(54877,{filter:n})}function I_(n){const e=[];return n.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function nl(n){return n.length>=4&&n.get(0)==="projects"&&n.get(2)==="databases"}function rl(n){return!!n&&typeof n._toProto=="function"&&n._protoValueType==="ProtoValue"}class Ut{constructor(e,t,r,s,i=B.min(),a=B.min(),c=we.EMPTY_BYTE_STRING,l=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=a,this.resumeToken=c,this.expectedCount=l}withSequenceNumber(e){return new Ut(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Ut(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Ut(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Ut(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class v_{constructor(e){this.yt=e}}function A_(n){const e=__({parent:n.parent,structuredQuery:n.structuredQuery});return n.limitType==="LAST"?ks(e,e.limit,"L"):e}class R_{constructor(){this.Sn=new b_}addToCollectionParentIndex(e,t){return this.Sn.add(t),C.resolve()}getCollectionParents(e,t){return C.resolve(this.Sn.getEntries(t))}addFieldIndex(e,t){return C.resolve()}deleteFieldIndex(e,t){return C.resolve()}deleteAllFieldIndexes(e){return C.resolve()}createTargetIndexes(e,t){return C.resolve()}getDocumentsMatchingTarget(e,t){return C.resolve(null)}getIndexType(e,t){return C.resolve(0)}getFieldIndexes(e,t){return C.resolve([])}getNextCollectionGroupToUpdate(e){return C.resolve(null)}getMinOffset(e,t){return C.resolve(Nt.min())}getMinOffsetFromCollectionGroup(e,t){return C.resolve(Nt.min())}updateCollectionGroup(e,t,r){return C.resolve()}updateIndexEntries(e,t){return C.resolve()}}class b_{constructor(){this.index={}}add(e){const t=e.lastSegment(),r=e.popLast(),s=this.index[t]||new fe(X.comparator),i=!s.has(r);return this.index[t]=s.add(r),i}has(e){const t=e.lastSegment(),r=e.popLast(),s=this.index[t];return s&&s.has(r)}getEntries(e){return(this.index[e]||new fe(X.comparator)).toArray()}}const sl={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},il=41943040;class Oe{static withCacheSize(e){return new Oe(e,Oe.DEFAULT_COLLECTION_PERCENTILE,Oe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}Oe.DEFAULT_COLLECTION_PERCENTILE=10,Oe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Oe.DEFAULT=new Oe(il,Oe.DEFAULT_COLLECTION_PERCENTILE,Oe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Oe.DISABLED=new Oe(-1,0,0);class xn{constructor(e){this.sr=e}next(){return this.sr+=2,this.sr}static _r(){return new xn(0)}static ar(){return new xn(-1)}}const ol="LruGarbageCollector",P_=1048576;function al([n,e],[t,r]){const s=W(n,t);return s===0?W(e,r):s}class C_{constructor(e){this.Pr=e,this.buffer=new fe(al),this.Tr=0}Ir(){return++this.Tr}Er(e){const t=[e,this.Ir()];if(this.buffer.size<this.Pr)this.buffer=this.buffer.add(t);else{const r=this.buffer.last();al(t,r)<0&&(this.buffer=this.buffer.delete(r).add(t))}}get maxValue(){return this.buffer.last()[0]}}class S_{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.Rr=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.Ar(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return this.Rr!==null}Ar(e){V(ol,`Garbage collection scheduled in ${e}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){kn(t)?V(ol,"Ignoring IndexedDB error during garbage collection: ",t):await Sn(t)}await this.Ar(3e5)})}}class k_{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.dr(e).next(r=>Math.floor(t/100*r))}nthSequenceNumber(e,t){if(t===0)return C.resolve(_s.ce);const r=new C_(t);return this.Vr.forEachTarget(e,s=>r.Er(s.sequenceNumber)).next(()=>this.Vr.mr(e,s=>r.Er(s))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.Vr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(V("LruGarbageCollector","Garbage collection skipped; disabled"),C.resolve(sl)):this.getCacheSize(e).next(r=>r<this.params.cacheSizeCollectionThreshold?(V("LruGarbageCollector",`Garbage collection skipped; Cache size ${r} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),sl):this.gr(e,t))}getCacheSize(e){return this.Vr.getCacheSize(e)}gr(e,t){let r,s,i,a,c,l,d;const f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(m=>(m>this.params.maximumSequenceNumbersToCollect?(V("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${m}`),s=this.params.maximumSequenceNumbersToCollect):s=m,a=Date.now(),this.nthSequenceNumber(e,s))).next(m=>(r=m,c=Date.now(),this.removeTargets(e,r,t))).next(m=>(i=m,l=Date.now(),this.removeOrphanedDocuments(e,r))).next(m=>(d=Date.now(),Pn()<=H.DEBUG&&V("LruGarbageCollector",`LRU Garbage Collection
27
27
  Counted targets in ${a-f}ms
28
28
  Determined least recently used ${s} in `+(c-a)+`ms
29
29
  Removed ${i} targets in `+(l-c)+`ms
30
30
  Removed ${m} documents in `+(d-l)+`ms
31
- Total Duration: ${d-f}ms`),S.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:m})))}}function N_(n,e){return new k_(n,e)}class D_{constructor(){this.changes=new on(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,be.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const r=this.changes.get(t);return r!==void 0?S.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class O_{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class V_{constructor(e,t,r,s){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=r,this.indexManager=s}getDocument(e,t){let r=null;return this.documentOverlayCache.getOverlay(e,t).next(s=>(r=s,this.remoteDocumentCache.getEntry(e,t))).next(s=>(r!==null&&br(r.mutation,s,Fe.empty(),ee.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(r=>this.getLocalViewOfDocuments(e,r,G()).next(()=>r))}getLocalViewOfDocuments(e,t,r=G()){const s=an();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,r).next(i=>{let a=Ir();return i.forEach((c,l)=>{a=a.insert(c,l.overlayedDocument)}),a}))}getOverlayedDocuments(e,t){const r=an();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,G()))}populateOverlays(e,t,r){const s=[];return r.forEach(i=>{t.has(i)||s.push(i)}),this.documentOverlayCache.getOverlays(e,s).next(i=>{i.forEach((a,c)=>{t.set(a,c)})})}computeViews(e,t,r,s){let i=Tt();const a=vr(),c=function(){return vr()}();return t.forEach((l,d)=>{const f=r.get(d.key);s.has(d.key)&&(f===void 0||f.mutation instanceof Mt)?i=i.insert(d.key,d):f!==void 0?(a.set(d.key,f.mutation.getFieldMask()),br(f.mutation,d,f.mutation.getFieldMask(),ee.now())):a.set(d.key,Fe.empty())}),this.recalculateAndSaveOverlays(e,i).next(l=>(l.forEach((d,f)=>a.set(d,f)),t.forEach((d,f)=>c.set(d,new O_(f,a.get(d)??null))),c))}recalculateAndSaveOverlays(e,t){const r=vr();let s=new se((a,c)=>a-c),i=G();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(a=>{for(const c of a)c.keys().forEach(l=>{const d=t.get(l);if(d===null)return;let f=r.get(l)||Fe.empty();f=c.applyToLocalView(d,f),r.set(l,f);const m=(s.get(c.batchId)||G()).add(l);s=s.insert(c.batchId,m)})}).next(()=>{const a=[],c=s.getReverseIterator();for(;c.hasNext();){const l=c.getNext(),d=l.key,f=l.value,m=Cu();f.forEach(g=>{if(!i.has(g)){const R=Mu(t.get(g),r.get(g));R!==null&&m.set(g,R),i=i.add(g)}}),a.push(this.documentOverlayCache.saveOverlays(e,d,m))}return S.waitFor(a)}).next(()=>r)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(r=>this.recalculateAndSaveOverlays(e,r))}getDocumentsMatchingQuery(e,t,r,s){return Og(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):mo(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,s):this.getDocumentsMatchingCollectionQuery(e,t,r,s)}getNextDocuments(e,t,r,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,r,s).next(i=>{const a=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,r.largestBatchId,s-i.size):S.resolve(an());let c=gr,l=i;return a.next(d=>S.forEach(d,(f,m)=>(c<m.largestBatchId&&(c=m.largestBatchId),i.get(f)?S.resolve():this.remoteDocumentCache.getEntry(e,f).next(g=>{l=l.insert(f,g)}))).next(()=>this.populateOverlays(e,d,i)).next(()=>this.computeViews(e,l,d,G())).next(f=>({batchId:c,changes:Su(f)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new L(t)).next(r=>{let s=Ir();return r.isFoundDocument()&&(s=s.insert(r.key,r)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,r,s){const i=t.collectionGroup;let a=Ir();return this.indexManager.getCollectionParents(e,i).next(c=>S.forEach(c,l=>{const d=function(m,g){return new sn(g,null,m.explicitOrderBy.slice(),m.filters.slice(),m.limit,m.limitType,m.startAt,m.endAt)}(t,l.child(i));return this.getDocumentsMatchingCollectionQuery(e,d,r,s).next(f=>{f.forEach((m,g)=>{a=a.insert(m,g)})})}).next(()=>a))}getDocumentsMatchingCollectionQuery(e,t,r,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,r.largestBatchId).next(a=>(i=a,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,i,s))).next(a=>{i.forEach((l,d)=>{const f=d.getKey();a.get(f)===null&&(a=a.insert(f,be.newInvalidDocument(f)))});let c=Ir();return a.forEach((l,d)=>{const f=i.get(l);f!==void 0&&br(f.mutation,d,Fe.empty(),ee.now()),Ds(t,d)&&(c=c.insert(l,d))}),c})}}class L_{constructor(e){this.serializer=e,this.Nr=new Map,this.Br=new Map}getBundleMetadata(e,t){return S.resolve(this.Nr.get(t))}saveBundleMetadata(e,t){return this.Nr.set(t.id,function(s){return{id:s.id,version:s.version,createTime:ot(s.createTime)}}(t)),S.resolve()}getNamedQuery(e,t){return S.resolve(this.Br.get(t))}saveNamedQuery(e,t){return this.Br.set(t.name,function(s){return{name:s.name,query:A_(s.bundledQuery),readTime:ot(s.readTime)}}(t)),S.resolve()}}class M_{constructor(){this.overlays=new se(L.comparator),this.Lr=new Map}getOverlay(e,t){return S.resolve(this.overlays.get(t))}getOverlays(e,t){const r=an();return S.forEach(t,s=>this.getOverlay(e,s).next(i=>{i!==null&&r.set(s,i)})).next(()=>r)}saveOverlays(e,t,r){return r.forEach((s,i)=>{this.bt(e,t,i)}),S.resolve()}removeOverlaysForBatchId(e,t,r){const s=this.Lr.get(r);return s!==void 0&&(s.forEach(i=>this.overlays=this.overlays.remove(i)),this.Lr.delete(r)),S.resolve()}getOverlaysForCollection(e,t,r){const s=an(),i=t.length+1,a=new L(t.child("")),c=this.overlays.getIteratorFrom(a);for(;c.hasNext();){const l=c.getNext().value,d=l.getKey();if(!t.isPrefixOf(d.path))break;d.path.length===i&&l.largestBatchId>r&&s.set(l.getKey(),l)}return S.resolve(s)}getOverlaysForCollectionGroup(e,t,r,s){let i=new se((d,f)=>d-f);const a=this.overlays.getIterator();for(;a.hasNext();){const d=a.getNext().value;if(d.getKey().getCollectionGroup()===t&&d.largestBatchId>r){let f=i.get(d.largestBatchId);f===null&&(f=an(),i=i.insert(d.largestBatchId,f)),f.set(d.getKey(),d)}}const c=an(),l=i.getIterator();for(;l.hasNext()&&(l.getNext().value.forEach((d,f)=>c.set(d,f)),!(c.size()>=s)););return S.resolve(c)}bt(e,t,r){const s=this.overlays.get(r.key);if(s!==null){const a=this.Lr.get(s.largestBatchId).delete(r.key);this.Lr.set(s.largestBatchId,a)}this.overlays=this.overlays.insert(r.key,new Zg(t,r));let i=this.Lr.get(t);i===void 0&&(i=G(),this.Lr.set(t,i)),this.Lr.set(t,i.add(r.key))}}class x_{constructor(){this.sessionToken=we.EMPTY_BYTE_STRING}getSessionToken(e){return S.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,S.resolve()}}class bo{constructor(){this.kr=new fe(ge.Kr),this.qr=new fe(ge.Ur)}isEmpty(){return this.kr.isEmpty()}addReference(e,t){const r=new ge(e,t);this.kr=this.kr.add(r),this.qr=this.qr.add(r)}$r(e,t){e.forEach(r=>this.addReference(r,t))}removeReference(e,t){this.Wr(new ge(e,t))}Qr(e,t){e.forEach(r=>this.removeReference(r,t))}Gr(e){const t=new L(new X([])),r=new ge(t,e),s=new ge(t,e+1),i=[];return this.qr.forEachInRange([r,s],a=>{this.Wr(a),i.push(a.key)}),i}zr(){this.kr.forEach(e=>this.Wr(e))}Wr(e){this.kr=this.kr.delete(e),this.qr=this.qr.delete(e)}jr(e){const t=new L(new X([])),r=new ge(t,e),s=new ge(t,e+1);let i=G();return this.qr.forEachInRange([r,s],a=>{i=i.add(a.key)}),i}containsKey(e){const t=new ge(e,0),r=this.kr.firstAfterOrEqual(t);return r!==null&&e.isEqual(r.key)}}class ge{constructor(e,t){this.key=e,this.Hr=t}static Kr(e,t){return L.comparator(e.key,t.key)||W(e.Hr,t.Hr)}static Ur(e,t){return W(e.Hr,t.Hr)||L.comparator(e.key,t.key)}}class U_{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Yn=1,this.Jr=new fe(ge.Kr)}checkEmpty(e){return S.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,r,s){const i=this.Yn;this.Yn++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const a=new Xg(i,t,r,s);this.mutationQueue.push(a);for(const c of s)this.Jr=this.Jr.add(new ge(c.key,i)),this.indexManager.addToCollectionParentIndex(e,c.key.path.popLast());return S.resolve(a)}lookupMutationBatch(e,t){return S.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){const r=t+1,s=this.Xr(r),i=s<0?0:s;return S.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return S.resolve(this.mutationQueue.length===0?oo:this.Yn-1)}getAllMutationBatches(e){return S.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const r=new ge(t,0),s=new ge(t,Number.POSITIVE_INFINITY),i=[];return this.Jr.forEachInRange([r,s],a=>{const c=this.Zr(a.Hr);i.push(c)}),S.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new fe(W);return t.forEach(s=>{const i=new ge(s,0),a=new ge(s,Number.POSITIVE_INFINITY);this.Jr.forEachInRange([i,a],c=>{r=r.add(c.Hr)})}),S.resolve(this.Yr(r))}getAllMutationBatchesAffectingQuery(e,t){const r=t.path,s=r.length+1;let i=r;L.isDocumentKey(i)||(i=i.child(""));const a=new ge(new L(i),0);let c=new fe(W);return this.Jr.forEachWhile(l=>{const d=l.key.path;return!!r.isPrefixOf(d)&&(d.length===s&&(c=c.add(l.Hr)),!0)},a),S.resolve(this.Yr(c))}Yr(e){const t=[];return e.forEach(r=>{const s=this.Zr(r);s!==null&&t.push(s)}),t}removeMutationBatch(e,t){Y(this.ei(t.batchId,"removed")===0,55003),this.mutationQueue.shift();let r=this.Jr;return S.forEach(t.mutations,s=>{const i=new ge(s.key,t.batchId);return r=r.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)}).next(()=>{this.Jr=r})}nr(e){}containsKey(e,t){const r=new ge(t,0),s=this.Jr.firstAfterOrEqual(r);return S.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,S.resolve()}ei(e,t){return this.Xr(e)}Xr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Zr(e){const t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class F_{constructor(e){this.ti=e,this.docs=function(){return new se(L.comparator)}(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const r=t.key,s=this.docs.get(r),i=s?s.size:0,a=this.ti(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const r=this.docs.get(t);return S.resolve(r?r.document.mutableCopy():be.newInvalidDocument(t))}getEntries(e,t){let r=Tt();return t.forEach(s=>{const i=this.docs.get(s);r=r.insert(s,i?i.document.mutableCopy():be.newInvalidDocument(s))}),S.resolve(r)}getDocumentsMatchingQuery(e,t,r,s){let i=Tt();const a=t.path,c=new L(a.child("__id-9223372036854775808__")),l=this.docs.getIteratorFrom(c);for(;l.hasNext();){const{key:d,value:{document:f}}=l.getNext();if(!a.isPrefixOf(d.path))break;d.path.length>a.length+1||cg(ag(f),r)<=0||(s.has(f.key)||Ds(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return S.resolve(i)}getAllFromCollectionGroup(e,t,r,s){x(9500)}ni(e,t){return S.forEach(this.docs,r=>t(r))}newChangeBuffer(e){return new B_(this)}getSize(e){return S.resolve(this.size)}}class B_ extends D_{constructor(e){super(),this.Mr=e}applyChanges(e){const t=[];return this.changes.forEach((r,s)=>{s.isValidDocument()?t.push(this.Mr.addEntry(e,s)):this.Mr.removeEntry(r)}),S.waitFor(t)}getFromCache(e,t){return this.Mr.getEntry(e,t)}getAllFromCache(e,t){return this.Mr.getEntries(e,t)}}class q_{constructor(e){this.persistence=e,this.ri=new on(t=>ho(t),fo),this.lastRemoteSnapshotVersion=B.min(),this.highestTargetId=0,this.ii=0,this.si=new bo,this.targetCount=0,this.oi=xn._r()}forEachTarget(e,t){return this.ri.forEach((r,s)=>t(s)),S.resolve()}getLastRemoteSnapshotVersion(e){return S.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return S.resolve(this.ii)}allocateTargetId(e){return this.highestTargetId=this.oi.next(),S.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.ii&&(this.ii=t),S.resolve()}lr(e){this.ri.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.oi=new xn(t),this.highestTargetId=t),e.sequenceNumber>this.ii&&(this.ii=e.sequenceNumber)}addTargetData(e,t){return this.lr(t),this.targetCount+=1,S.resolve()}updateTargetData(e,t){return this.lr(t),S.resolve()}removeTargetData(e,t){return this.ri.delete(t.target),this.si.Gr(t.targetId),this.targetCount-=1,S.resolve()}removeTargets(e,t,r){let s=0;const i=[];return this.ri.forEach((a,c)=>{c.sequenceNumber<=t&&r.get(c.targetId)===null&&(this.ri.delete(a),i.push(this.removeMatchingKeysForTargetId(e,c.targetId)),s++)}),S.waitFor(i).next(()=>s)}getTargetCount(e){return S.resolve(this.targetCount)}getTargetData(e,t){const r=this.ri.get(t)||null;return S.resolve(r)}addMatchingKeys(e,t,r){return this.si.$r(t,r),S.resolve()}removeMatchingKeys(e,t,r){this.si.Qr(t,r);const s=this.persistence.referenceDelegate,i=[];return s&&t.forEach(a=>{i.push(s.markPotentiallyOrphaned(e,a))}),S.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.si.Gr(t),S.resolve()}getMatchingKeysForTargetId(e,t){const r=this.si.jr(t);return S.resolve(r)}containsKey(e,t){return S.resolve(this.si.containsKey(t))}}class cl{constructor(e,t){this._i={},this.overlays={},this.ai=new _s(0),this.ui=!1,this.ui=!0,this.ci=new x_,this.referenceDelegate=e(this),this.li=new q_(this),this.indexManager=new R_,this.remoteDocumentCache=function(s){return new F_(s)}(r=>this.referenceDelegate.hi(r)),this.serializer=new v_(t),this.Pi=new L_(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ui=!1,Promise.resolve()}get started(){return this.ui}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new M_,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this._i[e.toKey()];return r||(r=new U_(t,this.referenceDelegate),this._i[e.toKey()]=r),r}getGlobalsCache(){return this.ci}getTargetCache(){return this.li}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Pi}runTransaction(e,t,r){V("MemoryPersistence","Starting transaction:",e);const s=new j_(this.ai.next());return this.referenceDelegate.Ti(),r(s).next(i=>this.referenceDelegate.Ii(s).next(()=>i)).toPromise().then(i=>(s.raiseOnCommittedEvent(),i))}Ei(e,t){return S.or(Object.values(this._i).map(r=>()=>r.containsKey(e,t)))}}class j_ extends lg{constructor(e){super(),this.currentSequenceNumber=e}}class Po{constructor(e){this.persistence=e,this.Ri=new bo,this.Ai=null}static Vi(e){return new Po(e)}get di(){if(this.Ai)return this.Ai;throw x(60996)}addReference(e,t,r){return this.Ri.addReference(r,t),this.di.delete(r.toString()),S.resolve()}removeReference(e,t,r){return this.Ri.removeReference(r,t),this.di.add(r.toString()),S.resolve()}markPotentiallyOrphaned(e,t){return this.di.add(t.toString()),S.resolve()}removeTarget(e,t){this.Ri.Gr(t.targetId).forEach(s=>this.di.add(s.toString()));const r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(s=>{s.forEach(i=>this.di.add(i.toString()))}).next(()=>r.removeTargetData(e,t))}Ti(){this.Ai=new Set}Ii(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return S.forEach(this.di,r=>{const s=L.fromPath(r);return this.mi(e,s).next(i=>{i||t.removeEntry(s,B.min())})}).next(()=>(this.Ai=null,t.apply(e)))}updateLimboDocument(e,t){return this.mi(e,t).next(r=>{r?this.di.delete(t.toString()):this.di.add(t.toString())})}hi(e){return 0}mi(e,t){return S.or([()=>S.resolve(this.Ri.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}}class $s{constructor(e,t){this.persistence=e,this.fi=new on(r=>fg(r.path),(r,s)=>r.isEqual(s)),this.garbageCollector=N_(this,t)}static Vi(e,t){return new $s(e,t)}Ti(){}Ii(e){return S.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}dr(e){const t=this.pr(e);return this.persistence.getTargetCache().getTargetCount(e).next(r=>t.next(s=>r+s))}pr(e){let t=0;return this.mr(e,r=>{t++}).next(()=>t)}mr(e,t){return S.forEach(this.fi,(r,s)=>this.wr(e,r,s).next(i=>i?S.resolve():t(s)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,t){let r=0;const s=this.persistence.getRemoteDocumentCache(),i=s.newChangeBuffer();return s.ni(e,a=>this.wr(e,a,t).next(c=>{c||(r++,i.removeEntry(a,B.min()))})).next(()=>i.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.fi.set(t,e.currentSequenceNumber),S.resolve()}removeTarget(e,t){const r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),S.resolve()}removeReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),S.resolve()}updateLimboDocument(e,t){return this.fi.set(t,e.currentSequenceNumber),S.resolve()}hi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=bs(e.data.value)),t}wr(e,t,r){return S.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{const s=this.fi.get(t);return S.resolve(s!==void 0&&s>r)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class So{constructor(e,t,r,s){this.targetId=e,this.fromCache=t,this.Ts=r,this.Is=s}static Es(e,t){let r=G(),s=G();for(const i of t.docChanges)switch(i.type){case 0:r=r.add(i.doc.key);break;case 1:s=s.add(i.doc.key)}return new So(e,t.fromCache,r,s)}}class $_{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class z_{constructor(){this.Rs=!1,this.As=!1,this.Vs=100,this.ds=function(){return Cp()?8:hg(ve())>0?6:4}()}initialize(e,t){this.fs=e,this.indexManager=t,this.Rs=!0}getDocumentsMatchingQuery(e,t,r,s){const i={result:null};return this.gs(e,t).next(a=>{i.result=a}).next(()=>{if(!i.result)return this.ps(e,t,s,r).next(a=>{i.result=a})}).next(()=>{if(i.result)return;const a=new $_;return this.ys(e,t,a).next(c=>{if(i.result=c,this.As)return this.ws(e,t,a,c.size)})}).next(()=>i.result)}ws(e,t,r,s){return r.documentReadCount<this.Vs?(bn()<=H.DEBUG&&V("QueryEngine","SDK will not create cache indexes for query:",Ln(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),S.resolve()):(bn()<=H.DEBUG&&V("QueryEngine","Query:",Ln(t),"scans",r.documentReadCount,"local documents and returns",s,"documents as results."),r.documentReadCount>this.ds*s?(bn()<=H.DEBUG&&V("QueryEngine","The SDK decides to create cache indexes for query:",Ln(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,it(t))):S.resolve())}gs(e,t){if(vu(t))return S.resolve(null);let r=it(t);return this.indexManager.getIndexType(e,r).next(s=>s===0?null:(t.limit!==null&&s===1&&(t=ks(t,null,"F"),r=it(t)),this.indexManager.getDocumentsMatchingTarget(e,r).next(i=>{const a=G(...i);return this.fs.getDocuments(e,a).next(c=>this.indexManager.getMinOffset(e,r).next(l=>{const d=this.bs(t,c);return this.Ss(t,d,a,l.readTime)?this.gs(e,ks(t,null,"F")):this.Ds(e,d,t,l)}))})))}ps(e,t,r,s){return vu(t)||s.isEqual(B.min())?S.resolve(null):this.fs.getDocuments(e,r).next(i=>{const a=this.bs(t,i);return this.Ss(t,a,r,s)?S.resolve(null):(bn()<=H.DEBUG&&V("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Ln(t)),this.Ds(e,a,t,og(s,gr)).next(c=>c))})}bs(e,t){let r=new fe(bu(e));return t.forEach((s,i)=>{Ds(e,i)&&(r=r.add(i))}),r}Ss(e,t,r,s){if(e.limit===null)return!1;if(r.size!==t.size)return!0;const i=e.limitType==="F"?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(s)>0)}ys(e,t,r){return bn()<=H.DEBUG&&V("QueryEngine","Using full collection scan to execute query:",Ln(t)),this.fs.getDocumentsMatchingQuery(e,t,Nt.min(),r)}Ds(e,t,r,s){return this.fs.getDocumentsMatchingQuery(e,r,s).next(i=>(t.forEach(a=>{i=i.insert(a.key,a)}),i))}}const Co="LocalStore",H_=3e8;class W_{constructor(e,t,r,s){this.persistence=e,this.Cs=t,this.serializer=s,this.vs=new se(W),this.Fs=new on(i=>ho(i),fo),this.Ms=new Map,this.xs=e.getRemoteDocumentCache(),this.li=e.getTargetCache(),this.Pi=e.getBundleCache(),this.Os(r)}Os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new V_(this.xs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.xs.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.vs))}}function G_(n,e,t,r){return new W_(n,e,t,r)}async function ul(n,e){const t=U(n);return await t.persistence.runTransaction("Handle user change","readonly",r=>{let s;return t.mutationQueue.getAllMutationBatches(r).next(i=>(s=i,t.Os(e),t.mutationQueue.getAllMutationBatches(r))).next(i=>{const a=[],c=[];let l=G();for(const d of s){a.push(d.batchId);for(const f of d.mutations)l=l.add(f.key)}for(const d of i){c.push(d.batchId);for(const f of d.mutations)l=l.add(f.key)}return t.localDocuments.getDocuments(r,l).next(d=>({Ns:d,removedBatchIds:a,addedBatchIds:c}))})})}function K_(n,e){const t=U(n);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",r=>{const s=e.batch.keys(),i=t.xs.newChangeBuffer({trackRemovals:!0});return function(c,l,d,f){const m=d.batch,g=m.keys();let R=S.resolve();return g.forEach(C=>{R=R.next(()=>f.getEntry(l,C)).next(N=>{const k=d.docVersions.get(C);Y(k!==null,48541),N.version.compareTo(k)<0&&(m.applyToRemoteDocument(N,d),N.isValidDocument()&&(N.setReadTime(d.commitVersion),f.addEntry(N)))})}),R.next(()=>c.mutationQueue.removeMutationBatch(l,m))}(t,r,e,i).next(()=>i.apply(r)).next(()=>t.mutationQueue.performConsistencyCheck(r)).next(()=>t.documentOverlayCache.removeOverlaysForBatchId(r,s,e.batch.batchId)).next(()=>t.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(r,function(c){let l=G();for(let d=0;d<c.mutationResults.length;++d)c.mutationResults[d].transformResults.length>0&&(l=l.add(c.batch.mutations[d].key));return l}(e))).next(()=>t.localDocuments.getDocuments(r,s))})}function ll(n){const e=U(n);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.li.getLastRemoteSnapshotVersion(t))}function Q_(n,e){const t=U(n),r=e.snapshotVersion;let s=t.vs;return t.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{const a=t.xs.newChangeBuffer({trackRemovals:!0});s=t.vs;const c=[];e.targetChanges.forEach((f,m)=>{const g=s.get(m);if(!g)return;c.push(t.li.removeMatchingKeys(i,f.removedDocuments,m).next(()=>t.li.addMatchingKeys(i,f.addedDocuments,m)));let R=g.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(m)!==null?R=R.withResumeToken(we.EMPTY_BYTE_STRING,B.min()).withLastLimboFreeSnapshotVersion(B.min()):f.resumeToken.approximateByteSize()>0&&(R=R.withResumeToken(f.resumeToken,r)),s=s.insert(m,R),function(N,k,F){return N.resumeToken.approximateByteSize()===0||k.snapshotVersion.toMicroseconds()-N.snapshotVersion.toMicroseconds()>=H_?!0:F.addedDocuments.size+F.modifiedDocuments.size+F.removedDocuments.size>0}(g,R,f)&&c.push(t.li.updateTargetData(i,R))});let l=Tt(),d=G();if(e.documentUpdates.forEach(f=>{e.resolvedLimboDocuments.has(f)&&c.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))}),c.push(Y_(i,a,e.documentUpdates).next(f=>{l=f.Bs,d=f.Ls})),!r.isEqual(B.min())){const f=t.li.getLastRemoteSnapshotVersion(i).next(m=>t.li.setTargetsMetadata(i,i.currentSequenceNumber,r));c.push(f)}return S.waitFor(c).next(()=>a.apply(i)).next(()=>t.localDocuments.getLocalViewOfDocuments(i,l,d)).next(()=>l)}).then(i=>(t.vs=s,i))}function Y_(n,e,t){let r=G(),s=G();return t.forEach(i=>r=r.add(i)),e.getEntries(n,r).next(i=>{let a=Tt();return t.forEach((c,l)=>{const d=i.get(c);l.isFoundDocument()!==d.isFoundDocument()&&(s=s.add(c)),l.isNoDocument()&&l.version.isEqual(B.min())?(e.removeEntry(c,l.readTime),a=a.insert(c,l)):!d.isValidDocument()||l.version.compareTo(d.version)>0||l.version.compareTo(d.version)===0&&d.hasPendingWrites?(e.addEntry(l),a=a.insert(c,l)):V(Co,"Ignoring outdated watch update for ",c,". Current version:",d.version," Watch version:",l.version)}),{Bs:a,Ls:s}})}function J_(n,e){const t=U(n);return t.persistence.runTransaction("Get next mutation batch","readonly",r=>(e===void 0&&(e=oo),t.mutationQueue.getNextMutationBatchAfterBatchId(r,e)))}function X_(n,e){const t=U(n);return t.persistence.runTransaction("Allocate target","readwrite",r=>{let s;return t.li.getTargetData(r,e).next(i=>i?(s=i,S.resolve(s)):t.li.allocateTargetId(r).next(a=>(s=new Ut(e,a,"TargetPurposeListen",r.currentSequenceNumber),t.li.addTargetData(r,s).next(()=>s))))}).then(r=>{const s=t.vs.get(r.targetId);return(s===null||r.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.vs=t.vs.insert(r.targetId,r),t.Fs.set(e,r.targetId)),r})}async function ko(n,e,t){const r=U(n),s=r.vs.get(e),i=t?"readwrite":"readwrite-primary";try{t||await r.persistence.runTransaction("Release target",i,a=>r.persistence.referenceDelegate.removeTarget(a,s))}catch(a){if(!kn(a))throw a;V(Co,`Failed to update sequence numbers for target ${e}: ${a}`)}r.vs=r.vs.remove(e),r.Fs.delete(s.target)}function hl(n,e,t){const r=U(n);let s=B.min(),i=G();return r.persistence.runTransaction("Execute query","readwrite",a=>function(l,d,f){const m=U(l),g=m.Fs.get(f);return g!==void 0?S.resolve(m.vs.get(g)):m.li.getTargetData(d,f)}(r,a,it(e)).next(c=>{if(c)return s=c.lastLimboFreeSnapshotVersion,r.li.getMatchingKeysForTargetId(a,c.targetId).next(l=>{i=l})}).next(()=>r.Cs.getDocumentsMatchingQuery(a,e,t?s:B.min(),t?i:G())).next(c=>(Z_(r,xg(e),c),{documents:c,ks:i})))}function Z_(n,e,t){let r=n.Ms.get(e)||B.min();t.forEach((s,i)=>{i.readTime.compareTo(r)>0&&(r=i.readTime)}),n.Ms.set(e,r)}class dl{constructor(){this.activeTargetIds=$g()}Qs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class ey{constructor(){this.vo=new dl,this.Fo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.vo.Qs(e),this.Fo[e]||"not-current"}updateQueryState(e,t,r){this.Fo[e]=t}removeLocalQueryTarget(e){this.vo.Gs(e)}isLocalQueryTarget(e){return this.vo.activeTargetIds.has(e)}clearQueryState(e){delete this.Fo[e]}getAllActiveQueryTargets(){return this.vo.activeTargetIds}isActiveQueryTarget(e){return this.vo.activeTargetIds.has(e)}start(){return this.vo=new dl,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class ty{Mo(e){}shutdown(){}}const fl="ConnectivityMonitor";class pl{constructor(){this.xo=()=>this.Oo(),this.No=()=>this.Bo(),this.Lo=[],this.ko()}Mo(e){this.Lo.push(e)}shutdown(){window.removeEventListener("online",this.xo),window.removeEventListener("offline",this.No)}ko(){window.addEventListener("online",this.xo),window.addEventListener("offline",this.No)}Oo(){V(fl,"Network connectivity changed: AVAILABLE");for(const e of this.Lo)e(0)}Bo(){V(fl,"Network connectivity changed: UNAVAILABLE");for(const e of this.Lo)e(1)}static v(){return typeof window<"u"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}}let zs=null;function No(){return zs===null?zs=function(){return 268435456+Math.round(2147483648*Math.random())}():zs++,"0x"+zs.toString(16)}const Do="RestConnection",ny={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"};class ry{get Ko(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.qo=t+"://"+e.host,this.Uo=`projects/${r}/databases/${s}`,this.$o=this.databaseId.database===vs?`project_id=${r}`:`project_id=${r}&database_id=${s}`}Wo(e,t,r,s,i){const a=No(),c=this.Qo(e,t.toUriEncodedString());V(Do,`Sending RPC '${e}' ${a}:`,c,r);const l={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.$o};this.Go(l,s,i);const{host:d}=new URL(c),f=tt(d);return this.zo(e,c,l,r,f).then(m=>(V(Do,`Received RPC '${e}' ${a}: `,m),m),m=>{throw Pn(Do,`RPC '${e}' ${a} failed with error: `,m,"url: ",c,"request:",r),m})}jo(e,t,r,s,i,a){return this.Wo(e,t,r,s,i)}Go(e,t,r){e["X-Goog-Api-Client"]=function(){return"gl-js/ fire/"+Rn}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((s,i)=>e[i]=s),r&&r.headers.forEach((s,i)=>e[i]=s)}Qo(e,t){const r=ny[e];let s=`${this.qo}/v1/${t}:${r}`;return this.databaseInfo.apiKey&&(s=`${s}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),s}terminate(){}}class sy{constructor(e){this.Ho=e.Ho,this.Jo=e.Jo}Zo(e){this.Xo=e}Yo(e){this.e_=e}t_(e){this.n_=e}onMessage(e){this.r_=e}close(){this.Jo()}send(e){this.Ho(e)}i_(){this.Xo()}s_(){this.e_()}o_(e){this.n_(e)}__(e){this.r_(e)}}const Pe="WebChannelConnection",kr=(n,e,t)=>{n.listen(e,r=>{try{t(r)}catch(s){setTimeout(()=>{throw s},0)}})};class Un extends ry{constructor(e){super(e),this.a_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static u_(){if(!Un.c_){const e=Fc();kr(e,Uc.STAT_EVENT,t=>{t.stat===to.PROXY?V(Pe,"STAT_EVENT: detected buffering proxy"):t.stat===to.NOPROXY&&V(Pe,"STAT_EVENT: detected no buffering proxy")}),Un.c_=!0}}zo(e,t,r,s,i){const a=No();return new Promise((c,l)=>{const d=new Mc;d.setWithCredentials(!0),d.listenOnce(xc.COMPLETE,()=>{try{switch(d.getLastErrorCode()){case ms.NO_ERROR:const m=d.getResponseJson();V(Pe,`XHR for RPC '${e}' ${a} received:`,JSON.stringify(m)),c(m);break;case ms.TIMEOUT:V(Pe,`RPC '${e}' ${a} timed out`),l(new D(P.DEADLINE_EXCEEDED,"Request time out"));break;case ms.HTTP_ERROR:const g=d.getStatus();if(V(Pe,`RPC '${e}' ${a} failed with status:`,g,"response text:",d.getResponseText()),g>0){let R=d.getResponseJson();Array.isArray(R)&&(R=R[0]);const C=R?.error;if(C&&C.status&&C.message){const N=function(F){const $=F.toLowerCase().replace(/_/g,"-");return Object.values(P).indexOf($)>=0?$:P.UNKNOWN}(C.status);l(new D(N,C.message))}else l(new D(P.UNKNOWN,"Server responded with status "+d.getStatus()))}else l(new D(P.UNAVAILABLE,"Connection failed."));break;default:x(9055,{l_:e,streamId:a,h_:d.getLastErrorCode(),P_:d.getLastError()})}}finally{V(Pe,`RPC '${e}' ${a} completed.`)}});const f=JSON.stringify(s);V(Pe,`RPC '${e}' ${a} sending request:`,s),d.send(t,"POST",f,r,15)})}T_(e,t,r){const s=No(),i=[this.qo,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=this.createWebChannelTransport(),c={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;l!==void 0&&(c.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(c.useFetchStreams=!0),this.Go(c.initMessageHeaders,t,r),c.encodeInitMessageHeaders=!0;const d=i.join("");V(Pe,`Creating RPC '${e}' stream ${s}: ${d}`,c);const f=a.createWebChannel(d,c);this.I_(f);let m=!1,g=!1;const R=new sy({Ho:C=>{g?V(Pe,`Not sending because RPC '${e}' stream ${s} is closed:`,C):(m||(V(Pe,`Opening RPC '${e}' stream ${s} transport.`),f.open(),m=!0),V(Pe,`RPC '${e}' stream ${s} sending:`,C),f.send(C))},Jo:()=>f.close()});return kr(f,pr.EventType.OPEN,()=>{g||(V(Pe,`RPC '${e}' stream ${s} transport opened.`),R.i_())}),kr(f,pr.EventType.CLOSE,()=>{g||(g=!0,V(Pe,`RPC '${e}' stream ${s} transport closed`),R.o_(),this.E_(f))}),kr(f,pr.EventType.ERROR,C=>{g||(g=!0,Pn(Pe,`RPC '${e}' stream ${s} transport errored. Name:`,C.name,"Message:",C.message),R.o_(new D(P.UNAVAILABLE,"The operation could not be completed")))}),kr(f,pr.EventType.MESSAGE,C=>{if(!g){const N=C.data[0];Y(!!N,16349);const k=N,F=k?.error||k[0]?.error;if(F){V(Pe,`RPC '${e}' stream ${s} received error:`,F);const $=F.status;let j=function(re){const w=he[re];if(w!==void 0)return qu(w)}($),J=F.message;j===void 0&&(j=P.INTERNAL,J="Unknown error status: "+$+" with message "+F.message),g=!0,R.o_(new D(j,J)),f.close()}else V(Pe,`RPC '${e}' stream ${s} received:`,N),R.__(N)}}),Un.u_(),setTimeout(()=>{R.s_()},0),R}terminate(){this.a_.forEach(e=>e.close()),this.a_=[]}I_(e){this.a_.push(e)}E_(e){this.a_=this.a_.filter(t=>t===e)}Go(e,t,r){super.Go(e,t,r),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return Bc()}}function iy(n){return new Un(n)}function Oo(){return typeof document<"u"?document:null}function Hs(n){return new u_(n,!0)}Un.c_=!1;class ml{constructor(e,t,r=1e3,s=1.5,i=6e4){this.Ci=e,this.timerId=t,this.R_=r,this.A_=s,this.V_=i,this.d_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.d_=0}g_(){this.d_=this.V_}p_(e){this.cancel();const t=Math.floor(this.d_+this.y_()),r=Math.max(0,Date.now()-this.f_),s=Math.max(0,t-r);s>0&&V("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.d_} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.m_=this.Ci.enqueueAfterDelay(this.timerId,s,()=>(this.f_=Date.now(),e())),this.d_*=this.A_,this.d_<this.R_&&(this.d_=this.R_),this.d_>this.V_&&(this.d_=this.V_)}w_(){this.m_!==null&&(this.m_.skipDelay(),this.m_=null)}cancel(){this.m_!==null&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.d_}}const gl="PersistentStream";class _l{constructor(e,t,r,s,i,a,c,l){this.Ci=e,this.b_=r,this.S_=s,this.connection=i,this.authCredentialsProvider=a,this.appCheckCredentialsProvider=c,this.listener=l,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new ml(e,t)}x_(){return this.state===1||this.state===5||this.O_()}O_(){return this.state===2||this.state===3}start(){this.F_=0,this.state!==4?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&this.C_===null&&(this.C_=this.Ci.enqueueAfterDelay(this.b_,6e4,()=>this.k_()))}K_(e){this.q_(),this.stream.send(e)}async k_(){if(this.O_())return this.close(0)}q_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.q_(),this.U_(),this.M_.cancel(),this.D_++,e!==4?this.M_.reset():t&&t.code===P.RESOURCE_EXHAUSTED?(Et(t.toString()),Et("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):t&&t.code===P.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.W_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.t_(t)}W_(){}auth(){this.state=1;const e=this.Q_(this.D_),t=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([r,s])=>{this.D_===t&&this.G_(r,s)},r=>{e(()=>{const s=new D(P.UNKNOWN,"Fetching auth token failed: "+r.message);return this.z_(s)})})}G_(e,t){const r=this.Q_(this.D_);this.stream=this.j_(e,t),this.stream.Zo(()=>{r(()=>this.listener.Zo())}),this.stream.Yo(()=>{r(()=>(this.state=2,this.v_=this.Ci.enqueueAfterDelay(this.S_,1e4,()=>(this.O_()&&(this.state=3),Promise.resolve())),this.listener.Yo()))}),this.stream.t_(s=>{r(()=>this.z_(s))}),this.stream.onMessage(s=>{r(()=>++this.F_==1?this.H_(s):this.onNext(s))})}N_(){this.state=5,this.M_.p_(async()=>{this.state=0,this.start()})}z_(e){return V(gl,`close with error: ${e}`),this.stream=null,this.close(4,e)}Q_(e){return t=>{this.Ci.enqueueAndForget(()=>this.D_===e?t():(V(gl,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class oy extends _l{constructor(e,t,r,s,i,a){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,s,a),this.serializer=i}j_(e,t){return this.connection.T_("Listen",e,t)}H_(e){return this.onNext(e)}onNext(e){this.M_.reset();const t=d_(this.serializer,e),r=function(i){if(!("targetChange"in i))return B.min();const a=i.targetChange;return a.targetIds&&a.targetIds.length?B.min():a.readTime?ot(a.readTime):B.min()}(e);return this.listener.J_(t,r)}Z_(e){const t={};t.database=Ro(this.serializer),t.addTarget=function(i,a){let c;const l=a.target;if(c=po(l)?{documents:m_(i,l)}:{query:Zu(i,l).ft},c.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){c.resumeToken=Ku(i,a.resumeToken);const d=To(i,a.expectedCount);d!==null&&(c.expectedCount=d)}else if(a.snapshotVersion.compareTo(B.min())>0){c.readTime=js(i,a.snapshotVersion.toTimestamp());const d=To(i,a.expectedCount);d!==null&&(c.expectedCount=d)}return c}(this.serializer,e);const r=y_(this.serializer,e);r&&(t.labels=r),this.K_(t)}X_(e){const t={};t.database=Ro(this.serializer),t.removeTarget=e,this.K_(t)}}class ay extends _l{constructor(e,t,r,s,i,a){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,s,a),this.serializer=i}get Y_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}W_(){this.Y_&&this.ea([])}j_(e,t){return this.connection.T_("Write",e,t)}H_(e){return Y(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,Y(!e.writeResults||e.writeResults.length===0,55816),this.listener.ta()}onNext(e){Y(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.M_.reset();const t=p_(e.writeResults,e.commitTime),r=ot(e.commitTime);return this.listener.na(r,t)}ra(){const e={};e.database=Ro(this.serializer),this.K_(e)}ea(e){const t={streamToken:this.lastStreamToken,writes:e.map(r=>f_(this.serializer,r))};this.K_(t)}}class cy{}class uy extends cy{constructor(e,t,r,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=s,this.ia=!1}sa(){if(this.ia)throw new D(P.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,r,s){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,a])=>this.connection.Wo(e,Io(t,r),s,i,a)).catch(i=>{throw i.name==="FirebaseError"?(i.code===P.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new D(P.UNKNOWN,i.toString())})}jo(e,t,r,s,i){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([a,c])=>this.connection.jo(e,Io(t,r),s,a,c,i)).catch(a=>{throw a.name==="FirebaseError"?(a.code===P.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),a):new D(P.UNKNOWN,a.toString())})}terminate(){this.ia=!0,this.connection.terminate()}}function ly(n,e,t,r){return new uy(n,e,t,r)}class hy{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){this.oa===0&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve())))}ha(e){this.state==="Online"?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ca("Offline")))}set(e){this.Pa(),this.oa=0,e==="Online"&&(this.aa=!1),this.ca(e)}ca(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}la(e){const t=`Could not reach Cloud Firestore backend. ${e}
32
- This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.aa?(Et(t),this.aa=!1):V("OnlineStateTracker",t)}Pa(){this._a!==null&&(this._a.cancel(),this._a=null)}}const cn="RemoteStore";class dy{constructor(e,t,r,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.Ta=[],this.Ia=new Map,this.Ea=new Set,this.Ra=[],this.Aa=i,this.Aa.Mo(a=>{r.enqueueAndForget(async()=>{un(this)&&(V(cn,"Restarting streams for network reachability change."),await async function(l){const d=U(l);d.Ea.add(4),await Nr(d),d.Va.set("Unknown"),d.Ea.delete(4),await Ws(d)}(this))})}),this.Va=new hy(r,s)}}async function Ws(n){if(un(n))for(const e of n.Ra)await e(!0)}async function Nr(n){for(const e of n.Ra)await e(!1)}function yl(n,e){const t=U(n);t.Ia.has(e.targetId)||(t.Ia.set(e.targetId,e),xo(t)?Mo(t):Fn(t).O_()&&Lo(t,e))}function Vo(n,e){const t=U(n),r=Fn(t);t.Ia.delete(e),r.O_()&&El(t,e),t.Ia.size===0&&(r.O_()?r.L_():un(t)&&t.Va.set("Unknown"))}function Lo(n,e){if(n.da.$e(e.targetId),e.resumeToken.approximateByteSize()>0||e.snapshotVersion.compareTo(B.min())>0){const t=n.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;e=e.withExpectedCount(t)}Fn(n).Z_(e)}function El(n,e){n.da.$e(e),Fn(n).X_(e)}function Mo(n){n.da=new i_({getRemoteKeysForTarget:e=>n.remoteSyncer.getRemoteKeysForTarget(e),At:e=>n.Ia.get(e)||null,ht:()=>n.datastore.serializer.databaseId}),Fn(n).start(),n.Va.ua()}function xo(n){return un(n)&&!Fn(n).x_()&&n.Ia.size>0}function un(n){return U(n).Ea.size===0}function Tl(n){n.da=void 0}async function fy(n){n.Va.set("Online")}async function py(n){n.Ia.forEach((e,t)=>{Lo(n,e)})}async function my(n,e){Tl(n),xo(n)?(n.Va.ha(e),Mo(n)):n.Va.set("Unknown")}async function gy(n,e,t){if(n.Va.set("Online"),e instanceof Hu&&e.state===2&&e.cause)try{await async function(s,i){const a=i.cause;for(const c of i.targetIds)s.Ia.has(c)&&(await s.remoteSyncer.rejectListen(c,a),s.Ia.delete(c),s.da.removeTarget(c))}(n,e)}catch(r){V(cn,"Failed to remove targets %s: %s ",e.targetIds.join(","),r),await Gs(n,r)}else if(e instanceof Bs?n.da.Xe(e):e instanceof zu?n.da.st(e):n.da.tt(e),!t.isEqual(B.min()))try{const r=await ll(n.localStore);t.compareTo(r)>=0&&await function(i,a){const c=i.da.Tt(a);return c.targetChanges.forEach((l,d)=>{if(l.resumeToken.approximateByteSize()>0){const f=i.Ia.get(d);f&&i.Ia.set(d,f.withResumeToken(l.resumeToken,a))}}),c.targetMismatches.forEach((l,d)=>{const f=i.Ia.get(l);if(!f)return;i.Ia.set(l,f.withResumeToken(we.EMPTY_BYTE_STRING,f.snapshotVersion)),El(i,l);const m=new Ut(f.target,l,d,f.sequenceNumber);Lo(i,m)}),i.remoteSyncer.applyRemoteEvent(c)}(n,t)}catch(r){V(cn,"Failed to raise snapshot:",r),await Gs(n,r)}}async function Gs(n,e,t){if(!kn(e))throw e;n.Ea.add(1),await Nr(n),n.Va.set("Offline"),t||(t=()=>ll(n.localStore)),n.asyncQueue.enqueueRetryable(async()=>{V(cn,"Retrying IndexedDB access"),await t(),n.Ea.delete(1),await Ws(n)})}function wl(n,e){return e().catch(t=>Gs(n,t,e))}async function Ks(n){const e=U(n),t=Ft(e);let r=e.Ta.length>0?e.Ta[e.Ta.length-1].batchId:oo;for(;_y(e);)try{const s=await J_(e.localStore,r);if(s===null){e.Ta.length===0&&t.L_();break}r=s.batchId,yy(e,s)}catch(s){await Gs(e,s)}Il(e)&&vl(e)}function _y(n){return un(n)&&n.Ta.length<10}function yy(n,e){n.Ta.push(e);const t=Ft(n);t.O_()&&t.Y_&&t.ea(e.mutations)}function Il(n){return un(n)&&!Ft(n).x_()&&n.Ta.length>0}function vl(n){Ft(n).start()}async function Ey(n){Ft(n).ra()}async function Ty(n){const e=Ft(n);for(const t of n.Ta)e.ea(t.mutations)}async function wy(n,e,t){const r=n.Ta.shift(),s=yo.from(r,e,t);await wl(n,()=>n.remoteSyncer.applySuccessfulWrite(s)),await Ks(n)}async function Iy(n,e){e&&Ft(n).Y_&&await async function(r,s){if(function(a){return n_(a)&&a!==P.ABORTED}(s.code)){const i=r.Ta.shift();Ft(r).B_(),await wl(r,()=>r.remoteSyncer.rejectFailedWrite(i.batchId,s)),await Ks(r)}}(n,e),Il(n)&&vl(n)}async function Al(n,e){const t=U(n);t.asyncQueue.verifyOperationInProgress(),V(cn,"RemoteStore received new credentials");const r=un(t);t.Ea.add(3),await Nr(t),r&&t.Va.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.Ea.delete(3),await Ws(t)}async function vy(n,e){const t=U(n);e?(t.Ea.delete(2),await Ws(t)):e||(t.Ea.add(2),await Nr(t),t.Va.set("Unknown"))}function Fn(n){return n.ma||(n.ma=function(t,r,s){const i=U(t);return i.sa(),new oy(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(n.datastore,n.asyncQueue,{Zo:fy.bind(null,n),Yo:py.bind(null,n),t_:my.bind(null,n),J_:gy.bind(null,n)}),n.Ra.push(async e=>{e?(n.ma.B_(),xo(n)?Mo(n):n.Va.set("Unknown")):(await n.ma.stop(),Tl(n))})),n.ma}function Ft(n){return n.fa||(n.fa=function(t,r,s){const i=U(t);return i.sa(),new ay(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(n.datastore,n.asyncQueue,{Zo:()=>Promise.resolve(),Yo:Ey.bind(null,n),t_:Iy.bind(null,n),ta:Ty.bind(null,n),na:wy.bind(null,n)}),n.Ra.push(async e=>{e?(n.fa.B_(),await Ks(n)):(await n.fa.stop(),n.Ta.length>0&&(V(cn,`Stopping write stream with ${n.Ta.length} pending writes`),n.Ta=[]))})),n.fa}class Uo{constructor(e,t,r,s,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=s,this.removalCallback=i,this.deferred=new nt,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(a=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,r,s,i){const a=Date.now()+r,c=new Uo(e,t,a,s,i);return c.start(r),c}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new D(P.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Fo(n,e){if(Et("AsyncQueue",`${e}: ${n}`),kn(n))return new D(P.UNAVAILABLE,`${e}: ${n}`);throw n}class Bn{static emptySet(e){return new Bn(e.comparator)}constructor(e){this.comparator=e?(t,r)=>e(t,r)||L.comparator(t.key,r.key):(t,r)=>L.comparator(t.key,r.key),this.keyedMap=Ir(),this.sortedSet=new se(this.comparator)}has(e){return this.keyedMap.get(e)!=null}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,r)=>(e(t),!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){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Bn)||this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();for(;t.hasNext();){const s=t.getNext().key,i=r.getNext().key;if(!s.isEqual(i))return!1}return!0}toString(){const e=[];return this.forEach(t=>{e.push(t.toString())}),e.length===0?"DocumentSet ()":`DocumentSet (
31
+ Total Duration: ${d-f}ms`),C.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:m})))}}function N_(n,e){return new k_(n,e)}class D_{constructor(){this.changes=new an(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,be.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const r=this.changes.get(t);return r!==void 0?C.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class O_{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class V_{constructor(e,t,r,s){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=r,this.indexManager=s}getDocument(e,t){let r=null;return this.documentOverlayCache.getOverlay(e,t).next(s=>(r=s,this.remoteDocumentCache.getEntry(e,t))).next(s=>(r!==null&&br(r.mutation,s,Fe.empty(),ee.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(r=>this.getLocalViewOfDocuments(e,r,G()).next(()=>r))}getLocalViewOfDocuments(e,t,r=G()){const s=cn();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,r).next(i=>{let a=Ir();return i.forEach((c,l)=>{a=a.insert(c,l.overlayedDocument)}),a}))}getOverlayedDocuments(e,t){const r=cn();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,G()))}populateOverlays(e,t,r){const s=[];return r.forEach(i=>{t.has(i)||s.push(i)}),this.documentOverlayCache.getOverlays(e,s).next(i=>{i.forEach((a,c)=>{t.set(a,c)})})}computeViews(e,t,r,s){let i=Tt();const a=vr(),c=function(){return vr()}();return t.forEach((l,d)=>{const f=r.get(d.key);s.has(d.key)&&(f===void 0||f.mutation instanceof Mt)?i=i.insert(d.key,d):f!==void 0?(a.set(d.key,f.mutation.getFieldMask()),br(f.mutation,d,f.mutation.getFieldMask(),ee.now())):a.set(d.key,Fe.empty())}),this.recalculateAndSaveOverlays(e,i).next(l=>(l.forEach((d,f)=>a.set(d,f)),t.forEach((d,f)=>c.set(d,new O_(f,a.get(d)??null))),c))}recalculateAndSaveOverlays(e,t){const r=vr();let s=new se((a,c)=>a-c),i=G();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(a=>{for(const c of a)c.keys().forEach(l=>{const d=t.get(l);if(d===null)return;let f=r.get(l)||Fe.empty();f=c.applyToLocalView(d,f),r.set(l,f);const m=(s.get(c.batchId)||G()).add(l);s=s.insert(c.batchId,m)})}).next(()=>{const a=[],c=s.getReverseIterator();for(;c.hasNext();){const l=c.getNext(),d=l.key,f=l.value,m=Su();f.forEach(_=>{if(!i.has(_)){const R=Mu(t.get(_),r.get(_));R!==null&&m.set(_,R),i=i.add(_)}}),a.push(this.documentOverlayCache.saveOverlays(e,d,m))}return C.waitFor(a)}).next(()=>r)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(r=>this.recalculateAndSaveOverlays(e,r))}getDocumentsMatchingQuery(e,t,r,s){return Og(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):mo(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,s):this.getDocumentsMatchingCollectionQuery(e,t,r,s)}getNextDocuments(e,t,r,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,r,s).next(i=>{const a=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,r.largestBatchId,s-i.size):C.resolve(cn());let c=gr,l=i;return a.next(d=>C.forEach(d,(f,m)=>(c<m.largestBatchId&&(c=m.largestBatchId),i.get(f)?C.resolve():this.remoteDocumentCache.getEntry(e,f).next(_=>{l=l.insert(f,_)}))).next(()=>this.populateOverlays(e,d,i)).next(()=>this.computeViews(e,l,d,G())).next(f=>({batchId:c,changes:Cu(f)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new L(t)).next(r=>{let s=Ir();return r.isFoundDocument()&&(s=s.insert(r.key,r)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,r,s){const i=t.collectionGroup;let a=Ir();return this.indexManager.getCollectionParents(e,i).next(c=>C.forEach(c,l=>{const d=function(m,_){return new on(_,null,m.explicitOrderBy.slice(),m.filters.slice(),m.limit,m.limitType,m.startAt,m.endAt)}(t,l.child(i));return this.getDocumentsMatchingCollectionQuery(e,d,r,s).next(f=>{f.forEach((m,_)=>{a=a.insert(m,_)})})}).next(()=>a))}getDocumentsMatchingCollectionQuery(e,t,r,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,r.largestBatchId).next(a=>(i=a,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,i,s))).next(a=>{i.forEach((l,d)=>{const f=d.getKey();a.get(f)===null&&(a=a.insert(f,be.newInvalidDocument(f)))});let c=Ir();return a.forEach((l,d)=>{const f=i.get(l);f!==void 0&&br(f.mutation,d,Fe.empty(),ee.now()),Ds(t,d)&&(c=c.insert(l,d))}),c})}}class L_{constructor(e){this.serializer=e,this.Nr=new Map,this.Br=new Map}getBundleMetadata(e,t){return C.resolve(this.Nr.get(t))}saveBundleMetadata(e,t){return this.Nr.set(t.id,function(s){return{id:s.id,version:s.version,createTime:ot(s.createTime)}}(t)),C.resolve()}getNamedQuery(e,t){return C.resolve(this.Br.get(t))}saveNamedQuery(e,t){return this.Br.set(t.name,function(s){return{name:s.name,query:A_(s.bundledQuery),readTime:ot(s.readTime)}}(t)),C.resolve()}}class M_{constructor(){this.overlays=new se(L.comparator),this.Lr=new Map}getOverlay(e,t){return C.resolve(this.overlays.get(t))}getOverlays(e,t){const r=cn();return C.forEach(t,s=>this.getOverlay(e,s).next(i=>{i!==null&&r.set(s,i)})).next(()=>r)}saveOverlays(e,t,r){return r.forEach((s,i)=>{this.bt(e,t,i)}),C.resolve()}removeOverlaysForBatchId(e,t,r){const s=this.Lr.get(r);return s!==void 0&&(s.forEach(i=>this.overlays=this.overlays.remove(i)),this.Lr.delete(r)),C.resolve()}getOverlaysForCollection(e,t,r){const s=cn(),i=t.length+1,a=new L(t.child("")),c=this.overlays.getIteratorFrom(a);for(;c.hasNext();){const l=c.getNext().value,d=l.getKey();if(!t.isPrefixOf(d.path))break;d.path.length===i&&l.largestBatchId>r&&s.set(l.getKey(),l)}return C.resolve(s)}getOverlaysForCollectionGroup(e,t,r,s){let i=new se((d,f)=>d-f);const a=this.overlays.getIterator();for(;a.hasNext();){const d=a.getNext().value;if(d.getKey().getCollectionGroup()===t&&d.largestBatchId>r){let f=i.get(d.largestBatchId);f===null&&(f=cn(),i=i.insert(d.largestBatchId,f)),f.set(d.getKey(),d)}}const c=cn(),l=i.getIterator();for(;l.hasNext()&&(l.getNext().value.forEach((d,f)=>c.set(d,f)),!(c.size()>=s)););return C.resolve(c)}bt(e,t,r){const s=this.overlays.get(r.key);if(s!==null){const a=this.Lr.get(s.largestBatchId).delete(r.key);this.Lr.set(s.largestBatchId,a)}this.overlays=this.overlays.insert(r.key,new Zg(t,r));let i=this.Lr.get(t);i===void 0&&(i=G(),this.Lr.set(t,i)),this.Lr.set(t,i.add(r.key))}}class x_{constructor(){this.sessionToken=we.EMPTY_BYTE_STRING}getSessionToken(e){return C.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,C.resolve()}}class bo{constructor(){this.kr=new fe(ge.Kr),this.qr=new fe(ge.Ur)}isEmpty(){return this.kr.isEmpty()}addReference(e,t){const r=new ge(e,t);this.kr=this.kr.add(r),this.qr=this.qr.add(r)}$r(e,t){e.forEach(r=>this.addReference(r,t))}removeReference(e,t){this.Wr(new ge(e,t))}Qr(e,t){e.forEach(r=>this.removeReference(r,t))}Gr(e){const t=new L(new X([])),r=new ge(t,e),s=new ge(t,e+1),i=[];return this.qr.forEachInRange([r,s],a=>{this.Wr(a),i.push(a.key)}),i}zr(){this.kr.forEach(e=>this.Wr(e))}Wr(e){this.kr=this.kr.delete(e),this.qr=this.qr.delete(e)}jr(e){const t=new L(new X([])),r=new ge(t,e),s=new ge(t,e+1);let i=G();return this.qr.forEachInRange([r,s],a=>{i=i.add(a.key)}),i}containsKey(e){const t=new ge(e,0),r=this.kr.firstAfterOrEqual(t);return r!==null&&e.isEqual(r.key)}}class ge{constructor(e,t){this.key=e,this.Hr=t}static Kr(e,t){return L.comparator(e.key,t.key)||W(e.Hr,t.Hr)}static Ur(e,t){return W(e.Hr,t.Hr)||L.comparator(e.key,t.key)}}class U_{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Yn=1,this.Jr=new fe(ge.Kr)}checkEmpty(e){return C.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,r,s){const i=this.Yn;this.Yn++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const a=new Xg(i,t,r,s);this.mutationQueue.push(a);for(const c of s)this.Jr=this.Jr.add(new ge(c.key,i)),this.indexManager.addToCollectionParentIndex(e,c.key.path.popLast());return C.resolve(a)}lookupMutationBatch(e,t){return C.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){const r=t+1,s=this.Xr(r),i=s<0?0:s;return C.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return C.resolve(this.mutationQueue.length===0?oo:this.Yn-1)}getAllMutationBatches(e){return C.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const r=new ge(t,0),s=new ge(t,Number.POSITIVE_INFINITY),i=[];return this.Jr.forEachInRange([r,s],a=>{const c=this.Zr(a.Hr);i.push(c)}),C.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new fe(W);return t.forEach(s=>{const i=new ge(s,0),a=new ge(s,Number.POSITIVE_INFINITY);this.Jr.forEachInRange([i,a],c=>{r=r.add(c.Hr)})}),C.resolve(this.Yr(r))}getAllMutationBatchesAffectingQuery(e,t){const r=t.path,s=r.length+1;let i=r;L.isDocumentKey(i)||(i=i.child(""));const a=new ge(new L(i),0);let c=new fe(W);return this.Jr.forEachWhile(l=>{const d=l.key.path;return!!r.isPrefixOf(d)&&(d.length===s&&(c=c.add(l.Hr)),!0)},a),C.resolve(this.Yr(c))}Yr(e){const t=[];return e.forEach(r=>{const s=this.Zr(r);s!==null&&t.push(s)}),t}removeMutationBatch(e,t){J(this.ei(t.batchId,"removed")===0,55003),this.mutationQueue.shift();let r=this.Jr;return C.forEach(t.mutations,s=>{const i=new ge(s.key,t.batchId);return r=r.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)}).next(()=>{this.Jr=r})}nr(e){}containsKey(e,t){const r=new ge(t,0),s=this.Jr.firstAfterOrEqual(r);return C.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,C.resolve()}ei(e,t){return this.Xr(e)}Xr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Zr(e){const t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class F_{constructor(e){this.ti=e,this.docs=function(){return new se(L.comparator)}(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const r=t.key,s=this.docs.get(r),i=s?s.size:0,a=this.ti(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const r=this.docs.get(t);return C.resolve(r?r.document.mutableCopy():be.newInvalidDocument(t))}getEntries(e,t){let r=Tt();return t.forEach(s=>{const i=this.docs.get(s);r=r.insert(s,i?i.document.mutableCopy():be.newInvalidDocument(s))}),C.resolve(r)}getDocumentsMatchingQuery(e,t,r,s){let i=Tt();const a=t.path,c=new L(a.child("__id-9223372036854775808__")),l=this.docs.getIteratorFrom(c);for(;l.hasNext();){const{key:d,value:{document:f}}=l.getNext();if(!a.isPrefixOf(d.path))break;d.path.length>a.length+1||cg(ag(f),r)<=0||(s.has(f.key)||Ds(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return C.resolve(i)}getAllFromCollectionGroup(e,t,r,s){x(9500)}ni(e,t){return C.forEach(this.docs,r=>t(r))}newChangeBuffer(e){return new B_(this)}getSize(e){return C.resolve(this.size)}}class B_ extends D_{constructor(e){super(),this.Mr=e}applyChanges(e){const t=[];return this.changes.forEach((r,s)=>{s.isValidDocument()?t.push(this.Mr.addEntry(e,s)):this.Mr.removeEntry(r)}),C.waitFor(t)}getFromCache(e,t){return this.Mr.getEntry(e,t)}getAllFromCache(e,t){return this.Mr.getEntries(e,t)}}class q_{constructor(e){this.persistence=e,this.ri=new an(t=>ho(t),fo),this.lastRemoteSnapshotVersion=B.min(),this.highestTargetId=0,this.ii=0,this.si=new bo,this.targetCount=0,this.oi=xn._r()}forEachTarget(e,t){return this.ri.forEach((r,s)=>t(s)),C.resolve()}getLastRemoteSnapshotVersion(e){return C.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return C.resolve(this.ii)}allocateTargetId(e){return this.highestTargetId=this.oi.next(),C.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.ii&&(this.ii=t),C.resolve()}lr(e){this.ri.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.oi=new xn(t),this.highestTargetId=t),e.sequenceNumber>this.ii&&(this.ii=e.sequenceNumber)}addTargetData(e,t){return this.lr(t),this.targetCount+=1,C.resolve()}updateTargetData(e,t){return this.lr(t),C.resolve()}removeTargetData(e,t){return this.ri.delete(t.target),this.si.Gr(t.targetId),this.targetCount-=1,C.resolve()}removeTargets(e,t,r){let s=0;const i=[];return this.ri.forEach((a,c)=>{c.sequenceNumber<=t&&r.get(c.targetId)===null&&(this.ri.delete(a),i.push(this.removeMatchingKeysForTargetId(e,c.targetId)),s++)}),C.waitFor(i).next(()=>s)}getTargetCount(e){return C.resolve(this.targetCount)}getTargetData(e,t){const r=this.ri.get(t)||null;return C.resolve(r)}addMatchingKeys(e,t,r){return this.si.$r(t,r),C.resolve()}removeMatchingKeys(e,t,r){this.si.Qr(t,r);const s=this.persistence.referenceDelegate,i=[];return s&&t.forEach(a=>{i.push(s.markPotentiallyOrphaned(e,a))}),C.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.si.Gr(t),C.resolve()}getMatchingKeysForTargetId(e,t){const r=this.si.jr(t);return C.resolve(r)}containsKey(e,t){return C.resolve(this.si.containsKey(t))}}class cl{constructor(e,t){this._i={},this.overlays={},this.ai=new _s(0),this.ui=!1,this.ui=!0,this.ci=new x_,this.referenceDelegate=e(this),this.li=new q_(this),this.indexManager=new R_,this.remoteDocumentCache=function(s){return new F_(s)}(r=>this.referenceDelegate.hi(r)),this.serializer=new v_(t),this.Pi=new L_(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ui=!1,Promise.resolve()}get started(){return this.ui}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new M_,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this._i[e.toKey()];return r||(r=new U_(t,this.referenceDelegate),this._i[e.toKey()]=r),r}getGlobalsCache(){return this.ci}getTargetCache(){return this.li}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Pi}runTransaction(e,t,r){V("MemoryPersistence","Starting transaction:",e);const s=new j_(this.ai.next());return this.referenceDelegate.Ti(),r(s).next(i=>this.referenceDelegate.Ii(s).next(()=>i)).toPromise().then(i=>(s.raiseOnCommittedEvent(),i))}Ei(e,t){return C.or(Object.values(this._i).map(r=>()=>r.containsKey(e,t)))}}class j_ extends lg{constructor(e){super(),this.currentSequenceNumber=e}}class Po{constructor(e){this.persistence=e,this.Ri=new bo,this.Ai=null}static Vi(e){return new Po(e)}get di(){if(this.Ai)return this.Ai;throw x(60996)}addReference(e,t,r){return this.Ri.addReference(r,t),this.di.delete(r.toString()),C.resolve()}removeReference(e,t,r){return this.Ri.removeReference(r,t),this.di.add(r.toString()),C.resolve()}markPotentiallyOrphaned(e,t){return this.di.add(t.toString()),C.resolve()}removeTarget(e,t){this.Ri.Gr(t.targetId).forEach(s=>this.di.add(s.toString()));const r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(s=>{s.forEach(i=>this.di.add(i.toString()))}).next(()=>r.removeTargetData(e,t))}Ti(){this.Ai=new Set}Ii(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return C.forEach(this.di,r=>{const s=L.fromPath(r);return this.mi(e,s).next(i=>{i||t.removeEntry(s,B.min())})}).next(()=>(this.Ai=null,t.apply(e)))}updateLimboDocument(e,t){return this.mi(e,t).next(r=>{r?this.di.delete(t.toString()):this.di.add(t.toString())})}hi(e){return 0}mi(e,t){return C.or([()=>C.resolve(this.Ri.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}}class $s{constructor(e,t){this.persistence=e,this.fi=new an(r=>fg(r.path),(r,s)=>r.isEqual(s)),this.garbageCollector=N_(this,t)}static Vi(e,t){return new $s(e,t)}Ti(){}Ii(e){return C.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}dr(e){const t=this.pr(e);return this.persistence.getTargetCache().getTargetCount(e).next(r=>t.next(s=>r+s))}pr(e){let t=0;return this.mr(e,r=>{t++}).next(()=>t)}mr(e,t){return C.forEach(this.fi,(r,s)=>this.wr(e,r,s).next(i=>i?C.resolve():t(s)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,t){let r=0;const s=this.persistence.getRemoteDocumentCache(),i=s.newChangeBuffer();return s.ni(e,a=>this.wr(e,a,t).next(c=>{c||(r++,i.removeEntry(a,B.min()))})).next(()=>i.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.fi.set(t,e.currentSequenceNumber),C.resolve()}removeTarget(e,t){const r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),C.resolve()}removeReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),C.resolve()}updateLimboDocument(e,t){return this.fi.set(t,e.currentSequenceNumber),C.resolve()}hi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=bs(e.data.value)),t}wr(e,t,r){return C.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{const s=this.fi.get(t);return C.resolve(s!==void 0&&s>r)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class Co{constructor(e,t,r,s){this.targetId=e,this.fromCache=t,this.Ts=r,this.Is=s}static Es(e,t){let r=G(),s=G();for(const i of t.docChanges)switch(i.type){case 0:r=r.add(i.doc.key);break;case 1:s=s.add(i.doc.key)}return new Co(e,t.fromCache,r,s)}}class $_{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class z_{constructor(){this.Rs=!1,this.As=!1,this.Vs=100,this.ds=function(){return Sp()?8:hg(ve())>0?6:4}()}initialize(e,t){this.fs=e,this.indexManager=t,this.Rs=!0}getDocumentsMatchingQuery(e,t,r,s){const i={result:null};return this.gs(e,t).next(a=>{i.result=a}).next(()=>{if(!i.result)return this.ps(e,t,s,r).next(a=>{i.result=a})}).next(()=>{if(i.result)return;const a=new $_;return this.ys(e,t,a).next(c=>{if(i.result=c,this.As)return this.ws(e,t,a,c.size)})}).next(()=>i.result)}ws(e,t,r,s){return r.documentReadCount<this.Vs?(Pn()<=H.DEBUG&&V("QueryEngine","SDK will not create cache indexes for query:",Ln(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),C.resolve()):(Pn()<=H.DEBUG&&V("QueryEngine","Query:",Ln(t),"scans",r.documentReadCount,"local documents and returns",s,"documents as results."),r.documentReadCount>this.ds*s?(Pn()<=H.DEBUG&&V("QueryEngine","The SDK decides to create cache indexes for query:",Ln(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,it(t))):C.resolve())}gs(e,t){if(vu(t))return C.resolve(null);let r=it(t);return this.indexManager.getIndexType(e,r).next(s=>s===0?null:(t.limit!==null&&s===1&&(t=ks(t,null,"F"),r=it(t)),this.indexManager.getDocumentsMatchingTarget(e,r).next(i=>{const a=G(...i);return this.fs.getDocuments(e,a).next(c=>this.indexManager.getMinOffset(e,r).next(l=>{const d=this.bs(t,c);return this.Ss(t,d,a,l.readTime)?this.gs(e,ks(t,null,"F")):this.Ds(e,d,t,l)}))})))}ps(e,t,r,s){return vu(t)||s.isEqual(B.min())?C.resolve(null):this.fs.getDocuments(e,r).next(i=>{const a=this.bs(t,i);return this.Ss(t,a,r,s)?C.resolve(null):(Pn()<=H.DEBUG&&V("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Ln(t)),this.Ds(e,a,t,og(s,gr)).next(c=>c))})}bs(e,t){let r=new fe(bu(e));return t.forEach((s,i)=>{Ds(e,i)&&(r=r.add(i))}),r}Ss(e,t,r,s){if(e.limit===null)return!1;if(r.size!==t.size)return!0;const i=e.limitType==="F"?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(s)>0)}ys(e,t,r){return Pn()<=H.DEBUG&&V("QueryEngine","Using full collection scan to execute query:",Ln(t)),this.fs.getDocumentsMatchingQuery(e,t,Nt.min(),r)}Ds(e,t,r,s){return this.fs.getDocumentsMatchingQuery(e,r,s).next(i=>(t.forEach(a=>{i=i.insert(a.key,a)}),i))}}const So="LocalStore",H_=3e8;class W_{constructor(e,t,r,s){this.persistence=e,this.Cs=t,this.serializer=s,this.vs=new se(W),this.Fs=new an(i=>ho(i),fo),this.Ms=new Map,this.xs=e.getRemoteDocumentCache(),this.li=e.getTargetCache(),this.Pi=e.getBundleCache(),this.Os(r)}Os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new V_(this.xs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.xs.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.vs))}}function G_(n,e,t,r){return new W_(n,e,t,r)}async function ul(n,e){const t=F(n);return await t.persistence.runTransaction("Handle user change","readonly",r=>{let s;return t.mutationQueue.getAllMutationBatches(r).next(i=>(s=i,t.Os(e),t.mutationQueue.getAllMutationBatches(r))).next(i=>{const a=[],c=[];let l=G();for(const d of s){a.push(d.batchId);for(const f of d.mutations)l=l.add(f.key)}for(const d of i){c.push(d.batchId);for(const f of d.mutations)l=l.add(f.key)}return t.localDocuments.getDocuments(r,l).next(d=>({Ns:d,removedBatchIds:a,addedBatchIds:c}))})})}function K_(n,e){const t=F(n);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",r=>{const s=e.batch.keys(),i=t.xs.newChangeBuffer({trackRemovals:!0});return function(c,l,d,f){const m=d.batch,_=m.keys();let R=C.resolve();return _.forEach(S=>{R=R.next(()=>f.getEntry(l,S)).next(N=>{const k=d.docVersions.get(S);J(k!==null,48541),N.version.compareTo(k)<0&&(m.applyToRemoteDocument(N,d),N.isValidDocument()&&(N.setReadTime(d.commitVersion),f.addEntry(N)))})}),R.next(()=>c.mutationQueue.removeMutationBatch(l,m))}(t,r,e,i).next(()=>i.apply(r)).next(()=>t.mutationQueue.performConsistencyCheck(r)).next(()=>t.documentOverlayCache.removeOverlaysForBatchId(r,s,e.batch.batchId)).next(()=>t.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(r,function(c){let l=G();for(let d=0;d<c.mutationResults.length;++d)c.mutationResults[d].transformResults.length>0&&(l=l.add(c.batch.mutations[d].key));return l}(e))).next(()=>t.localDocuments.getDocuments(r,s))})}function ll(n){const e=F(n);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.li.getLastRemoteSnapshotVersion(t))}function Q_(n,e){const t=F(n),r=e.snapshotVersion;let s=t.vs;return t.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{const a=t.xs.newChangeBuffer({trackRemovals:!0});s=t.vs;const c=[];e.targetChanges.forEach((f,m)=>{const _=s.get(m);if(!_)return;c.push(t.li.removeMatchingKeys(i,f.removedDocuments,m).next(()=>t.li.addMatchingKeys(i,f.addedDocuments,m)));let R=_.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(m)!==null?R=R.withResumeToken(we.EMPTY_BYTE_STRING,B.min()).withLastLimboFreeSnapshotVersion(B.min()):f.resumeToken.approximateByteSize()>0&&(R=R.withResumeToken(f.resumeToken,r)),s=s.insert(m,R),function(N,k,U){return N.resumeToken.approximateByteSize()===0||k.snapshotVersion.toMicroseconds()-N.snapshotVersion.toMicroseconds()>=H_?!0:U.addedDocuments.size+U.modifiedDocuments.size+U.removedDocuments.size>0}(_,R,f)&&c.push(t.li.updateTargetData(i,R))});let l=Tt(),d=G();if(e.documentUpdates.forEach(f=>{e.resolvedLimboDocuments.has(f)&&c.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))}),c.push(Y_(i,a,e.documentUpdates).next(f=>{l=f.Bs,d=f.Ls})),!r.isEqual(B.min())){const f=t.li.getLastRemoteSnapshotVersion(i).next(m=>t.li.setTargetsMetadata(i,i.currentSequenceNumber,r));c.push(f)}return C.waitFor(c).next(()=>a.apply(i)).next(()=>t.localDocuments.getLocalViewOfDocuments(i,l,d)).next(()=>l)}).then(i=>(t.vs=s,i))}function Y_(n,e,t){let r=G(),s=G();return t.forEach(i=>r=r.add(i)),e.getEntries(n,r).next(i=>{let a=Tt();return t.forEach((c,l)=>{const d=i.get(c);l.isFoundDocument()!==d.isFoundDocument()&&(s=s.add(c)),l.isNoDocument()&&l.version.isEqual(B.min())?(e.removeEntry(c,l.readTime),a=a.insert(c,l)):!d.isValidDocument()||l.version.compareTo(d.version)>0||l.version.compareTo(d.version)===0&&d.hasPendingWrites?(e.addEntry(l),a=a.insert(c,l)):V(So,"Ignoring outdated watch update for ",c,". Current version:",d.version," Watch version:",l.version)}),{Bs:a,Ls:s}})}function J_(n,e){const t=F(n);return t.persistence.runTransaction("Get next mutation batch","readonly",r=>(e===void 0&&(e=oo),t.mutationQueue.getNextMutationBatchAfterBatchId(r,e)))}function X_(n,e){const t=F(n);return t.persistence.runTransaction("Allocate target","readwrite",r=>{let s;return t.li.getTargetData(r,e).next(i=>i?(s=i,C.resolve(s)):t.li.allocateTargetId(r).next(a=>(s=new Ut(e,a,"TargetPurposeListen",r.currentSequenceNumber),t.li.addTargetData(r,s).next(()=>s))))}).then(r=>{const s=t.vs.get(r.targetId);return(s===null||r.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.vs=t.vs.insert(r.targetId,r),t.Fs.set(e,r.targetId)),r})}async function ko(n,e,t){const r=F(n),s=r.vs.get(e),i=t?"readwrite":"readwrite-primary";try{t||await r.persistence.runTransaction("Release target",i,a=>r.persistence.referenceDelegate.removeTarget(a,s))}catch(a){if(!kn(a))throw a;V(So,`Failed to update sequence numbers for target ${e}: ${a}`)}r.vs=r.vs.remove(e),r.Fs.delete(s.target)}function hl(n,e,t){const r=F(n);let s=B.min(),i=G();return r.persistence.runTransaction("Execute query","readwrite",a=>function(l,d,f){const m=F(l),_=m.Fs.get(f);return _!==void 0?C.resolve(m.vs.get(_)):m.li.getTargetData(d,f)}(r,a,it(e)).next(c=>{if(c)return s=c.lastLimboFreeSnapshotVersion,r.li.getMatchingKeysForTargetId(a,c.targetId).next(l=>{i=l})}).next(()=>r.Cs.getDocumentsMatchingQuery(a,e,t?s:B.min(),t?i:G())).next(c=>(Z_(r,xg(e),c),{documents:c,ks:i})))}function Z_(n,e,t){let r=n.Ms.get(e)||B.min();t.forEach((s,i)=>{i.readTime.compareTo(r)>0&&(r=i.readTime)}),n.Ms.set(e,r)}class dl{constructor(){this.activeTargetIds=$g()}Qs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class ey{constructor(){this.vo=new dl,this.Fo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.vo.Qs(e),this.Fo[e]||"not-current"}updateQueryState(e,t,r){this.Fo[e]=t}removeLocalQueryTarget(e){this.vo.Gs(e)}isLocalQueryTarget(e){return this.vo.activeTargetIds.has(e)}clearQueryState(e){delete this.Fo[e]}getAllActiveQueryTargets(){return this.vo.activeTargetIds}isActiveQueryTarget(e){return this.vo.activeTargetIds.has(e)}start(){return this.vo=new dl,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class ty{Mo(e){}shutdown(){}}const fl="ConnectivityMonitor";class pl{constructor(){this.xo=()=>this.Oo(),this.No=()=>this.Bo(),this.Lo=[],this.ko()}Mo(e){this.Lo.push(e)}shutdown(){window.removeEventListener("online",this.xo),window.removeEventListener("offline",this.No)}ko(){window.addEventListener("online",this.xo),window.addEventListener("offline",this.No)}Oo(){V(fl,"Network connectivity changed: AVAILABLE");for(const e of this.Lo)e(0)}Bo(){V(fl,"Network connectivity changed: UNAVAILABLE");for(const e of this.Lo)e(1)}static v(){return typeof window<"u"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}}let zs=null;function No(){return zs===null?zs=function(){return 268435456+Math.round(2147483648*Math.random())}():zs++,"0x"+zs.toString(16)}const Do="RestConnection",ny={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"};class ry{get Ko(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.qo=t+"://"+e.host,this.Uo=`projects/${r}/databases/${s}`,this.$o=this.databaseId.database===vs?`project_id=${r}`:`project_id=${r}&database_id=${s}`}Wo(e,t,r,s,i){const a=No(),c=this.Qo(e,t.toUriEncodedString());V(Do,`Sending RPC '${e}' ${a}:`,c,r);const l={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.$o};this.Go(l,s,i);const{host:d}=new URL(c),f=tt(d);return this.zo(e,c,l,r,f).then(m=>(V(Do,`Received RPC '${e}' ${a}: `,m),m),m=>{throw sn(Do,`RPC '${e}' ${a} failed with error: `,m,"url: ",c,"request:",r),m})}jo(e,t,r,s,i,a){return this.Wo(e,t,r,s,i)}Go(e,t,r){e["X-Goog-Api-Client"]=function(){return"gl-js/ fire/"+bn}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((s,i)=>e[i]=s),r&&r.headers.forEach((s,i)=>e[i]=s)}Qo(e,t){const r=ny[e];let s=`${this.qo}/v1/${t}:${r}`;return this.databaseInfo.apiKey&&(s=`${s}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),s}terminate(){}}class sy{constructor(e){this.Ho=e.Ho,this.Jo=e.Jo}Zo(e){this.Xo=e}Yo(e){this.e_=e}t_(e){this.n_=e}onMessage(e){this.r_=e}close(){this.Jo()}send(e){this.Ho(e)}i_(){this.Xo()}s_(){this.e_()}o_(e){this.n_(e)}__(e){this.r_(e)}}const Pe="WebChannelConnection",kr=(n,e,t)=>{n.listen(e,r=>{try{t(r)}catch(s){setTimeout(()=>{throw s},0)}})};class Un extends ry{constructor(e){super(e),this.a_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static u_(){if(!Un.c_){const e=Fc();kr(e,Uc.STAT_EVENT,t=>{t.stat===to.PROXY?V(Pe,"STAT_EVENT: detected buffering proxy"):t.stat===to.NOPROXY&&V(Pe,"STAT_EVENT: detected no buffering proxy")}),Un.c_=!0}}zo(e,t,r,s,i){const a=No();return new Promise((c,l)=>{const d=new Mc;d.setWithCredentials(!0),d.listenOnce(xc.COMPLETE,()=>{try{switch(d.getLastErrorCode()){case ms.NO_ERROR:const m=d.getResponseJson();V(Pe,`XHR for RPC '${e}' ${a} received:`,JSON.stringify(m)),c(m);break;case ms.TIMEOUT:V(Pe,`RPC '${e}' ${a} timed out`),l(new D(P.DEADLINE_EXCEEDED,"Request time out"));break;case ms.HTTP_ERROR:const _=d.getStatus();if(V(Pe,`RPC '${e}' ${a} failed with status:`,_,"response text:",d.getResponseText()),_>0){let R=d.getResponseJson();Array.isArray(R)&&(R=R[0]);const S=R?.error;if(S&&S.status&&S.message){const N=function(U){const $=U.toLowerCase().replace(/_/g,"-");return Object.values(P).indexOf($)>=0?$:P.UNKNOWN}(S.status);l(new D(N,S.message))}else l(new D(P.UNKNOWN,"Server responded with status "+d.getStatus()))}else l(new D(P.UNAVAILABLE,"Connection failed."));break;default:x(9055,{l_:e,streamId:a,h_:d.getLastErrorCode(),P_:d.getLastError()})}}finally{V(Pe,`RPC '${e}' ${a} completed.`)}});const f=JSON.stringify(s);V(Pe,`RPC '${e}' ${a} sending request:`,s),d.send(t,"POST",f,r,15)})}T_(e,t,r){const s=No(),i=[this.qo,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=this.createWebChannelTransport(),c={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;l!==void 0&&(c.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(c.useFetchStreams=!0),this.Go(c.initMessageHeaders,t,r),c.encodeInitMessageHeaders=!0;const d=i.join("");V(Pe,`Creating RPC '${e}' stream ${s}: ${d}`,c);const f=a.createWebChannel(d,c);this.I_(f);let m=!1,_=!1;const R=new sy({Ho:S=>{_?V(Pe,`Not sending because RPC '${e}' stream ${s} is closed:`,S):(m||(V(Pe,`Opening RPC '${e}' stream ${s} transport.`),f.open(),m=!0),V(Pe,`RPC '${e}' stream ${s} sending:`,S),f.send(S))},Jo:()=>f.close()});return kr(f,pr.EventType.OPEN,()=>{_||(V(Pe,`RPC '${e}' stream ${s} transport opened.`),R.i_())}),kr(f,pr.EventType.CLOSE,()=>{_||(_=!0,V(Pe,`RPC '${e}' stream ${s} transport closed`),R.o_(),this.E_(f))}),kr(f,pr.EventType.ERROR,S=>{_||(_=!0,sn(Pe,`RPC '${e}' stream ${s} transport errored. Name:`,S.name,"Message:",S.message),R.o_(new D(P.UNAVAILABLE,"The operation could not be completed")))}),kr(f,pr.EventType.MESSAGE,S=>{if(!_){const N=S.data[0];J(!!N,16349);const k=N,U=k?.error||k[0]?.error;if(U){V(Pe,`RPC '${e}' stream ${s} received error:`,U);const $=U.status;let j=function(re){const w=he[re];if(w!==void 0)return qu(w)}($),Q=U.message;$==="NOT_FOUND"&&Q.includes("database")&&Q.includes("does not exist")&&Q.includes(this.databaseId.database)&&sn(`Database '${this.databaseId.database}' not found. Please check your project configuration.`),j===void 0&&(j=P.INTERNAL,Q="Unknown error status: "+$+" with message "+U.message),_=!0,R.o_(new D(j,Q)),f.close()}else V(Pe,`RPC '${e}' stream ${s} received:`,N),R.__(N)}}),Un.u_(),setTimeout(()=>{R.s_()},0),R}terminate(){this.a_.forEach(e=>e.close()),this.a_=[]}I_(e){this.a_.push(e)}E_(e){this.a_=this.a_.filter(t=>t===e)}Go(e,t,r){super.Go(e,t,r),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return Bc()}}function iy(n){return new Un(n)}function Oo(){return typeof document<"u"?document:null}function Hs(n){return new u_(n,!0)}Un.c_=!1;class ml{constructor(e,t,r=1e3,s=1.5,i=6e4){this.Ci=e,this.timerId=t,this.R_=r,this.A_=s,this.V_=i,this.d_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.d_=0}g_(){this.d_=this.V_}p_(e){this.cancel();const t=Math.floor(this.d_+this.y_()),r=Math.max(0,Date.now()-this.f_),s=Math.max(0,t-r);s>0&&V("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.d_} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.m_=this.Ci.enqueueAfterDelay(this.timerId,s,()=>(this.f_=Date.now(),e())),this.d_*=this.A_,this.d_<this.R_&&(this.d_=this.R_),this.d_>this.V_&&(this.d_=this.V_)}w_(){this.m_!==null&&(this.m_.skipDelay(),this.m_=null)}cancel(){this.m_!==null&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.d_}}const gl="PersistentStream";class _l{constructor(e,t,r,s,i,a,c,l){this.Ci=e,this.b_=r,this.S_=s,this.connection=i,this.authCredentialsProvider=a,this.appCheckCredentialsProvider=c,this.listener=l,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new ml(e,t)}x_(){return this.state===1||this.state===5||this.O_()}O_(){return this.state===2||this.state===3}start(){this.F_=0,this.state!==4?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&this.C_===null&&(this.C_=this.Ci.enqueueAfterDelay(this.b_,6e4,()=>this.k_()))}K_(e){this.q_(),this.stream.send(e)}async k_(){if(this.O_())return this.close(0)}q_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.q_(),this.U_(),this.M_.cancel(),this.D_++,e!==4?this.M_.reset():t&&t.code===P.RESOURCE_EXHAUSTED?(Et(t.toString()),Et("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):t&&t.code===P.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.W_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.t_(t)}W_(){}auth(){this.state=1;const e=this.Q_(this.D_),t=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([r,s])=>{this.D_===t&&this.G_(r,s)},r=>{e(()=>{const s=new D(P.UNKNOWN,"Fetching auth token failed: "+r.message);return this.z_(s)})})}G_(e,t){const r=this.Q_(this.D_);this.stream=this.j_(e,t),this.stream.Zo(()=>{r(()=>this.listener.Zo())}),this.stream.Yo(()=>{r(()=>(this.state=2,this.v_=this.Ci.enqueueAfterDelay(this.S_,1e4,()=>(this.O_()&&(this.state=3),Promise.resolve())),this.listener.Yo()))}),this.stream.t_(s=>{r(()=>this.z_(s))}),this.stream.onMessage(s=>{r(()=>++this.F_==1?this.H_(s):this.onNext(s))})}N_(){this.state=5,this.M_.p_(async()=>{this.state=0,this.start()})}z_(e){return V(gl,`close with error: ${e}`),this.stream=null,this.close(4,e)}Q_(e){return t=>{this.Ci.enqueueAndForget(()=>this.D_===e?t():(V(gl,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class oy extends _l{constructor(e,t,r,s,i,a){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,s,a),this.serializer=i}j_(e,t){return this.connection.T_("Listen",e,t)}H_(e){return this.onNext(e)}onNext(e){this.M_.reset();const t=d_(this.serializer,e),r=function(i){if(!("targetChange"in i))return B.min();const a=i.targetChange;return a.targetIds&&a.targetIds.length?B.min():a.readTime?ot(a.readTime):B.min()}(e);return this.listener.J_(t,r)}Z_(e){const t={};t.database=Ro(this.serializer),t.addTarget=function(i,a){let c;const l=a.target;if(c=po(l)?{documents:m_(i,l)}:{query:Zu(i,l).ft},c.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){c.resumeToken=Ku(i,a.resumeToken);const d=To(i,a.expectedCount);d!==null&&(c.expectedCount=d)}else if(a.snapshotVersion.compareTo(B.min())>0){c.readTime=js(i,a.snapshotVersion.toTimestamp());const d=To(i,a.expectedCount);d!==null&&(c.expectedCount=d)}return c}(this.serializer,e);const r=y_(this.serializer,e);r&&(t.labels=r),this.K_(t)}X_(e){const t={};t.database=Ro(this.serializer),t.removeTarget=e,this.K_(t)}}class ay extends _l{constructor(e,t,r,s,i,a){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,s,a),this.serializer=i}get Y_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}W_(){this.Y_&&this.ea([])}j_(e,t){return this.connection.T_("Write",e,t)}H_(e){return J(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,J(!e.writeResults||e.writeResults.length===0,55816),this.listener.ta()}onNext(e){J(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.M_.reset();const t=p_(e.writeResults,e.commitTime),r=ot(e.commitTime);return this.listener.na(r,t)}ra(){const e={};e.database=Ro(this.serializer),this.K_(e)}ea(e){const t={streamToken:this.lastStreamToken,writes:e.map(r=>f_(this.serializer,r))};this.K_(t)}}class cy{}class uy extends cy{constructor(e,t,r,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=s,this.ia=!1}sa(){if(this.ia)throw new D(P.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,r,s){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,a])=>this.connection.Wo(e,Io(t,r),s,i,a)).catch(i=>{throw i.name==="FirebaseError"?(i.code===P.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new D(P.UNKNOWN,i.toString())})}jo(e,t,r,s,i){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([a,c])=>this.connection.jo(e,Io(t,r),s,a,c,i)).catch(a=>{throw a.name==="FirebaseError"?(a.code===P.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),a):new D(P.UNKNOWN,a.toString())})}terminate(){this.ia=!0,this.connection.terminate()}}function ly(n,e,t,r){return new uy(n,e,t,r)}class hy{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){this.oa===0&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve())))}ha(e){this.state==="Online"?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ca("Offline")))}set(e){this.Pa(),this.oa=0,e==="Online"&&(this.aa=!1),this.ca(e)}ca(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}la(e){const t=`Could not reach Cloud Firestore backend. ${e}
32
+ This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.aa?(Et(t),this.aa=!1):V("OnlineStateTracker",t)}Pa(){this._a!==null&&(this._a.cancel(),this._a=null)}}const un="RemoteStore";class dy{constructor(e,t,r,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.Ta=[],this.Ia=new Map,this.Ea=new Set,this.Ra=[],this.Aa=i,this.Aa.Mo(a=>{r.enqueueAndForget(async()=>{ln(this)&&(V(un,"Restarting streams for network reachability change."),await async function(l){const d=F(l);d.Ea.add(4),await Nr(d),d.Va.set("Unknown"),d.Ea.delete(4),await Ws(d)}(this))})}),this.Va=new hy(r,s)}}async function Ws(n){if(ln(n))for(const e of n.Ra)await e(!0)}async function Nr(n){for(const e of n.Ra)await e(!1)}function yl(n,e){const t=F(n);t.Ia.has(e.targetId)||(t.Ia.set(e.targetId,e),xo(t)?Mo(t):Fn(t).O_()&&Lo(t,e))}function Vo(n,e){const t=F(n),r=Fn(t);t.Ia.delete(e),r.O_()&&El(t,e),t.Ia.size===0&&(r.O_()?r.L_():ln(t)&&t.Va.set("Unknown"))}function Lo(n,e){if(n.da.$e(e.targetId),e.resumeToken.approximateByteSize()>0||e.snapshotVersion.compareTo(B.min())>0){const t=n.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;e=e.withExpectedCount(t)}Fn(n).Z_(e)}function El(n,e){n.da.$e(e),Fn(n).X_(e)}function Mo(n){n.da=new i_({getRemoteKeysForTarget:e=>n.remoteSyncer.getRemoteKeysForTarget(e),At:e=>n.Ia.get(e)||null,ht:()=>n.datastore.serializer.databaseId}),Fn(n).start(),n.Va.ua()}function xo(n){return ln(n)&&!Fn(n).x_()&&n.Ia.size>0}function ln(n){return F(n).Ea.size===0}function Tl(n){n.da=void 0}async function fy(n){n.Va.set("Online")}async function py(n){n.Ia.forEach((e,t)=>{Lo(n,e)})}async function my(n,e){Tl(n),xo(n)?(n.Va.ha(e),Mo(n)):n.Va.set("Unknown")}async function gy(n,e,t){if(n.Va.set("Online"),e instanceof Hu&&e.state===2&&e.cause)try{await async function(s,i){const a=i.cause;for(const c of i.targetIds)s.Ia.has(c)&&(await s.remoteSyncer.rejectListen(c,a),s.Ia.delete(c),s.da.removeTarget(c))}(n,e)}catch(r){V(un,"Failed to remove targets %s: %s ",e.targetIds.join(","),r),await Gs(n,r)}else if(e instanceof Bs?n.da.Xe(e):e instanceof zu?n.da.st(e):n.da.tt(e),!t.isEqual(B.min()))try{const r=await ll(n.localStore);t.compareTo(r)>=0&&await function(i,a){const c=i.da.Tt(a);return c.targetChanges.forEach((l,d)=>{if(l.resumeToken.approximateByteSize()>0){const f=i.Ia.get(d);f&&i.Ia.set(d,f.withResumeToken(l.resumeToken,a))}}),c.targetMismatches.forEach((l,d)=>{const f=i.Ia.get(l);if(!f)return;i.Ia.set(l,f.withResumeToken(we.EMPTY_BYTE_STRING,f.snapshotVersion)),El(i,l);const m=new Ut(f.target,l,d,f.sequenceNumber);Lo(i,m)}),i.remoteSyncer.applyRemoteEvent(c)}(n,t)}catch(r){V(un,"Failed to raise snapshot:",r),await Gs(n,r)}}async function Gs(n,e,t){if(!kn(e))throw e;n.Ea.add(1),await Nr(n),n.Va.set("Offline"),t||(t=()=>ll(n.localStore)),n.asyncQueue.enqueueRetryable(async()=>{V(un,"Retrying IndexedDB access"),await t(),n.Ea.delete(1),await Ws(n)})}function wl(n,e){return e().catch(t=>Gs(n,t,e))}async function Ks(n){const e=F(n),t=Ft(e);let r=e.Ta.length>0?e.Ta[e.Ta.length-1].batchId:oo;for(;_y(e);)try{const s=await J_(e.localStore,r);if(s===null){e.Ta.length===0&&t.L_();break}r=s.batchId,yy(e,s)}catch(s){await Gs(e,s)}Il(e)&&vl(e)}function _y(n){return ln(n)&&n.Ta.length<10}function yy(n,e){n.Ta.push(e);const t=Ft(n);t.O_()&&t.Y_&&t.ea(e.mutations)}function Il(n){return ln(n)&&!Ft(n).x_()&&n.Ta.length>0}function vl(n){Ft(n).start()}async function Ey(n){Ft(n).ra()}async function Ty(n){const e=Ft(n);for(const t of n.Ta)e.ea(t.mutations)}async function wy(n,e,t){const r=n.Ta.shift(),s=yo.from(r,e,t);await wl(n,()=>n.remoteSyncer.applySuccessfulWrite(s)),await Ks(n)}async function Iy(n,e){e&&Ft(n).Y_&&await async function(r,s){if(function(a){return n_(a)&&a!==P.ABORTED}(s.code)){const i=r.Ta.shift();Ft(r).B_(),await wl(r,()=>r.remoteSyncer.rejectFailedWrite(i.batchId,s)),await Ks(r)}}(n,e),Il(n)&&vl(n)}async function Al(n,e){const t=F(n);t.asyncQueue.verifyOperationInProgress(),V(un,"RemoteStore received new credentials");const r=ln(t);t.Ea.add(3),await Nr(t),r&&t.Va.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.Ea.delete(3),await Ws(t)}async function vy(n,e){const t=F(n);e?(t.Ea.delete(2),await Ws(t)):e||(t.Ea.add(2),await Nr(t),t.Va.set("Unknown"))}function Fn(n){return n.ma||(n.ma=function(t,r,s){const i=F(t);return i.sa(),new oy(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(n.datastore,n.asyncQueue,{Zo:fy.bind(null,n),Yo:py.bind(null,n),t_:my.bind(null,n),J_:gy.bind(null,n)}),n.Ra.push(async e=>{e?(n.ma.B_(),xo(n)?Mo(n):n.Va.set("Unknown")):(await n.ma.stop(),Tl(n))})),n.ma}function Ft(n){return n.fa||(n.fa=function(t,r,s){const i=F(t);return i.sa(),new ay(r,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(n.datastore,n.asyncQueue,{Zo:()=>Promise.resolve(),Yo:Ey.bind(null,n),t_:Iy.bind(null,n),ta:Ty.bind(null,n),na:wy.bind(null,n)}),n.Ra.push(async e=>{e?(n.fa.B_(),await Ks(n)):(await n.fa.stop(),n.Ta.length>0&&(V(un,`Stopping write stream with ${n.Ta.length} pending writes`),n.Ta=[]))})),n.fa}class Uo{constructor(e,t,r,s,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=s,this.removalCallback=i,this.deferred=new nt,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(a=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,r,s,i){const a=Date.now()+r,c=new Uo(e,t,a,s,i);return c.start(r),c}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new D(P.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Fo(n,e){if(Et("AsyncQueue",`${e}: ${n}`),kn(n))return new D(P.UNAVAILABLE,`${e}: ${n}`);throw n}class Bn{static emptySet(e){return new Bn(e.comparator)}constructor(e){this.comparator=e?(t,r)=>e(t,r)||L.comparator(t.key,r.key):(t,r)=>L.comparator(t.key,r.key),this.keyedMap=Ir(),this.sortedSet=new se(this.comparator)}has(e){return this.keyedMap.get(e)!=null}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,r)=>(e(t),!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){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Bn)||this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();for(;t.hasNext();){const s=t.getNext().key,i=r.getNext().key;if(!s.isEqual(i))return!1}return!0}toString(){const e=[];return this.forEach(t=>{e.push(t.toString())}),e.length===0?"DocumentSet ()":`DocumentSet (
33
33
  `+e.join(`
34
34
  `)+`
35
- )`}copy(e,t){const r=new Bn;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class Rl{constructor(){this.ga=new se(L.comparator)}track(e){const t=e.doc.key,r=this.ga.get(t);r?e.type!==0&&r.type===3?this.ga=this.ga.insert(t,e):e.type===3&&r.type!==1?this.ga=this.ga.insert(t,{type:r.type,doc:e.doc}):e.type===2&&r.type===2?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):e.type===2&&r.type===0?this.ga=this.ga.insert(t,{type:0,doc:e.doc}):e.type===1&&r.type===0?this.ga=this.ga.remove(t):e.type===1&&r.type===2?this.ga=this.ga.insert(t,{type:1,doc:r.doc}):e.type===0&&r.type===1?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):x(63341,{Vt:e,pa:r}):this.ga=this.ga.insert(t,e)}ya(){const e=[];return this.ga.inorderTraversal((t,r)=>{e.push(r)}),e}}class qn{constructor(e,t,r,s,i,a,c,l,d){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=s,this.mutatedKeys=i,this.fromCache=a,this.syncStateChanged=c,this.excludesMetadataChanges=l,this.hasCachedResults=d}static fromInitialDocuments(e,t,r,s,i){const a=[];return t.forEach(c=>{a.push({type:0,doc:c})}),new qn(e,t,Bn.emptySet(t),a,r,s,!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)&&Ns(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++)if(t[s].type!==r[s].type||!t[s].doc.isEqual(r[s].doc))return!1;return!0}}class Ay{constructor(){this.wa=void 0,this.ba=[]}Sa(){return this.ba.some(e=>e.Da())}}class Ry{constructor(){this.queries=bl(),this.onlineState="Unknown",this.Ca=new Set}terminate(){(function(t,r){const s=U(t),i=s.queries;s.queries=bl(),i.forEach((a,c)=>{for(const l of c.ba)l.onError(r)})})(this,new D(P.ABORTED,"Firestore shutting down"))}}function bl(){return new on(n=>Ru(n),Ns)}async function Bo(n,e){const t=U(n);let r=3;const s=e.query;let i=t.queries.get(s);i?!i.Sa()&&e.Da()&&(r=2):(i=new Ay,r=e.Da()?0:1);try{switch(r){case 0:i.wa=await t.onListen(s,!0);break;case 1:i.wa=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(a){const c=Fo(a,`Initialization of query '${Ln(e.query)}' failed`);return void e.onError(c)}t.queries.set(s,i),i.ba.push(e),e.va(t.onlineState),i.wa&&e.Fa(i.wa)&&jo(t)}async function qo(n,e){const t=U(n),r=e.query;let s=3;const i=t.queries.get(r);if(i){const a=i.ba.indexOf(e);a>=0&&(i.ba.splice(a,1),i.ba.length===0?s=e.Da()?0:1:!i.Sa()&&e.Da()&&(s=2))}switch(s){case 0:return t.queries.delete(r),t.onUnlisten(r,!0);case 1:return t.queries.delete(r),t.onUnlisten(r,!1);case 2:return t.onLastRemoteStoreUnlisten(r);default:return}}function by(n,e){const t=U(n);let r=!1;for(const s of e){const i=s.query,a=t.queries.get(i);if(a){for(const c of a.ba)c.Fa(s)&&(r=!0);a.wa=s}}r&&jo(t)}function Py(n,e,t){const r=U(n),s=r.queries.get(e);if(s)for(const i of s.ba)i.onError(t);r.queries.delete(e)}function jo(n){n.Ca.forEach(e=>{e.next()})}var $o,Pl;(Pl=$o||($o={})).Ma="default",Pl.Cache="cache";class zo{constructor(e,t,r){this.query=e,this.xa=t,this.Oa=!1,this.Na=null,this.onlineState="Unknown",this.options=r||{}}Fa(e){if(!this.options.includeMetadataChanges){const r=[];for(const s of e.docChanges)s.type!==3&&r.push(s);e=new qn(e.query,e.docs,e.oldDocs,r,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Oa?this.Ba(e)&&(this.xa.next(e),t=!0):this.La(e,this.onlineState)&&(this.ka(e),t=!0),this.Na=e,t}onError(e){this.xa.error(e)}va(e){this.onlineState=e;let t=!1;return this.Na&&!this.Oa&&this.La(this.Na,e)&&(this.ka(this.Na),t=!0),t}La(e,t){if(!e.fromCache||!this.Da())return!0;const r=t!=="Offline";return(!this.options.Ka||!r)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}Ba(e){if(e.docChanges.length>0)return!0;const t=this.Na&&this.Na.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}ka(e){e=qn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Oa=!0,this.xa.next(e)}Da(){return this.options.source!==$o.Cache}}class Sl{constructor(e){this.key=e}}class Cl{constructor(e){this.key=e}}class Sy{constructor(e,t){this.query=e,this.Za=t,this.Xa=null,this.hasCachedResults=!1,this.current=!1,this.Ya=G(),this.mutatedKeys=G(),this.eu=bu(e),this.tu=new Bn(this.eu)}get nu(){return this.Za}ru(e,t){const r=t?t.iu:new Rl,s=t?t.tu:this.tu;let i=t?t.mutatedKeys:this.mutatedKeys,a=s,c=!1;const l=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,d=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal((f,m)=>{const g=s.get(f),R=Ds(this.query,m)?m:null,C=!!g&&this.mutatedKeys.has(g.key),N=!!R&&(R.hasLocalMutations||this.mutatedKeys.has(R.key)&&R.hasCommittedMutations);let k=!1;g&&R?g.data.isEqual(R.data)?C!==N&&(r.track({type:3,doc:R}),k=!0):this.su(g,R)||(r.track({type:2,doc:R}),k=!0,(l&&this.eu(R,l)>0||d&&this.eu(R,d)<0)&&(c=!0)):!g&&R?(r.track({type:0,doc:R}),k=!0):g&&!R&&(r.track({type:1,doc:g}),k=!0,(l||d)&&(c=!0)),k&&(R?(a=a.add(R),i=N?i.add(f):i.delete(f)):(a=a.delete(f),i=i.delete(f)))}),this.query.limit!==null)for(;a.size>this.query.limit;){const f=this.query.limitType==="F"?a.last():a.first();a=a.delete(f.key),i=i.delete(f.key),r.track({type:1,doc:f})}return{tu:a,iu:r,Ss:c,mutatedKeys:i}}su(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,s){const i=this.tu;this.tu=e.tu,this.mutatedKeys=e.mutatedKeys;const a=e.iu.ya();a.sort((f,m)=>function(R,C){const N=k=>{switch(k){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return x(20277,{Vt:k})}};return N(R)-N(C)}(f.type,m.type)||this.eu(f.doc,m.doc)),this.ou(r),s=s??!1;const c=t&&!s?this._u():[],l=this.Ya.size===0&&this.current&&!s?1:0,d=l!==this.Xa;return this.Xa=l,a.length!==0||d?{snapshot:new qn(this.query,e.tu,i,a,e.mutatedKeys,l===0,d,!1,!!r&&r.resumeToken.approximateByteSize()>0),au:c}:{au:c}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({tu:this.tu,iu:new Rl,mutatedKeys:this.mutatedKeys,Ss:!1},!1)):{au:[]}}uu(e){return!this.Za.has(e)&&!!this.tu.has(e)&&!this.tu.get(e).hasLocalMutations}ou(e){e&&(e.addedDocuments.forEach(t=>this.Za=this.Za.add(t)),e.modifiedDocuments.forEach(t=>{}),e.removedDocuments.forEach(t=>this.Za=this.Za.delete(t)),this.current=e.current)}_u(){if(!this.current)return[];const e=this.Ya;this.Ya=G(),this.tu.forEach(r=>{this.uu(r.key)&&(this.Ya=this.Ya.add(r.key))});const t=[];return e.forEach(r=>{this.Ya.has(r)||t.push(new Cl(r))}),this.Ya.forEach(r=>{e.has(r)||t.push(new Sl(r))}),t}cu(e){this.Za=e.ks,this.Ya=G();const t=this.ru(e.documents);return this.applyChanges(t,!0)}lu(){return qn.fromInitialDocuments(this.query,this.tu,this.mutatedKeys,this.Xa===0,this.hasCachedResults)}}const Ho="SyncEngine";class Cy{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class ky{constructor(e){this.key=e,this.hu=!1}}class Ny{constructor(e,t,r,s,i,a){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=a,this.Pu={},this.Tu=new on(c=>Ru(c),Ns),this.Iu=new Map,this.Eu=new Set,this.Ru=new se(L.comparator),this.Au=new Map,this.Vu=new bo,this.du={},this.mu=new Map,this.fu=xn.ar(),this.onlineState="Unknown",this.gu=void 0}get isPrimaryClient(){return this.gu===!0}}async function Dy(n,e,t=!0){const r=xl(n);let s;const i=r.Tu.get(e);return i?(r.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.lu()):s=await kl(r,e,t,!0),s}async function Oy(n,e){const t=xl(n);await kl(t,e,!0,!1)}async function kl(n,e,t,r){const s=await X_(n.localStore,it(e)),i=s.targetId,a=n.sharedClientState.addLocalQueryTarget(i,t);let c;return r&&(c=await Vy(n,e,i,a==="current",s.resumeToken)),n.isPrimaryClient&&t&&yl(n.remoteStore,s),c}async function Vy(n,e,t,r,s){n.pu=(m,g,R)=>async function(N,k,F,$){let j=k.view.ru(F);j.Ss&&(j=await hl(N.localStore,k.query,!1).then(({documents:w})=>k.view.ru(w,j)));const J=$&&$.targetChanges.get(k.targetId),_e=$&&$.targetMismatches.get(k.targetId)!=null,re=k.view.applyChanges(j,N.isPrimaryClient,J,_e);return Ml(N,k.targetId,re.au),re.snapshot}(n,m,g,R);const i=await hl(n.localStore,e,!0),a=new Sy(e,i.ks),c=a.ru(i.documents),l=Cr.createSynthesizedTargetChangeForCurrentChange(t,r&&n.onlineState!=="Offline",s),d=a.applyChanges(c,n.isPrimaryClient,l);Ml(n,t,d.au);const f=new Cy(e,t,a);return n.Tu.set(e,f),n.Iu.has(t)?n.Iu.get(t).push(e):n.Iu.set(t,[e]),d.snapshot}async function Ly(n,e,t){const r=U(n),s=r.Tu.get(e),i=r.Iu.get(s.targetId);if(i.length>1)return r.Iu.set(s.targetId,i.filter(a=>!Ns(a,e))),void r.Tu.delete(e);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(s.targetId),r.sharedClientState.isActiveQueryTarget(s.targetId)||await ko(r.localStore,s.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(s.targetId),t&&Vo(r.remoteStore,s.targetId),Wo(r,s.targetId)}).catch(Cn)):(Wo(r,s.targetId),await ko(r.localStore,s.targetId,!0))}async function My(n,e){const t=U(n),r=t.Tu.get(e),s=t.Iu.get(r.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(r.targetId),Vo(t.remoteStore,r.targetId))}async function xy(n,e,t){const r=zy(n);try{const s=await function(a,c){const l=U(a),d=ee.now(),f=c.reduce((R,C)=>R.add(C.key),G());let m,g;return l.persistence.runTransaction("Locally write mutations","readwrite",R=>{let C=Tt(),N=G();return l.xs.getEntries(R,f).next(k=>{C=k,C.forEach((F,$)=>{$.isValidDocument()||(N=N.add(F))})}).next(()=>l.localDocuments.getOverlayedDocuments(R,C)).next(k=>{m=k;const F=[];for(const $ of c){const j=Yg($,m.get($.key).overlayedDocument);j!=null&&F.push(new Mt($.key,j,fu(j.value.mapValue),$e.exists(!0)))}return l.mutationQueue.addMutationBatch(R,d,F,c)}).next(k=>{g=k;const F=k.applyToLocalDocumentSet(m,N);return l.documentOverlayCache.saveOverlays(R,k.batchId,F)})}).then(()=>({batchId:g.batchId,changes:Su(m)}))}(r.localStore,e);r.sharedClientState.addPendingMutation(s.batchId),function(a,c,l){let d=a.du[a.currentUser.toKey()];d||(d=new se(W)),d=d.insert(c,l),a.du[a.currentUser.toKey()]=d}(r,s.batchId,t),await Dr(r,s.changes),await Ks(r.remoteStore)}catch(s){const i=Fo(s,"Failed to persist write");t.reject(i)}}async function Nl(n,e){const t=U(n);try{const r=await Q_(t.localStore,e);e.targetChanges.forEach((s,i)=>{const a=t.Au.get(i);a&&(Y(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1,22616),s.addedDocuments.size>0?a.hu=!0:s.modifiedDocuments.size>0?Y(a.hu,14607):s.removedDocuments.size>0&&(Y(a.hu,42227),a.hu=!1))}),await Dr(t,r,e)}catch(r){await Cn(r)}}function Dl(n,e,t){const r=U(n);if(r.isPrimaryClient&&t===0||!r.isPrimaryClient&&t===1){const s=[];r.Tu.forEach((i,a)=>{const c=a.view.va(e);c.snapshot&&s.push(c.snapshot)}),function(a,c){const l=U(a);l.onlineState=c;let d=!1;l.queries.forEach((f,m)=>{for(const g of m.ba)g.va(c)&&(d=!0)}),d&&jo(l)}(r.eventManager,e),s.length&&r.Pu.J_(s),r.onlineState=e,r.isPrimaryClient&&r.sharedClientState.setOnlineState(e)}}async function Uy(n,e,t){const r=U(n);r.sharedClientState.updateQueryState(e,"rejected",t);const s=r.Au.get(e),i=s&&s.key;if(i){let a=new se(L.comparator);a=a.insert(i,be.newNoDocument(i,B.min()));const c=G().add(i),l=new Fs(B.min(),new Map,new se(W),a,c);await Nl(r,l),r.Ru=r.Ru.remove(i),r.Au.delete(e),Go(r)}else await ko(r.localStore,e,!1).then(()=>Wo(r,e,t)).catch(Cn)}async function Fy(n,e){const t=U(n),r=e.batch.batchId;try{const s=await K_(t.localStore,e);Vl(t,r,null),Ol(t,r),t.sharedClientState.updateMutationState(r,"acknowledged"),await Dr(t,s)}catch(s){await Cn(s)}}async function By(n,e,t){const r=U(n);try{const s=await function(a,c){const l=U(a);return l.persistence.runTransaction("Reject batch","readwrite-primary",d=>{let f;return l.mutationQueue.lookupMutationBatch(d,c).next(m=>(Y(m!==null,37113),f=m.keys(),l.mutationQueue.removeMutationBatch(d,m))).next(()=>l.mutationQueue.performConsistencyCheck(d)).next(()=>l.documentOverlayCache.removeOverlaysForBatchId(d,f,c)).next(()=>l.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(d,f)).next(()=>l.localDocuments.getDocuments(d,f))})}(r.localStore,e);Vl(r,e,t),Ol(r,e),r.sharedClientState.updateMutationState(e,"rejected",t),await Dr(r,s)}catch(s){await Cn(s)}}function Ol(n,e){(n.mu.get(e)||[]).forEach(t=>{t.resolve()}),n.mu.delete(e)}function Vl(n,e,t){const r=U(n);let s=r.du[r.currentUser.toKey()];if(s){const i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),r.du[r.currentUser.toKey()]=s}}function Wo(n,e,t=null){n.sharedClientState.removeLocalQueryTarget(e);for(const r of n.Iu.get(e))n.Tu.delete(r),t&&n.Pu.yu(r,t);n.Iu.delete(e),n.isPrimaryClient&&n.Vu.Gr(e).forEach(r=>{n.Vu.containsKey(r)||Ll(n,r)})}function Ll(n,e){n.Eu.delete(e.path.canonicalString());const t=n.Ru.get(e);t!==null&&(Vo(n.remoteStore,t),n.Ru=n.Ru.remove(e),n.Au.delete(t),Go(n))}function Ml(n,e,t){for(const r of t)r instanceof Sl?(n.Vu.addReference(r.key,e),qy(n,r)):r instanceof Cl?(V(Ho,"Document no longer in limbo: "+r.key),n.Vu.removeReference(r.key,e),n.Vu.containsKey(r.key)||Ll(n,r.key)):x(19791,{wu:r})}function qy(n,e){const t=e.key,r=t.path.canonicalString();n.Ru.get(t)||n.Eu.has(r)||(V(Ho,"New document in limbo: "+t),n.Eu.add(r),Go(n))}function Go(n){for(;n.Eu.size>0&&n.Ru.size<n.maxConcurrentLimboResolutions;){const e=n.Eu.values().next().value;n.Eu.delete(e);const t=new L(X.fromString(e)),r=n.fu.next();n.Au.set(r,new ky(t)),n.Ru=n.Ru.insert(t,r),yl(n.remoteStore,new Ut(it(Cs(t.path)),r,"TargetPurposeLimboResolution",_s.ce))}}async function Dr(n,e,t){const r=U(n),s=[],i=[],a=[];r.Tu.isEmpty()||(r.Tu.forEach((c,l)=>{a.push(r.pu(l,e,t).then(d=>{if((d||t)&&r.isPrimaryClient){const f=d?!d.fromCache:t?.targetChanges.get(l.targetId)?.current;r.sharedClientState.updateQueryState(l.targetId,f?"current":"not-current")}if(d){s.push(d);const f=So.Es(l.targetId,d);i.push(f)}}))}),await Promise.all(a),r.Pu.J_(s),await async function(l,d){const f=U(l);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",m=>S.forEach(d,g=>S.forEach(g.Ts,R=>f.persistence.referenceDelegate.addReference(m,g.targetId,R)).next(()=>S.forEach(g.Is,R=>f.persistence.referenceDelegate.removeReference(m,g.targetId,R)))))}catch(m){if(!kn(m))throw m;V(Co,"Failed to update sequence numbers: "+m)}for(const m of d){const g=m.targetId;if(!m.fromCache){const R=f.vs.get(g),C=R.snapshotVersion,N=R.withLastLimboFreeSnapshotVersion(C);f.vs=f.vs.insert(g,N)}}}(r.localStore,i))}async function jy(n,e){const t=U(n);if(!t.currentUser.isEqual(e)){V(Ho,"User change. New user:",e.toKey());const r=await ul(t.localStore,e);t.currentUser=e,function(i,a){i.mu.forEach(c=>{c.forEach(l=>{l.reject(new D(P.CANCELLED,a))})}),i.mu.clear()}(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,r.removedBatchIds,r.addedBatchIds),await Dr(t,r.Ns)}}function $y(n,e){const t=U(n),r=t.Au.get(e);if(r&&r.hu)return G().add(r.key);{let s=G();const i=t.Iu.get(e);if(!i)return s;for(const a of i){const c=t.Tu.get(a);s=s.unionWith(c.view.nu)}return s}}function xl(n){const e=U(n);return e.remoteStore.remoteSyncer.applyRemoteEvent=Nl.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=$y.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=Uy.bind(null,e),e.Pu.J_=by.bind(null,e.eventManager),e.Pu.yu=Py.bind(null,e.eventManager),e}function zy(n){const e=U(n);return e.remoteStore.remoteSyncer.applySuccessfulWrite=Fy.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=By.bind(null,e),e}class Qs{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=Hs(e.databaseInfo.databaseId),this.sharedClientState=this.Du(e),this.persistence=this.Cu(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Fu(e,this.localStore),this.indexBackfillerScheduler=this.Mu(e,this.localStore)}Fu(e,t){return null}Mu(e,t){return null}vu(e){return G_(this.persistence,new z_,e.initialUser,this.serializer)}Cu(e){return new cl(Po.Vi,this.serializer)}Du(e){return new ey}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}Qs.provider={build:()=>new Qs};class Hy extends Qs{constructor(e){super(),this.cacheSizeBytes=e}Fu(e,t){Y(this.persistence.referenceDelegate instanceof $s,46915);const r=this.persistence.referenceDelegate.garbageCollector;return new C_(r,e.asyncQueue,t)}Cu(e){const t=this.cacheSizeBytes!==void 0?Oe.withCacheSize(this.cacheSizeBytes):Oe.DEFAULT;return new cl(r=>$s.Vi(r,t),this.serializer)}}class Ko{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=r=>Dl(this.syncEngine,r,1),this.remoteStore.remoteSyncer.handleCredentialChange=jy.bind(null,this.syncEngine),await vy(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function(){return new Ry}()}createDatastore(e){const t=Hs(e.databaseInfo.databaseId),r=iy(e.databaseInfo);return ly(e.authCredentials,e.appCheckCredentials,r,t)}createRemoteStore(e){return function(r,s,i,a,c){return new dy(r,s,i,a,c)}(this.localStore,this.datastore,e.asyncQueue,t=>Dl(this.syncEngine,t,0),function(){return pl.v()?new pl:new ty}())}createSyncEngine(e,t){return function(s,i,a,c,l,d,f){const m=new Ny(s,i,a,c,l,d);return f&&(m.gu=!0),m}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){await async function(t){const r=U(t);V(cn,"RemoteStore shutting down."),r.Ea.add(5),await Nr(r),r.Aa.shutdown(),r.Va.set("Unknown")}(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}Ko.provider={build:()=>new Ko};class Qo{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ou(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ou(this.observer.error,e):Et("Uncaught Error in snapshot listener:",e.toString()))}Nu(){this.muted=!0}Ou(e,t){setTimeout(()=>{this.muted||e(t)},0)}}const Bt="FirestoreClient";class Wy{constructor(e,t,r,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this._databaseInfo=s,this.user=Re.UNAUTHENTICATED,this.clientId=ro.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async a=>{V(Bt,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a}),this.appCheckCredentials.start(r,a=>(V(Bt,"Received new app check token=",a),this.appCheckCredentialListener(a,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this._databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const e=new nt;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const r=Fo(t,"Failed to shutdown persistence");e.reject(r)}}),e.promise}}async function Yo(n,e){n.asyncQueue.verifyOperationInProgress(),V(Bt,"Initializing OfflineComponentProvider");const t=n.configuration;await e.initialize(t);let r=t.initialUser;n.setCredentialChangeListener(async s=>{r.isEqual(s)||(await ul(e.localStore,s),r=s)}),e.persistence.setDatabaseDeletedListener(()=>n.terminate()),n._offlineComponents=e}async function Ul(n,e){n.asyncQueue.verifyOperationInProgress();const t=await Gy(n);V(Bt,"Initializing OnlineComponentProvider"),await e.initialize(t,n.configuration),n.setCredentialChangeListener(r=>Al(e.remoteStore,r)),n.setAppCheckTokenChangeListener((r,s)=>Al(e.remoteStore,s)),n._onlineComponents=e}async function Gy(n){if(!n._offlineComponents)if(n._uninitializedComponentsProvider){V(Bt,"Using user provided OfflineComponentProvider");try{await Yo(n,n._uninitializedComponentsProvider._offline)}catch(e){const t=e;if(!function(s){return s.name==="FirebaseError"?s.code===P.FAILED_PRECONDITION||s.code===P.UNIMPLEMENTED:!(typeof DOMException<"u"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11}(t))throw t;Pn("Error using user provided cache. Falling back to memory cache: "+t),await Yo(n,new Qs)}}else V(Bt,"Using default OfflineComponentProvider"),await Yo(n,new Hy(void 0));return n._offlineComponents}async function Jo(n){return n._onlineComponents||(n._uninitializedComponentsProvider?(V(Bt,"Using user provided OnlineComponentProvider"),await Ul(n,n._uninitializedComponentsProvider._online)):(V(Bt,"Using default OnlineComponentProvider"),await Ul(n,new Ko))),n._onlineComponents}function Ky(n){return Jo(n).then(e=>e.syncEngine)}function Qy(n){return Jo(n).then(e=>e.datastore)}async function Ys(n){const e=await Jo(n),t=e.eventManager;return t.onListen=Dy.bind(null,e.syncEngine),t.onUnlisten=Ly.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=Oy.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=My.bind(null,e.syncEngine),t}function Yy(n,e,t,r){const s=new Qo(r),i=new zo(e,s,t);return n.asyncQueue.enqueueAndForget(async()=>Bo(await Ys(n),i)),()=>{s.Nu(),n.asyncQueue.enqueueAndForget(async()=>qo(await Ys(n),i))}}function Jy(n,e,t={}){const r=new nt;return n.asyncQueue.enqueueAndForget(async()=>function(i,a,c,l,d){const f=new Qo({next:g=>{f.Nu(),a.enqueueAndForget(()=>qo(i,m));const R=g.docs.has(c);!R&&g.fromCache?d.reject(new D(P.UNAVAILABLE,"Failed to get document because the client is offline.")):R&&g.fromCache&&l&&l.source==="server"?d.reject(new D(P.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.)')):d.resolve(g)},error:g=>d.reject(g)}),m=new zo(Cs(c.path),f,{includeMetadataChanges:!0,Ka:!0});return Bo(i,m)}(await Ys(n),n.asyncQueue,e,t,r)),r.promise}function Xy(n,e,t={}){const r=new nt;return n.asyncQueue.enqueueAndForget(async()=>function(i,a,c,l,d){const f=new Qo({next:g=>{f.Nu(),a.enqueueAndForget(()=>qo(i,m)),g.fromCache&&l.source==="server"?d.reject(new D(P.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.)')):d.resolve(g)},error:g=>d.reject(g)}),m=new zo(c,f,{includeMetadataChanges:!0,Ka:!0});return Bo(i,m)}(await Ys(n),n.asyncQueue,e,t,r)),r.promise}function Zy(n,e,t){const r=new nt;return n.asyncQueue.enqueueAndForget(async()=>{try{const s=await Qy(n);r.resolve(async function(a,c,l){const d=U(a),{request:f,gt:m,parent:g}=g_(d.serializer,Vg(c),l);d.connection.Ko||delete f.parent;const R=(await d.jo("RunAggregationQuery",d.serializer.databaseId,g,f,1)).filter(N=>!!N.result);Y(R.length===1,64727);const C=R[0].result?.aggregateFields;return Object.keys(C).reduce((N,k)=>(N[m[k]]=C[k],N),{})}(s,e,t))}catch(s){r.reject(s)}}),r.promise}function eE(n,e){const t=new nt;return n.asyncQueue.enqueueAndForget(async()=>xy(await Ky(n),e,t)),t.promise}function Fl(n){const e={};return n.timeoutSeconds!==void 0&&(e.timeoutSeconds=n.timeoutSeconds),e}const tE="ComponentProvider",Bl=new Map;function nE(n,e,t,r,s){return new _g(n,e,t,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Fl(s.experimentalLongPollingOptions),s.useFetchStreams,s.isUsingEmulator,r)}const ql="firestore.googleapis.com",jl=!0;class $l{constructor(e){if(e.host===void 0){if(e.ssl!==void 0)throw new D(P.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=ql,this.ssl=jl}else this.host=e.host,this.ssl=e.ssl??jl;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=il;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<P_)throw new D(P.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}sg("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Fl(e.experimentalLongPollingOptions??{}),function(r){if(r.timeoutSeconds!==void 0){if(isNaN(r.timeoutSeconds))throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (must not be NaN)`);if(r.timeoutSeconds<5)throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (minimum allowed value is 5)`);if(r.timeoutSeconds>30)throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function(r,s){return r.timeoutSeconds===s.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Js{constructor(e,t,r,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new $l({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new D(P.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 this._terminateTask!=="notTerminated"}_setSettings(e){if(this._settingsFrozen)throw new D(P.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 $l(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=function(r){if(!r)return new Km;switch(r.type){case"firstParty":return new Xm(r.sessionIndex||"0",r.iamToken||null,r.authTokenFactory||null);case"provider":return r.client;default:throw new D(P.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(t){const r=Bl.get(t);r&&(V(tE,"Removing Datastore"),Bl.delete(t),r.terminate())}(this),Promise.resolve()}}function zl(n,e,t,r={}){n=Ge(n,Js);const s=tt(e),i=n._getSettings(),a={...i,emulatorOptions:n._getEmulatorOptions()},c=`${e}:${t}`;s&&(ls(`https://${c}`),hs("Firestore",!0)),i.host!==ql&&i.host!==c&&Pn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");const l={...i,host:c,ssl:s,emulatorOptions:r};if(!en(l,a)&&(n._setSettings(l),r.mockUserToken)){let d,f;if(typeof r.mockUserToken=="string")d=r.mockUserToken,f=Re.MOCK_USER;else{d=yc(r.mockUserToken,n._app?.options.projectId);const m=r.mockUserToken.sub||r.mockUserToken.user_id;if(!m)throw new D(P.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");f=new Re(m)}n._authCredentials=new Qm(new jc(d,f))}}class at{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new at(this.firestore,e,this._query)}}class de{constructor(e,t,r){this.converter=t,this._key=r,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new qt(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new de(this.firestore,e,this._key)}toJSON(){return{type:de._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,r){if(mr(t,de._jsonSchema))return new de(e,r||null,new L(X.fromString(t.referencePath)))}}de._jsonSchemaVersion="firestore/documentReference/1.0",de._jsonSchema={type:ue("string",de._jsonSchemaVersion),referencePath:ue("string")};class qt extends at{constructor(e,t,r){super(e,t,Cs(r)),this._path=r,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 de(this.firestore,null,new L(e))}withConverter(e){return new qt(this.firestore,e,this._path)}}function Hl(n,e,...t){if(n=Q(n),Hc("collection","path",e),n instanceof Js){const r=X.fromString(e,...t);return Gc(r),new qt(n,null,r)}{if(!(n instanceof de||n instanceof qt))throw new D(P.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=n._path.child(X.fromString(e,...t));return Gc(r),new qt(n.firestore,null,r)}}function Xs(n,e,...t){if(n=Q(n),arguments.length===1&&(e=ro.newId()),Hc("doc","path",e),n instanceof Js){const r=X.fromString(e,...t);return Wc(r),new de(n,null,new L(r))}{if(!(n instanceof de||n instanceof qt))throw new D(P.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=n._path.child(X.fromString(e,...t));return Wc(r),new de(n.firestore,n instanceof qt?n.converter:null,new L(r))}}const Wl="AsyncQueue";class Gl{constructor(e=Promise.resolve()){this.Yu=[],this.ec=!1,this.tc=[],this.nc=null,this.rc=!1,this.sc=!1,this.oc=[],this.M_=new ml(this,"async_queue_retry"),this._c=()=>{const r=Oo();r&&V(Wl,"Visibility state changed to "+r.visibilityState),this.M_.w_()},this.ac=e;const t=Oo();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this._c)}get isShuttingDown(){return this.ec}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.uc(),this.cc(e)}enterRestrictedMode(e){if(!this.ec){this.ec=!0,this.sc=e||!1;const t=Oo();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this._c)}}enqueue(e){if(this.uc(),this.ec)return new Promise(()=>{});const t=new nt;return this.cc(()=>this.ec&&this.sc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Yu.push(e),this.lc()))}async lc(){if(this.Yu.length!==0){try{await this.Yu[0](),this.Yu.shift(),this.M_.reset()}catch(e){if(!kn(e))throw e;V(Wl,"Operation failed with retryable error: "+e)}this.Yu.length>0&&this.M_.p_(()=>this.lc())}}cc(e){const t=this.ac.then(()=>(this.rc=!0,e().catch(r=>{throw this.nc=r,this.rc=!1,Et("INTERNAL UNHANDLED ERROR: ",Kl(r)),r}).then(r=>(this.rc=!1,r))));return this.ac=t,t}enqueueAfterDelay(e,t,r){this.uc(),this.oc.indexOf(e)>-1&&(t=0);const s=Uo.createAndSchedule(this,e,t,r,i=>this.hc(i));return this.tc.push(s),s}uc(){this.nc&&x(47125,{Pc:Kl(this.nc)})}verifyOperationInProgress(){}async Tc(){let e;do e=this.ac,await e;while(e!==this.ac)}Ic(e){for(const t of this.tc)if(t.timerId===e)return!0;return!1}Ec(e){return this.Tc().then(()=>{this.tc.sort((t,r)=>t.targetTimeMs-r.targetTimeMs);for(const t of this.tc)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Tc()})}Rc(e){this.oc.push(e)}hc(e){const t=this.tc.indexOf(e);this.tc.splice(t,1)}}function Kl(n){let e=n.message||"";return n.stack&&(e=n.stack.includes(n.message)?n.stack:n.message+`
36
- `+n.stack),e}class jt extends Js{constructor(e,t,r,s){super(e,t,r,s),this.type="firestore",this._queue=new Gl,this._persistenceKey=s?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new Gl(e),this._firestoreClient=void 0,await e}}}function rE(n,e){const t=typeof n=="object"?n:fs(),r=typeof n=="string"?n:vs,s=dr(t,"firestore").getImmediate({identifier:r});if(!s._initialized){const i=ji("firestore");i&&zl(s,...i)}return s}function jn(n){if(n._terminated)throw new D(P.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||sE(n),n._firestoreClient}function sE(n){const e=n._freezeSettings(),t=nE(n._databaseId,n._app?.options.appId||"",n._persistenceKey,n._app?.options.apiKey,e);n._componentsProvider||e.localCache?._offlineComponentProvider&&e.localCache?._onlineComponentProvider&&(n._componentsProvider={_offline:e.localCache._offlineComponentProvider,_online:e.localCache._onlineComponentProvider}),n._firestoreClient=new Wy(n._authCredentials,n._appCheckCredentials,n._queue,t,n._componentsProvider&&function(s){const i=s?._online.build();return{_offline:s?._offline.build(i),_online:i}}(n._componentsProvider))}class ze{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ze(we.fromBase64String(e))}catch(t){throw new D(P.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new ze(we.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)}toJSON(){return{type:ze._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(mr(e,ze._jsonSchema))return ze.fromBase64String(e.bytes)}}ze._jsonSchemaVersion="firestore/bytes/1.0",ze._jsonSchema={type:ue("string",ze._jsonSchemaVersion),bytes:ue("string")};class Xo{constructor(...e){for(let t=0;t<e.length;++t)if(e[t].length===0)throw new D(P.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Ee(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class Zo{constructor(e){this._methodName=e}}class ct{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new D(P.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new D(P.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}_compareTo(e){return W(this._lat,e._lat)||W(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:ct._jsonSchemaVersion}}static fromJSON(e){if(mr(e,ct._jsonSchema))return new ct(e.latitude,e.longitude)}}ct._jsonSchemaVersion="firestore/geoPoint/1.0",ct._jsonSchema={type:ue("string",ct._jsonSchemaVersion),latitude:ue("number"),longitude:ue("number")};class Qe{constructor(e){this._values=(e||[]).map(t=>t)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(r,s){if(r.length!==s.length)return!1;for(let i=0;i<r.length;++i)if(r[i]!==s[i])return!1;return!0}(this._values,e._values)}toJSON(){return{type:Qe._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(mr(e,Qe._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(t=>typeof t=="number"))return new Qe(e.vectorValues);throw new D(P.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}Qe._jsonSchemaVersion="firestore/vectorValue/1.0",Qe._jsonSchema={type:ue("string",Qe._jsonSchemaVersion),vectorValues:ue("object")};const iE=/^__.*__$/;class oE{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return this.fieldMask!==null?new Mt(e,this.data,this.fieldMask,t,this.fieldTransforms):new Pr(e,this.data,t,this.fieldTransforms)}}class Ql{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new Mt(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Yl(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw x(40011,{dataSource:n})}}class ea{constructor(e,t,r,s,i,a){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=s,i===void 0&&this.validatePath(),this.fieldTransforms=i||[],this.fieldMask=a||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(e){return new ea({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(e){const t=this.path?.child(e),r=this.contextWith({path:t,arrayElement:!1});return r.validatePathSegment(e),r}childContextForFieldPath(e){const t=this.path?.child(e),r=this.contextWith({path:t,arrayElement:!1});return r.validatePath(),r}childContextForArray(e){return this.contextWith({path:void 0,arrayElement:!0})}createError(e){return ei(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return this.fieldMask.find(t=>e.isPrefixOf(t))!==void 0||this.fieldTransforms.find(t=>e.isPrefixOf(t.field))!==void 0}validatePath(){if(this.path)for(let e=0;e<this.path.length;e++)this.validatePathSegment(this.path.get(e))}validatePathSegment(e){if(e.length===0)throw this.createError("Document fields must not be empty");if(Yl(this.dataSource)&&iE.test(e))throw this.createError('Document fields cannot begin and end with "__"')}}class aE{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=r||Hs(e)}createContext(e,t,r,s=!1){return new ea({dataSource:e,methodName:t,targetDoc:r,path:Ee.emptyPath(),arrayElement:!1,hasConverter:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ta(n){const e=n._freezeSettings(),t=Hs(n._databaseId);return new aE(n._databaseId,!!e.ignoreUndefinedProperties,t)}function cE(n,e,t,r,s,i={}){const a=n.createContext(i.merge||i.mergeFields?2:0,e,t,s);na("Data must be an object, but it was:",a,r);const c=Xl(r,a);let l,d;if(i.merge)l=new Fe(a.fieldMask),d=a.fieldTransforms;else if(i.mergeFields){const f=[];for(const m of i.mergeFields){const g=ln(e,m,t);if(!a.contains(g))throw new D(P.INVALID_ARGUMENT,`Field '${g}' is specified in your field mask but missing from your input data.`);th(f,g)||f.push(g)}l=new Fe(f),d=a.fieldTransforms.filter(m=>l.covers(m.field))}else l=null,d=a.fieldTransforms;return new oE(new Ce(c),l,d)}class Zs extends Zo{_toFieldTransform(e){if(e.dataSource!==2)throw e.dataSource===1?e.createError(`${this._methodName}() can only appear at the top level of your update data`):e.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Zs}}function uE(n,e,t,r){const s=n.createContext(1,e,t);na("Data must be an object, but it was:",s,r);const i=[],a=Ce.empty();Dt(r,(l,d)=>{const f=eh(e,l,t);d=Q(d);const m=s.childContextForFieldPath(f);if(d instanceof Zs)i.push(f);else{const g=Or(d,m);g!=null&&(i.push(f),a.set(f,g))}});const c=new Fe(i);return new Ql(a,c,s.fieldTransforms)}function lE(n,e,t,r,s,i){const a=n.createContext(1,e,t),c=[ln(e,r,t)],l=[s];if(i.length%2!=0)throw new D(P.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let g=0;g<i.length;g+=2)c.push(ln(e,i[g])),l.push(i[g+1]);const d=[],f=Ce.empty();for(let g=c.length-1;g>=0;--g)if(!th(d,c[g])){const R=c[g];let C=l[g];C=Q(C);const N=a.childContextForFieldPath(R);if(C instanceof Zs)d.push(R);else{const k=Or(C,N);k!=null&&(d.push(R),f.set(R,k))}}const m=new Fe(d);return new Ql(f,m,a.fieldTransforms)}function Jl(n,e,t,r=!1){return Or(t,n.createContext(r?4:3,e))}function Or(n,e){if(Zl(n=Q(n)))return na("Unsupported field value:",e,n),Xl(n,e);if(n instanceof Zo)return function(r,s){if(!Yl(s.dataSource))throw s.createError(`${r._methodName}() can only be used with update() and set()`);if(!s.path)throw s.createError(`${r._methodName}() is not currently supported inside arrays`);const i=r._toFieldTransform(s);i&&s.fieldTransforms.push(i)}(n,e),null;if(n===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),n instanceof Array){if(e.settings.arrayElement&&e.dataSource!==4)throw e.createError("Nested arrays are not supported");return function(r,s){const i=[];let a=0;for(const c of r){let l=Or(c,s.childContextForArray(a));l==null&&(l={nullValue:"NULL_VALUE"}),i.push(l),a++}return{arrayValue:{values:i}}}(n,e)}return function(r,s){if((r=Q(r))===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return zg(s.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){const i=ee.fromDate(r);return{timestampValue:js(s.serializer,i)}}if(r instanceof ee){const i=new ee(r.seconds,1e3*Math.floor(r.nanoseconds/1e3));return{timestampValue:js(s.serializer,i)}}if(r instanceof ct)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof ze)return{bytesValue:Ku(s.serializer,r._byteString)};if(r instanceof de){const i=s.databaseId,a=r.firestore._databaseId;if(!a.isEqual(i))throw s.createError(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:wo(r.firestore._databaseId||s.databaseId,r._key.path)}}if(r instanceof Qe)return function(a,c){const l=a instanceof Qe?a.toArray():a;return{mapValue:{fields:{[au]:{stringValue:cu},[Rs]:{arrayValue:{values:l.map(f=>{if(typeof f!="number")throw c.createError("VectorValues must only contain numeric values.");return _o(c.serializer,f)})}}}}}}(r,s);if(rl(r))return r._toProto(s.serializer);throw s.createError(`Unsupported field value: ${gs(r)}`)}(n,e)}function Xl(n,e){const t={};return eu(n)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):Dt(n,(r,s)=>{const i=Or(s,e.childContextForField(r));i!=null&&(t[r]=i)}),{mapValue:{fields:t}}}function Zl(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof ee||n instanceof ct||n instanceof ze||n instanceof de||n instanceof Zo||n instanceof Qe||rl(n))}function na(n,e,t){if(!Zl(t)||!Kc(t)){const r=gs(t);throw r==="an object"?e.createError(n+" a custom object"):e.createError(n+" "+r)}}function ln(n,e,t){if((e=Q(e))instanceof Xo)return e._internalPath;if(typeof e=="string")return eh(n,e);throw ei("Field path arguments must be of type string or ",n,!1,void 0,t)}const hE=new RegExp("[~\\*/\\[\\]]");function eh(n,e,t){if(e.search(hE)>=0)throw ei(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,t);try{return new Xo(...e.split("."))._internalPath}catch{throw ei(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,t)}}function ei(n,e,t,r,s){const i=r&&!r.isEmpty(),a=s!==void 0;let c=`Function ${e}() called with invalid data`;t&&(c+=" (via `toFirestore()`)"),c+=". ";let l="";return(i||a)&&(l+=" (found",i&&(l+=` in field ${r}`),a&&(l+=` in document ${s}`),l+=")"),new D(P.INVALID_ARGUMENT,c+n+l)}function th(n,e){return n.some(t=>t.isEqual(e))}class dE{convertValue(e,t="none"){switch(Lt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ae(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(Vt(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw x(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const r={};return Dt(e,(s,i)=>{r[s]=this.convertValue(i,t)}),r}convertVectorValue(e){const t=e.fields?.[Rs].arrayValue?.values?.map(r=>ae(r.doubleValue));return new Qe(t)}convertGeoPoint(e){return new ct(ae(e.latitude),ae(e.longitude))}convertArray(e,t){return(e.values||[]).map(r=>this.convertValue(r,t))}convertServerTimestamp(e,t){switch(t){case"previous":const r=Is(e);return r==null?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(_r(e));default:return null}}convertTimestamp(e){const t=Ot(e);return new ee(t.seconds,t.nanos)}convertDocumentKey(e,t){const r=X.fromString(e);Y(nl(r),9688,{name:e});const s=new yr(r.get(1),r.get(3)),i=new L(r.popFirst(5));return s.isEqual(t)||Et(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}class ti extends dE{constructor(e){super(),this.firestore=e}convertBytes(e){return new ze(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new de(this.firestore,null,t)}}const nh="@firebase/firestore",rh="4.10.0";function sh(n){return function(t,r){if(typeof t!="object"||t===null)return!1;const s=t;for(const i of r)if(i in s&&typeof s[i]=="function")return!0;return!1}(n,["next","error","complete"])}class fE{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class pE{constructor(e,t,r){this._userDataWriter=t,this._data=r,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}_fieldsProto(){return new Ce({mapValue:{fields:this._data}}).clone().value.mapValue.fields}}class ra{constructor(e,t,r,s,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=s,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new de(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){const e=new mE(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){return this._document?.data.clone().value.mapValue.fields??void 0}get(e){if(this._document){const t=this._document.data.field(ln("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}}class mE extends ra{data(){return super.data()}}function ih(n){if(n.limitType==="L"&&n.explicitOrderBy.length===0)throw new D(P.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class sa{}class ni extends sa{}function oh(n,e,...t){let r=[];e instanceof sa&&r.push(e),r=r.concat(t),function(i){const a=i.filter(l=>l instanceof $n).length,c=i.filter(l=>l instanceof Vr).length;if(a>1||a>0&&c>0)throw new D(P.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const s of r)n=s._apply(n);return n}class Vr extends ni{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new Vr(e,t,r)}_apply(e){const t=this._parse(e);return hh(e._query,t),new at(e.firestore,e.converter,go(e._query,t))}_parse(e){const t=ta(e.firestore);return function(i,a,c,l,d,f,m){let g;if(d.isKeyField()){if(f==="array-contains"||f==="array-contains-any")throw new D(P.INVALID_ARGUMENT,`Invalid Query. You can't perform '${f}' queries on documentId().`);if(f==="in"||f==="not-in"){lh(m,f);const C=[];for(const N of m)C.push(uh(l,i,N));g={arrayValue:{values:C}}}else g=uh(l,i,m)}else f!=="in"&&f!=="not-in"&&f!=="array-contains-any"||lh(m,f),g=Jl(c,a,m,f==="in"||f==="not-in");return le.create(d,f,g)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function ah(n,e,t){const r=e,s=ln("where",n);return Vr._create(s,r,t)}class $n extends sa{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new $n(e,t)}_parse(e){const t=this._queryConstraints.map(r=>r._parse(e)).filter(r=>r.getFilters().length>0);return t.length===1?t[0]:Ke.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return t.getFilters().length===0?e:(function(s,i){let a=s;const c=i.getFlattenedFilters();for(const l of c)hh(a,l),a=go(a,l)}(e._query,t),new at(e.firestore,e.converter,go(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}}function gE(...n){return n.forEach(e=>dh("or",e)),$n._create("or",n)}function _E(...n){return n.forEach(e=>dh("and",e)),$n._create("and",n)}class ia extends ni{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new ia(e,t)}_apply(e){const t=function(s,i,a){if(s.startAt!==null)throw new D(P.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(s.endAt!==null)throw new D(P.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new wr(i,a)}(e._query,this._field,this._direction);return new at(e.firestore,e.converter,Lg(e._query,t))}}function yE(n,e="asc"){const t=e,r=ln("orderBy",n);return ia._create(r,t)}class oa extends ni{constructor(e,t,r){super(),this.type=e,this._limit=t,this._limitType=r}static _create(e,t,r){return new oa(e,t,r)}_apply(e){return new at(e.firestore,e.converter,ks(e._query,this._limit,this._limitType))}}function ch(n){return ig("limit",n),oa._create("limit",n,"F")}class aa extends ni{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new aa(e,t,r)}_apply(e){const t=TE(e,this.type,this._docOrFields,this._inclusive);return new at(e.firestore,e.converter,Mg(e._query,t))}}function EE(...n){return aa._create("startAfter",n,!1)}function TE(n,e,t,r){if(t[0]=Q(t[0]),t[0]instanceof ra)return function(i,a,c,l,d){if(!l)throw new D(P.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${c}().`);const f=[];for(const m of Vn(i))if(m.field.isKeyField())f.push(Ps(a,l.key));else{const g=l.data.field(m.field);if(ws(g))throw new D(P.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+m.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(g===null){const R=m.field.canonicalString();throw new D(P.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${R}' (used as the orderBy) does not exist.`)}f.push(g)}return new On(f,d)}(n._query,n.firestore._databaseId,e,t[0]._document,r);{const s=ta(n.firestore);return function(a,c,l,d,f,m){const g=a.explicitOrderBy;if(f.length>g.length)throw new D(P.INVALID_ARGUMENT,`Too many arguments provided to ${d}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const R=[];for(let C=0;C<f.length;C++){const N=f[C];if(g[C].field.isKeyField()){if(typeof N!="string")throw new D(P.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${d}(), but got a ${typeof N}`);if(!mo(a)&&N.indexOf("/")!==-1)throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${d}() must be a plain document ID, but '${N}' contains a slash.`);const k=a.path.child(X.fromString(N));if(!L.isDocumentKey(k))throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${d}() must result in a valid document path, but '${k}' is not because it contains an odd number of segments.`);const F=new L(k);R.push(Ps(c,F))}else{const k=Jl(l,d,N);R.push(k)}}return new On(R,m)}(n._query,n.firestore._databaseId,s,e,t,r)}}function uh(n,e,t){if(typeof(t=Q(t))=="string"){if(t==="")throw new D(P.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!mo(e)&&t.indexOf("/")!==-1)throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${t}' contains a '/' character.`);const r=e.path.child(X.fromString(t));if(!L.isDocumentKey(r))throw new D(P.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 Ps(n,new L(r))}if(t instanceof de)return Ps(n,t._key);throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${gs(t)}.`)}function lh(n,e){if(!Array.isArray(n)||n.length===0)throw new D(P.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function hh(n,e){const t=function(s,i){for(const a of s)for(const c of a.getFlattenedFilters())if(i.indexOf(c.op)>=0)return c.op;return null}(n.filters,function(s){switch(s){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(e.op));if(t!==null)throw t===e.op?new D(P.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new D(P.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${t.toString()}' filters.`)}function dh(n,e){if(!(e instanceof Vr||e instanceof $n))throw new D(P.INVALID_ARGUMENT,`Function ${n}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}function wE(n,e,t){let r;return r=n?t&&(t.merge||t.mergeFields)?n.toFirestore(e,t):n.toFirestore(e):e,r}function IE(){return new fE("count")}function vE(n){return AE(n,{count:IE()})}function AE(n,e){const t=Ge(n.firestore,jt),r=jn(t),s=mg(e,(i,a)=>new e_(a,i.aggregateType,i._internalFieldPath));return Zy(r,n._query,s).then(i=>function(c,l,d){const f=new ti(c);return new pE(l,f,d)}(t,n,i))}class Lr{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class hn extends ra{constructor(e,t,r,s,i,a){super(e,t,r,s,a),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new ri(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){const r=this._document.data.field(ln("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new D(P.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");const e=this._document,t={};return t.type=hn._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?t:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),t.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),t)}}hn._jsonSchemaVersion="firestore/documentSnapshot/1.0",hn._jsonSchema={type:ue("string",hn._jsonSchemaVersion),bundleSource:ue("string","DocumentSnapshot"),bundleName:ue("string"),bundle:ue("string")};class ri extends hn{data(e={}){return super.data(e)}}class dn{constructor(e,t,r,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new Lr(s.hasPendingWrites,s.fromCache),this.query=r}get docs(){const e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,t){this._snapshot.docs.forEach(r=>{e.call(t,new ri(this._firestore,this._userDataWriter,r.key,r,new Lr(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new D(P.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,i){if(s._snapshot.oldDocs.isEmpty()){let a=0;return s._snapshot.docChanges.map(c=>{const l=new ri(s._firestore,s._userDataWriter,c.doc.key,c.doc,new Lr(s._snapshot.mutatedKeys.has(c.doc.key),s._snapshot.fromCache),s.query.converter);return c.doc,{type:"added",doc:l,oldIndex:-1,newIndex:a++}})}{let a=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(c=>i||c.type!==3).map(c=>{const l=new ri(s._firestore,s._userDataWriter,c.doc.key,c.doc,new Lr(s._snapshot.mutatedKeys.has(c.doc.key),s._snapshot.fromCache),s.query.converter);let d=-1,f=-1;return c.type!==0&&(d=a.indexOf(c.doc.key),a=a.delete(c.doc.key)),c.type!==1&&(a=a.add(c.doc),f=a.indexOf(c.doc.key)),{type:RE(c.type),doc:l,oldIndex:d,newIndex:f}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new D(P.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");const e={};e.type=dn._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=ro.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;const t=[],r=[],s=[];return this.docs.forEach(i=>{i._document!==null&&(t.push(i._document),r.push(this._userDataWriter.convertObjectMap(i._document.data.value.mapValue.fields,"previous")),s.push(i.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}}function RE(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return x(61501,{type:n})}}dn._jsonSchemaVersion="firestore/querySnapshot/1.0",dn._jsonSchema={type:ue("string",dn._jsonSchemaVersion),bundleSource:ue("string","QuerySnapshot"),bundleName:ue("string"),bundle:ue("string")};class bE{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ta(e)}set(e,t,r){this._verifyNotCommitted();const s=ca(e,this._firestore),i=wE(s.converter,t,r),a=cE(this._dataReader,"WriteBatch.set",s._key,i,s.converter!==null,r);return this._mutations.push(a.toMutation(s._key,$e.none())),this}update(e,t,r,...s){this._verifyNotCommitted();const i=ca(e,this._firestore);let a;return a=typeof(t=Q(t))=="string"||t instanceof Xo?lE(this._dataReader,"WriteBatch.update",i._key,t,r,s):uE(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(a.toMutation(i._key,$e.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=ca(e,this._firestore);return this._mutations=this._mutations.concat(new Us(t._key,$e.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new D(P.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function ca(n,e){if((n=Q(n)).firestore!==e)throw new D(P.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return n}function PE(n){n=Ge(n,de);const e=Ge(n.firestore,jt),t=jn(e);return Jy(t,n._key).then(r=>mh(e,n,r))}function SE(n){n=Ge(n,at);const e=Ge(n.firestore,jt),t=jn(e),r=new ti(e);return ih(n._query),Xy(t,n._query).then(s=>new dn(e,r,n,s))}function CE(n){return ph(Ge(n.firestore,jt),[new Us(n._key,$e.none())])}function fh(n,...e){n=Q(n);let t={includeMetadataChanges:!1,source:"default"},r=0;typeof e[r]!="object"||sh(e[r])||(t=e[r++]);const s={includeMetadataChanges:t.includeMetadataChanges,source:t.source};if(sh(e[r])){const d=e[r];e[r]=d.next?.bind(d),e[r+1]=d.error?.bind(d),e[r+2]=d.complete?.bind(d)}let i,a,c;if(n instanceof de)a=Ge(n.firestore,jt),c=Cs(n._key.path),i={next:d=>{e[r]&&e[r](mh(a,n,d))},error:e[r+1],complete:e[r+2]};else{const d=Ge(n,at);a=Ge(d.firestore,jt),c=d._query;const f=new ti(a);i={next:m=>{e[r]&&e[r](new dn(a,f,d,m))},error:e[r+1],complete:e[r+2]},ih(n._query)}const l=jn(a);return Yy(l,c,s,i)}function ph(n,e){const t=jn(n);return eE(t,e)}function mh(n,e,t){const r=t.docs.get(e._key),s=new ti(n);return new hn(n,s,e._key,r,new Lr(t.hasPendingWrites,t.fromCache),e.converter)}function kE(n){return n=Ge(n,jt),jn(n),new bE(n,e=>ph(n,e))}(function(e,t=!0){Gm(nn),St(new _t("firestore",(r,{instanceIdentifier:s,options:i})=>{const a=r.getProvider("app").getImmediate(),c=new jt(new Ym(r.getProvider("auth-internal")),new Zm(a,r.getProvider("app-check-internal")),yg(a,s),a);return i={useFetchStreams:t,...i},c._setSettings(i),c},"PUBLIC").setMultipleInstances(!0)),je(nh,rh,e),je(nh,rh,"esm2020")})();class gh{constructor(){this.subscribers=new Set}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notify(e){this.subscribers.forEach(t=>t(e))}get subscribersCount(){return this.subscribers.size}}const Ie=[];for(let n=0;n<256;++n)Ie.push((n+256).toString(16).slice(1));function NE(n,e=0){return(Ie[n[e+0]]+Ie[n[e+1]]+Ie[n[e+2]]+Ie[n[e+3]]+"-"+Ie[n[e+4]]+Ie[n[e+5]]+"-"+Ie[n[e+6]]+Ie[n[e+7]]+"-"+Ie[n[e+8]]+Ie[n[e+9]]+"-"+Ie[n[e+10]]+Ie[n[e+11]]+Ie[n[e+12]]+Ie[n[e+13]]+Ie[n[e+14]]+Ie[n[e+15]]).toLowerCase()}let ua;const DE=new Uint8Array(16);function OE(){if(!ua){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ua=crypto.getRandomValues.bind(crypto)}return ua(DE)}const VE=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),_h={randomUUID:VE};function LE(n,e,t){n=n||{};const r=n.random??n.rng?.()??OE();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,NE(r)}function ME(n,e,t){return _h.randomUUID&&!n?_h.randomUUID():LE(n)}var xE=Object.defineProperty,UE=(n,e,t,r)=>{for(var s=void 0,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(e,t,s)||s);return s&&xE(e,t,s),s},ce;const yh=(ce=class{static registerFactory(n,e,t,r=!1){this._factoryMap[n]={factory:e,annotation:t,isLegacy:r}}static classFactory(n){if(!n)throw new Error("You should provide a class name.");if(!this._factoryMap[n])throw new Error(`You should register class ${n} prior to use.`);return this._factoryMap[n].factory}static registeredClasses(){return Object.entries(this._factoryMap).filter(([,n])=>!n.isLegacy).map(([n])=>n)}static registeredClassesAndLegacyNames(){return Object.keys(this._factoryMap)}static classesExtending(n){return Object.entries(this._factoryMap).filter(([,e])=>new e.factory instanceof n&&!e.isLegacy).map(([e])=>e)}static annotations(n){if(n instanceof ce?n=n.className:typeof n=="string"||(n=new n().className),!this._factoryMap[n])throw new Error(`You should register class ${n} prior to use.`);return this._factoryMap[n].annotation}constructor(n=ME()){this._id=n}get className(){return this.__className}setId(n){this._id=n}get id(){return this._id}afterDeserialize(){}beforeSerialize(){}getPersistentProperties(){return this._persistentProperties?this._persistentProperties.map(n=>({...n,name:n.name.slice(1)})):[]}getPropInfo(n){const e=this.getPersistentProperties().find(t=>t.name===n);if(!e)throw new Error(`Property "${n}" has not been registered.`);return e}isRequired(n){return this.getPropInfo(n).validator!=null}isPropValueValid(n){const e=this.getPropInfo(n);return e.validator?e.validator(this[e.name],e,this):!0}clone(n){const e=n.toObject();return delete e.id,this.fromObject(e)}fromObject(n){return this.fromObj(n),this.afterDeserialize(),this}fromObj(n){return this._persistentProperties?(this._persistentProperties.forEach(e=>{const t=this.removeUnderscore(e),r=n[t];r!=null&&(this[e.name]=this.fromDeepObject(r))}),this):this}toObject(){const n={},e=this.toObj(n);return this.pushDocument(n,this.className,e),{...e,__rootCollections:n}}toObj(n){if(!this._persistentProperties)return{};this.beforeSerialize();const e={};if(!this.className)throw new Error(`You should register \`${this.constructor.name||this.toString()||"this"}\` class prior to streaming it.`);return this._persistentProperties.forEach(t=>{const r=this[t.name],s=this.removeUnderscore(t);r!=null&&(t.isReference?e[s]=this.toReferenceObj(t,n):e[s]=this.toDeepObj(r,n),t.searchableArray&&(e[ce.searchableArrayNameFor(s)]=r.map(i=>i.id)))}),e.__className=this.className,e}static searchableArrayNameFor(n){return`__${n}_searchable`}fromDeepObject(n){if(n==null)return n;if(Array.isArray(n))return n.map(e=>this.fromDeepObject(e));if(n.__documentReference){const e=n,t=ce.createInstance(e);return t.__documentReference=n.__documentReference,t}if(n.__className)return ce.createInstance(n);if(typeof n=="object"){const e={};return Object.entries(n).forEach(([t,r])=>e[t]=this.fromDeepObject(r)),e}return n}toDeepObj(n,e){if(n!=null){if(Array.isArray(n))return n.map(t=>this.toDeepObj(t,e));if(n.__documentReference)return n;if(n instanceof ce)return n.toObj(e);if(typeof n=="object"){const t={};return Object.entries(n).forEach(([r,s])=>t[r]=this.toDeepObj(s,e)),t}return n}}static collectionPath(n,e,t){let r;return typeof e.storeInCollection=="function"?r=e.storeInCollection(n,e,t):r=e.storeInCollection??n.className,r}toReferenceObj(n,e){const t=this[n.name];return Array.isArray(t)?t.map(r=>(n.isPureReference||this.pushDocument(e,ce.collectionPath(r,n),r),this.buildRefObject(r,ce.collectionPath(r,n),n.cachedProps))):(n.isPureReference||this.pushDocument(e,ce.collectionPath(t,n),t),this.buildRefObject(t,ce.collectionPath(t,n),n.cachedProps))}buildRefObject(n,e,t){const r=t?.reduce((s,i)=>(n[i]!==void 0&&(s[i]=n[i]),s),{});return{id:n.id,__className:n.className||n.__className,__documentReference:{storedInCollection:e},...r}}pushDocument(n,e,t){if("__documentReference"in t&&t.__documentReference)return;n[e]||(n[e]=[]);const r=this.toDeepObj(t,n);n[e].push(r)}removeUnderscore(n){return n.name.slice(1)}static createReference(n){const e=ce.createInstance(n);return e.__documentReference=n.__documentReference||{storedInCollection:e.className},e}static createInstance(n){if(typeof n=="string")return new(ce.classFactory(n));try{return new(ce.classFactory(n.__className))().fromObject(n)}catch(e){const t=Object.entries(n).filter(([r,s])=>s!=null&&typeof s!="function").map(([r,s])=>`${r}: ${s}`).join(`,
35
+ )`}copy(e,t){const r=new Bn;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class Rl{constructor(){this.ga=new se(L.comparator)}track(e){const t=e.doc.key,r=this.ga.get(t);r?e.type!==0&&r.type===3?this.ga=this.ga.insert(t,e):e.type===3&&r.type!==1?this.ga=this.ga.insert(t,{type:r.type,doc:e.doc}):e.type===2&&r.type===2?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):e.type===2&&r.type===0?this.ga=this.ga.insert(t,{type:0,doc:e.doc}):e.type===1&&r.type===0?this.ga=this.ga.remove(t):e.type===1&&r.type===2?this.ga=this.ga.insert(t,{type:1,doc:r.doc}):e.type===0&&r.type===1?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):x(63341,{Vt:e,pa:r}):this.ga=this.ga.insert(t,e)}ya(){const e=[];return this.ga.inorderTraversal((t,r)=>{e.push(r)}),e}}class qn{constructor(e,t,r,s,i,a,c,l,d){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=s,this.mutatedKeys=i,this.fromCache=a,this.syncStateChanged=c,this.excludesMetadataChanges=l,this.hasCachedResults=d}static fromInitialDocuments(e,t,r,s,i){const a=[];return t.forEach(c=>{a.push({type:0,doc:c})}),new qn(e,t,Bn.emptySet(t),a,r,s,!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)&&Ns(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++)if(t[s].type!==r[s].type||!t[s].doc.isEqual(r[s].doc))return!1;return!0}}class Ay{constructor(){this.wa=void 0,this.ba=[]}Sa(){return this.ba.some(e=>e.Da())}}class Ry{constructor(){this.queries=bl(),this.onlineState="Unknown",this.Ca=new Set}terminate(){(function(t,r){const s=F(t),i=s.queries;s.queries=bl(),i.forEach((a,c)=>{for(const l of c.ba)l.onError(r)})})(this,new D(P.ABORTED,"Firestore shutting down"))}}function bl(){return new an(n=>Ru(n),Ns)}async function Bo(n,e){const t=F(n);let r=3;const s=e.query;let i=t.queries.get(s);i?!i.Sa()&&e.Da()&&(r=2):(i=new Ay,r=e.Da()?0:1);try{switch(r){case 0:i.wa=await t.onListen(s,!0);break;case 1:i.wa=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(a){const c=Fo(a,`Initialization of query '${Ln(e.query)}' failed`);return void e.onError(c)}t.queries.set(s,i),i.ba.push(e),e.va(t.onlineState),i.wa&&e.Fa(i.wa)&&jo(t)}async function qo(n,e){const t=F(n),r=e.query;let s=3;const i=t.queries.get(r);if(i){const a=i.ba.indexOf(e);a>=0&&(i.ba.splice(a,1),i.ba.length===0?s=e.Da()?0:1:!i.Sa()&&e.Da()&&(s=2))}switch(s){case 0:return t.queries.delete(r),t.onUnlisten(r,!0);case 1:return t.queries.delete(r),t.onUnlisten(r,!1);case 2:return t.onLastRemoteStoreUnlisten(r);default:return}}function by(n,e){const t=F(n);let r=!1;for(const s of e){const i=s.query,a=t.queries.get(i);if(a){for(const c of a.ba)c.Fa(s)&&(r=!0);a.wa=s}}r&&jo(t)}function Py(n,e,t){const r=F(n),s=r.queries.get(e);if(s)for(const i of s.ba)i.onError(t);r.queries.delete(e)}function jo(n){n.Ca.forEach(e=>{e.next()})}var $o,Pl;(Pl=$o||($o={})).Ma="default",Pl.Cache="cache";class zo{constructor(e,t,r){this.query=e,this.xa=t,this.Oa=!1,this.Na=null,this.onlineState="Unknown",this.options=r||{}}Fa(e){if(!this.options.includeMetadataChanges){const r=[];for(const s of e.docChanges)s.type!==3&&r.push(s);e=new qn(e.query,e.docs,e.oldDocs,r,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Oa?this.Ba(e)&&(this.xa.next(e),t=!0):this.La(e,this.onlineState)&&(this.ka(e),t=!0),this.Na=e,t}onError(e){this.xa.error(e)}va(e){this.onlineState=e;let t=!1;return this.Na&&!this.Oa&&this.La(this.Na,e)&&(this.ka(this.Na),t=!0),t}La(e,t){if(!e.fromCache||!this.Da())return!0;const r=t!=="Offline";return(!this.options.Ka||!r)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}Ba(e){if(e.docChanges.length>0)return!0;const t=this.Na&&this.Na.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}ka(e){e=qn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Oa=!0,this.xa.next(e)}Da(){return this.options.source!==$o.Cache}}class Cl{constructor(e){this.key=e}}class Sl{constructor(e){this.key=e}}class Cy{constructor(e,t){this.query=e,this.Za=t,this.Xa=null,this.hasCachedResults=!1,this.current=!1,this.Ya=G(),this.mutatedKeys=G(),this.eu=bu(e),this.tu=new Bn(this.eu)}get nu(){return this.Za}ru(e,t){const r=t?t.iu:new Rl,s=t?t.tu:this.tu;let i=t?t.mutatedKeys:this.mutatedKeys,a=s,c=!1;const l=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,d=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal((f,m)=>{const _=s.get(f),R=Ds(this.query,m)?m:null,S=!!_&&this.mutatedKeys.has(_.key),N=!!R&&(R.hasLocalMutations||this.mutatedKeys.has(R.key)&&R.hasCommittedMutations);let k=!1;_&&R?_.data.isEqual(R.data)?S!==N&&(r.track({type:3,doc:R}),k=!0):this.su(_,R)||(r.track({type:2,doc:R}),k=!0,(l&&this.eu(R,l)>0||d&&this.eu(R,d)<0)&&(c=!0)):!_&&R?(r.track({type:0,doc:R}),k=!0):_&&!R&&(r.track({type:1,doc:_}),k=!0,(l||d)&&(c=!0)),k&&(R?(a=a.add(R),i=N?i.add(f):i.delete(f)):(a=a.delete(f),i=i.delete(f)))}),this.query.limit!==null)for(;a.size>this.query.limit;){const f=this.query.limitType==="F"?a.last():a.first();a=a.delete(f.key),i=i.delete(f.key),r.track({type:1,doc:f})}return{tu:a,iu:r,Ss:c,mutatedKeys:i}}su(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,s){const i=this.tu;this.tu=e.tu,this.mutatedKeys=e.mutatedKeys;const a=e.iu.ya();a.sort((f,m)=>function(R,S){const N=k=>{switch(k){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return x(20277,{Vt:k})}};return N(R)-N(S)}(f.type,m.type)||this.eu(f.doc,m.doc)),this.ou(r),s=s??!1;const c=t&&!s?this._u():[],l=this.Ya.size===0&&this.current&&!s?1:0,d=l!==this.Xa;return this.Xa=l,a.length!==0||d?{snapshot:new qn(this.query,e.tu,i,a,e.mutatedKeys,l===0,d,!1,!!r&&r.resumeToken.approximateByteSize()>0),au:c}:{au:c}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({tu:this.tu,iu:new Rl,mutatedKeys:this.mutatedKeys,Ss:!1},!1)):{au:[]}}uu(e){return!this.Za.has(e)&&!!this.tu.has(e)&&!this.tu.get(e).hasLocalMutations}ou(e){e&&(e.addedDocuments.forEach(t=>this.Za=this.Za.add(t)),e.modifiedDocuments.forEach(t=>{}),e.removedDocuments.forEach(t=>this.Za=this.Za.delete(t)),this.current=e.current)}_u(){if(!this.current)return[];const e=this.Ya;this.Ya=G(),this.tu.forEach(r=>{this.uu(r.key)&&(this.Ya=this.Ya.add(r.key))});const t=[];return e.forEach(r=>{this.Ya.has(r)||t.push(new Sl(r))}),this.Ya.forEach(r=>{e.has(r)||t.push(new Cl(r))}),t}cu(e){this.Za=e.ks,this.Ya=G();const t=this.ru(e.documents);return this.applyChanges(t,!0)}lu(){return qn.fromInitialDocuments(this.query,this.tu,this.mutatedKeys,this.Xa===0,this.hasCachedResults)}}const Ho="SyncEngine";class Sy{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class ky{constructor(e){this.key=e,this.hu=!1}}class Ny{constructor(e,t,r,s,i,a){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=a,this.Pu={},this.Tu=new an(c=>Ru(c),Ns),this.Iu=new Map,this.Eu=new Set,this.Ru=new se(L.comparator),this.Au=new Map,this.Vu=new bo,this.du={},this.mu=new Map,this.fu=xn.ar(),this.onlineState="Unknown",this.gu=void 0}get isPrimaryClient(){return this.gu===!0}}async function Dy(n,e,t=!0){const r=xl(n);let s;const i=r.Tu.get(e);return i?(r.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.lu()):s=await kl(r,e,t,!0),s}async function Oy(n,e){const t=xl(n);await kl(t,e,!0,!1)}async function kl(n,e,t,r){const s=await X_(n.localStore,it(e)),i=s.targetId,a=n.sharedClientState.addLocalQueryTarget(i,t);let c;return r&&(c=await Vy(n,e,i,a==="current",s.resumeToken)),n.isPrimaryClient&&t&&yl(n.remoteStore,s),c}async function Vy(n,e,t,r,s){n.pu=(m,_,R)=>async function(N,k,U,$){let j=k.view.ru(U);j.Ss&&(j=await hl(N.localStore,k.query,!1).then(({documents:w})=>k.view.ru(w,j)));const Q=$&&$.targetChanges.get(k.targetId),_e=$&&$.targetMismatches.get(k.targetId)!=null,re=k.view.applyChanges(j,N.isPrimaryClient,Q,_e);return Ml(N,k.targetId,re.au),re.snapshot}(n,m,_,R);const i=await hl(n.localStore,e,!0),a=new Cy(e,i.ks),c=a.ru(i.documents),l=Sr.createSynthesizedTargetChangeForCurrentChange(t,r&&n.onlineState!=="Offline",s),d=a.applyChanges(c,n.isPrimaryClient,l);Ml(n,t,d.au);const f=new Sy(e,t,a);return n.Tu.set(e,f),n.Iu.has(t)?n.Iu.get(t).push(e):n.Iu.set(t,[e]),d.snapshot}async function Ly(n,e,t){const r=F(n),s=r.Tu.get(e),i=r.Iu.get(s.targetId);if(i.length>1)return r.Iu.set(s.targetId,i.filter(a=>!Ns(a,e))),void r.Tu.delete(e);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(s.targetId),r.sharedClientState.isActiveQueryTarget(s.targetId)||await ko(r.localStore,s.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(s.targetId),t&&Vo(r.remoteStore,s.targetId),Wo(r,s.targetId)}).catch(Sn)):(Wo(r,s.targetId),await ko(r.localStore,s.targetId,!0))}async function My(n,e){const t=F(n),r=t.Tu.get(e),s=t.Iu.get(r.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(r.targetId),Vo(t.remoteStore,r.targetId))}async function xy(n,e,t){const r=zy(n);try{const s=await function(a,c){const l=F(a),d=ee.now(),f=c.reduce((R,S)=>R.add(S.key),G());let m,_;return l.persistence.runTransaction("Locally write mutations","readwrite",R=>{let S=Tt(),N=G();return l.xs.getEntries(R,f).next(k=>{S=k,S.forEach((U,$)=>{$.isValidDocument()||(N=N.add(U))})}).next(()=>l.localDocuments.getOverlayedDocuments(R,S)).next(k=>{m=k;const U=[];for(const $ of c){const j=Yg($,m.get($.key).overlayedDocument);j!=null&&U.push(new Mt($.key,j,fu(j.value.mapValue),$e.exists(!0)))}return l.mutationQueue.addMutationBatch(R,d,U,c)}).next(k=>{_=k;const U=k.applyToLocalDocumentSet(m,N);return l.documentOverlayCache.saveOverlays(R,k.batchId,U)})}).then(()=>({batchId:_.batchId,changes:Cu(m)}))}(r.localStore,e);r.sharedClientState.addPendingMutation(s.batchId),function(a,c,l){let d=a.du[a.currentUser.toKey()];d||(d=new se(W)),d=d.insert(c,l),a.du[a.currentUser.toKey()]=d}(r,s.batchId,t),await Dr(r,s.changes),await Ks(r.remoteStore)}catch(s){const i=Fo(s,"Failed to persist write");t.reject(i)}}async function Nl(n,e){const t=F(n);try{const r=await Q_(t.localStore,e);e.targetChanges.forEach((s,i)=>{const a=t.Au.get(i);a&&(J(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1,22616),s.addedDocuments.size>0?a.hu=!0:s.modifiedDocuments.size>0?J(a.hu,14607):s.removedDocuments.size>0&&(J(a.hu,42227),a.hu=!1))}),await Dr(t,r,e)}catch(r){await Sn(r)}}function Dl(n,e,t){const r=F(n);if(r.isPrimaryClient&&t===0||!r.isPrimaryClient&&t===1){const s=[];r.Tu.forEach((i,a)=>{const c=a.view.va(e);c.snapshot&&s.push(c.snapshot)}),function(a,c){const l=F(a);l.onlineState=c;let d=!1;l.queries.forEach((f,m)=>{for(const _ of m.ba)_.va(c)&&(d=!0)}),d&&jo(l)}(r.eventManager,e),s.length&&r.Pu.J_(s),r.onlineState=e,r.isPrimaryClient&&r.sharedClientState.setOnlineState(e)}}async function Uy(n,e,t){const r=F(n);r.sharedClientState.updateQueryState(e,"rejected",t);const s=r.Au.get(e),i=s&&s.key;if(i){let a=new se(L.comparator);a=a.insert(i,be.newNoDocument(i,B.min()));const c=G().add(i),l=new Fs(B.min(),new Map,new se(W),a,c);await Nl(r,l),r.Ru=r.Ru.remove(i),r.Au.delete(e),Go(r)}else await ko(r.localStore,e,!1).then(()=>Wo(r,e,t)).catch(Sn)}async function Fy(n,e){const t=F(n),r=e.batch.batchId;try{const s=await K_(t.localStore,e);Vl(t,r,null),Ol(t,r),t.sharedClientState.updateMutationState(r,"acknowledged"),await Dr(t,s)}catch(s){await Sn(s)}}async function By(n,e,t){const r=F(n);try{const s=await function(a,c){const l=F(a);return l.persistence.runTransaction("Reject batch","readwrite-primary",d=>{let f;return l.mutationQueue.lookupMutationBatch(d,c).next(m=>(J(m!==null,37113),f=m.keys(),l.mutationQueue.removeMutationBatch(d,m))).next(()=>l.mutationQueue.performConsistencyCheck(d)).next(()=>l.documentOverlayCache.removeOverlaysForBatchId(d,f,c)).next(()=>l.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(d,f)).next(()=>l.localDocuments.getDocuments(d,f))})}(r.localStore,e);Vl(r,e,t),Ol(r,e),r.sharedClientState.updateMutationState(e,"rejected",t),await Dr(r,s)}catch(s){await Sn(s)}}function Ol(n,e){(n.mu.get(e)||[]).forEach(t=>{t.resolve()}),n.mu.delete(e)}function Vl(n,e,t){const r=F(n);let s=r.du[r.currentUser.toKey()];if(s){const i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),r.du[r.currentUser.toKey()]=s}}function Wo(n,e,t=null){n.sharedClientState.removeLocalQueryTarget(e);for(const r of n.Iu.get(e))n.Tu.delete(r),t&&n.Pu.yu(r,t);n.Iu.delete(e),n.isPrimaryClient&&n.Vu.Gr(e).forEach(r=>{n.Vu.containsKey(r)||Ll(n,r)})}function Ll(n,e){n.Eu.delete(e.path.canonicalString());const t=n.Ru.get(e);t!==null&&(Vo(n.remoteStore,t),n.Ru=n.Ru.remove(e),n.Au.delete(t),Go(n))}function Ml(n,e,t){for(const r of t)r instanceof Cl?(n.Vu.addReference(r.key,e),qy(n,r)):r instanceof Sl?(V(Ho,"Document no longer in limbo: "+r.key),n.Vu.removeReference(r.key,e),n.Vu.containsKey(r.key)||Ll(n,r.key)):x(19791,{wu:r})}function qy(n,e){const t=e.key,r=t.path.canonicalString();n.Ru.get(t)||n.Eu.has(r)||(V(Ho,"New document in limbo: "+t),n.Eu.add(r),Go(n))}function Go(n){for(;n.Eu.size>0&&n.Ru.size<n.maxConcurrentLimboResolutions;){const e=n.Eu.values().next().value;n.Eu.delete(e);const t=new L(X.fromString(e)),r=n.fu.next();n.Au.set(r,new ky(t)),n.Ru=n.Ru.insert(t,r),yl(n.remoteStore,new Ut(it(Ss(t.path)),r,"TargetPurposeLimboResolution",_s.ce))}}async function Dr(n,e,t){const r=F(n),s=[],i=[],a=[];r.Tu.isEmpty()||(r.Tu.forEach((c,l)=>{a.push(r.pu(l,e,t).then(d=>{if((d||t)&&r.isPrimaryClient){const f=d?!d.fromCache:t?.targetChanges.get(l.targetId)?.current;r.sharedClientState.updateQueryState(l.targetId,f?"current":"not-current")}if(d){s.push(d);const f=Co.Es(l.targetId,d);i.push(f)}}))}),await Promise.all(a),r.Pu.J_(s),await async function(l,d){const f=F(l);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",m=>C.forEach(d,_=>C.forEach(_.Ts,R=>f.persistence.referenceDelegate.addReference(m,_.targetId,R)).next(()=>C.forEach(_.Is,R=>f.persistence.referenceDelegate.removeReference(m,_.targetId,R)))))}catch(m){if(!kn(m))throw m;V(So,"Failed to update sequence numbers: "+m)}for(const m of d){const _=m.targetId;if(!m.fromCache){const R=f.vs.get(_),S=R.snapshotVersion,N=R.withLastLimboFreeSnapshotVersion(S);f.vs=f.vs.insert(_,N)}}}(r.localStore,i))}async function jy(n,e){const t=F(n);if(!t.currentUser.isEqual(e)){V(Ho,"User change. New user:",e.toKey());const r=await ul(t.localStore,e);t.currentUser=e,function(i,a){i.mu.forEach(c=>{c.forEach(l=>{l.reject(new D(P.CANCELLED,a))})}),i.mu.clear()}(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,r.removedBatchIds,r.addedBatchIds),await Dr(t,r.Ns)}}function $y(n,e){const t=F(n),r=t.Au.get(e);if(r&&r.hu)return G().add(r.key);{let s=G();const i=t.Iu.get(e);if(!i)return s;for(const a of i){const c=t.Tu.get(a);s=s.unionWith(c.view.nu)}return s}}function xl(n){const e=F(n);return e.remoteStore.remoteSyncer.applyRemoteEvent=Nl.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=$y.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=Uy.bind(null,e),e.Pu.J_=by.bind(null,e.eventManager),e.Pu.yu=Py.bind(null,e.eventManager),e}function zy(n){const e=F(n);return e.remoteStore.remoteSyncer.applySuccessfulWrite=Fy.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=By.bind(null,e),e}class Qs{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=Hs(e.databaseInfo.databaseId),this.sharedClientState=this.Du(e),this.persistence=this.Cu(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Fu(e,this.localStore),this.indexBackfillerScheduler=this.Mu(e,this.localStore)}Fu(e,t){return null}Mu(e,t){return null}vu(e){return G_(this.persistence,new z_,e.initialUser,this.serializer)}Cu(e){return new cl(Po.Vi,this.serializer)}Du(e){return new ey}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}Qs.provider={build:()=>new Qs};class Hy extends Qs{constructor(e){super(),this.cacheSizeBytes=e}Fu(e,t){J(this.persistence.referenceDelegate instanceof $s,46915);const r=this.persistence.referenceDelegate.garbageCollector;return new S_(r,e.asyncQueue,t)}Cu(e){const t=this.cacheSizeBytes!==void 0?Oe.withCacheSize(this.cacheSizeBytes):Oe.DEFAULT;return new cl(r=>$s.Vi(r,t),this.serializer)}}class Ko{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=r=>Dl(this.syncEngine,r,1),this.remoteStore.remoteSyncer.handleCredentialChange=jy.bind(null,this.syncEngine),await vy(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function(){return new Ry}()}createDatastore(e){const t=Hs(e.databaseInfo.databaseId),r=iy(e.databaseInfo);return ly(e.authCredentials,e.appCheckCredentials,r,t)}createRemoteStore(e){return function(r,s,i,a,c){return new dy(r,s,i,a,c)}(this.localStore,this.datastore,e.asyncQueue,t=>Dl(this.syncEngine,t,0),function(){return pl.v()?new pl:new ty}())}createSyncEngine(e,t){return function(s,i,a,c,l,d,f){const m=new Ny(s,i,a,c,l,d);return f&&(m.gu=!0),m}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){await async function(t){const r=F(t);V(un,"RemoteStore shutting down."),r.Ea.add(5),await Nr(r),r.Aa.shutdown(),r.Va.set("Unknown")}(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}Ko.provider={build:()=>new Ko};class Qo{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ou(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ou(this.observer.error,e):Et("Uncaught Error in snapshot listener:",e.toString()))}Nu(){this.muted=!0}Ou(e,t){setTimeout(()=>{this.muted||e(t)},0)}}const Bt="FirestoreClient";class Wy{constructor(e,t,r,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this._databaseInfo=s,this.user=Re.UNAUTHENTICATED,this.clientId=ro.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async a=>{V(Bt,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a}),this.appCheckCredentials.start(r,a=>(V(Bt,"Received new app check token=",a),this.appCheckCredentialListener(a,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this._databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const e=new nt;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const r=Fo(t,"Failed to shutdown persistence");e.reject(r)}}),e.promise}}async function Yo(n,e){n.asyncQueue.verifyOperationInProgress(),V(Bt,"Initializing OfflineComponentProvider");const t=n.configuration;await e.initialize(t);let r=t.initialUser;n.setCredentialChangeListener(async s=>{r.isEqual(s)||(await ul(e.localStore,s),r=s)}),e.persistence.setDatabaseDeletedListener(()=>n.terminate()),n._offlineComponents=e}async function Ul(n,e){n.asyncQueue.verifyOperationInProgress();const t=await Gy(n);V(Bt,"Initializing OnlineComponentProvider"),await e.initialize(t,n.configuration),n.setCredentialChangeListener(r=>Al(e.remoteStore,r)),n.setAppCheckTokenChangeListener((r,s)=>Al(e.remoteStore,s)),n._onlineComponents=e}async function Gy(n){if(!n._offlineComponents)if(n._uninitializedComponentsProvider){V(Bt,"Using user provided OfflineComponentProvider");try{await Yo(n,n._uninitializedComponentsProvider._offline)}catch(e){const t=e;if(!function(s){return s.name==="FirebaseError"?s.code===P.FAILED_PRECONDITION||s.code===P.UNIMPLEMENTED:!(typeof DOMException<"u"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11}(t))throw t;sn("Error using user provided cache. Falling back to memory cache: "+t),await Yo(n,new Qs)}}else V(Bt,"Using default OfflineComponentProvider"),await Yo(n,new Hy(void 0));return n._offlineComponents}async function Jo(n){return n._onlineComponents||(n._uninitializedComponentsProvider?(V(Bt,"Using user provided OnlineComponentProvider"),await Ul(n,n._uninitializedComponentsProvider._online)):(V(Bt,"Using default OnlineComponentProvider"),await Ul(n,new Ko))),n._onlineComponents}function Ky(n){return Jo(n).then(e=>e.syncEngine)}function Qy(n){return Jo(n).then(e=>e.datastore)}async function Ys(n){const e=await Jo(n),t=e.eventManager;return t.onListen=Dy.bind(null,e.syncEngine),t.onUnlisten=Ly.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=Oy.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=My.bind(null,e.syncEngine),t}function Yy(n,e,t,r){const s=new Qo(r),i=new zo(e,s,t);return n.asyncQueue.enqueueAndForget(async()=>Bo(await Ys(n),i)),()=>{s.Nu(),n.asyncQueue.enqueueAndForget(async()=>qo(await Ys(n),i))}}function Jy(n,e,t={}){const r=new nt;return n.asyncQueue.enqueueAndForget(async()=>function(i,a,c,l,d){const f=new Qo({next:_=>{f.Nu(),a.enqueueAndForget(()=>qo(i,m));const R=_.docs.has(c);!R&&_.fromCache?d.reject(new D(P.UNAVAILABLE,"Failed to get document because the client is offline.")):R&&_.fromCache&&l&&l.source==="server"?d.reject(new D(P.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.)')):d.resolve(_)},error:_=>d.reject(_)}),m=new zo(Ss(c.path),f,{includeMetadataChanges:!0,Ka:!0});return Bo(i,m)}(await Ys(n),n.asyncQueue,e,t,r)),r.promise}function Xy(n,e,t={}){const r=new nt;return n.asyncQueue.enqueueAndForget(async()=>function(i,a,c,l,d){const f=new Qo({next:_=>{f.Nu(),a.enqueueAndForget(()=>qo(i,m)),_.fromCache&&l.source==="server"?d.reject(new D(P.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.)')):d.resolve(_)},error:_=>d.reject(_)}),m=new zo(c,f,{includeMetadataChanges:!0,Ka:!0});return Bo(i,m)}(await Ys(n),n.asyncQueue,e,t,r)),r.promise}function Zy(n,e,t){const r=new nt;return n.asyncQueue.enqueueAndForget(async()=>{try{const s=await Qy(n);r.resolve(async function(a,c,l){const d=F(a),{request:f,gt:m,parent:_}=g_(d.serializer,Vg(c),l);d.connection.Ko||delete f.parent;const R=(await d.jo("RunAggregationQuery",d.serializer.databaseId,_,f,1)).filter(N=>!!N.result);J(R.length===1,64727);const S=R[0].result?.aggregateFields;return Object.keys(S).reduce((N,k)=>(N[m[k]]=S[k],N),{})}(s,e,t))}catch(s){r.reject(s)}}),r.promise}function eE(n,e){const t=new nt;return n.asyncQueue.enqueueAndForget(async()=>xy(await Ky(n),e,t)),t.promise}function Fl(n){const e={};return n.timeoutSeconds!==void 0&&(e.timeoutSeconds=n.timeoutSeconds),e}const tE="ComponentProvider",Bl=new Map;function nE(n,e,t,r,s){return new _g(n,e,t,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Fl(s.experimentalLongPollingOptions),s.useFetchStreams,s.isUsingEmulator,r)}const ql="firestore.googleapis.com",jl=!0;class $l{constructor(e){if(e.host===void 0){if(e.ssl!==void 0)throw new D(P.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=ql,this.ssl=jl}else this.host=e.host,this.ssl=e.ssl??jl;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=il;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<P_)throw new D(P.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}sg("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Fl(e.experimentalLongPollingOptions??{}),function(r){if(r.timeoutSeconds!==void 0){if(isNaN(r.timeoutSeconds))throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (must not be NaN)`);if(r.timeoutSeconds<5)throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (minimum allowed value is 5)`);if(r.timeoutSeconds>30)throw new D(P.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function(r,s){return r.timeoutSeconds===s.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Js{constructor(e,t,r,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new $l({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new D(P.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 this._terminateTask!=="notTerminated"}_setSettings(e){if(this._settingsFrozen)throw new D(P.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 $l(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=function(r){if(!r)return new Km;switch(r.type){case"firstParty":return new Xm(r.sessionIndex||"0",r.iamToken||null,r.authTokenFactory||null);case"provider":return r.client;default:throw new D(P.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(t){const r=Bl.get(t);r&&(V(tE,"Removing Datastore"),Bl.delete(t),r.terminate())}(this),Promise.resolve()}}function zl(n,e,t,r={}){n=Ge(n,Js);const s=tt(e),i=n._getSettings(),a={...i,emulatorOptions:n._getEmulatorOptions()},c=`${e}:${t}`;s&&(ls(`https://${c}`),hs("Firestore",!0)),i.host!==ql&&i.host!==c&&sn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");const l={...i,host:c,ssl:s,emulatorOptions:r};if(!en(l,a)&&(n._setSettings(l),r.mockUserToken)){let d,f;if(typeof r.mockUserToken=="string")d=r.mockUserToken,f=Re.MOCK_USER;else{d=yc(r.mockUserToken,n._app?.options.projectId);const m=r.mockUserToken.sub||r.mockUserToken.user_id;if(!m)throw new D(P.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");f=new Re(m)}n._authCredentials=new Qm(new jc(d,f))}}class at{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new at(this.firestore,e,this._query)}}class de{constructor(e,t,r){this.converter=t,this._key=r,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new qt(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new de(this.firestore,e,this._key)}toJSON(){return{type:de._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,r){if(mr(t,de._jsonSchema))return new de(e,r||null,new L(X.fromString(t.referencePath)))}}de._jsonSchemaVersion="firestore/documentReference/1.0",de._jsonSchema={type:ue("string",de._jsonSchemaVersion),referencePath:ue("string")};class qt extends at{constructor(e,t,r){super(e,t,Ss(r)),this._path=r,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 de(this.firestore,null,new L(e))}withConverter(e){return new qt(this.firestore,e,this._path)}}function Hl(n,e,...t){if(n=Y(n),Hc("collection","path",e),n instanceof Js){const r=X.fromString(e,...t);return Gc(r),new qt(n,null,r)}{if(!(n instanceof de||n instanceof qt))throw new D(P.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=n._path.child(X.fromString(e,...t));return Gc(r),new qt(n.firestore,null,r)}}function Xs(n,e,...t){if(n=Y(n),arguments.length===1&&(e=ro.newId()),Hc("doc","path",e),n instanceof Js){const r=X.fromString(e,...t);return Wc(r),new de(n,null,new L(r))}{if(!(n instanceof de||n instanceof qt))throw new D(P.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=n._path.child(X.fromString(e,...t));return Wc(r),new de(n.firestore,n instanceof qt?n.converter:null,new L(r))}}const Wl="AsyncQueue";class Gl{constructor(e=Promise.resolve()){this.Yu=[],this.ec=!1,this.tc=[],this.nc=null,this.rc=!1,this.sc=!1,this.oc=[],this.M_=new ml(this,"async_queue_retry"),this._c=()=>{const r=Oo();r&&V(Wl,"Visibility state changed to "+r.visibilityState),this.M_.w_()},this.ac=e;const t=Oo();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this._c)}get isShuttingDown(){return this.ec}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.uc(),this.cc(e)}enterRestrictedMode(e){if(!this.ec){this.ec=!0,this.sc=e||!1;const t=Oo();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this._c)}}enqueue(e){if(this.uc(),this.ec)return new Promise(()=>{});const t=new nt;return this.cc(()=>this.ec&&this.sc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Yu.push(e),this.lc()))}async lc(){if(this.Yu.length!==0){try{await this.Yu[0](),this.Yu.shift(),this.M_.reset()}catch(e){if(!kn(e))throw e;V(Wl,"Operation failed with retryable error: "+e)}this.Yu.length>0&&this.M_.p_(()=>this.lc())}}cc(e){const t=this.ac.then(()=>(this.rc=!0,e().catch(r=>{throw this.nc=r,this.rc=!1,Et("INTERNAL UNHANDLED ERROR: ",Kl(r)),r}).then(r=>(this.rc=!1,r))));return this.ac=t,t}enqueueAfterDelay(e,t,r){this.uc(),this.oc.indexOf(e)>-1&&(t=0);const s=Uo.createAndSchedule(this,e,t,r,i=>this.hc(i));return this.tc.push(s),s}uc(){this.nc&&x(47125,{Pc:Kl(this.nc)})}verifyOperationInProgress(){}async Tc(){let e;do e=this.ac,await e;while(e!==this.ac)}Ic(e){for(const t of this.tc)if(t.timerId===e)return!0;return!1}Ec(e){return this.Tc().then(()=>{this.tc.sort((t,r)=>t.targetTimeMs-r.targetTimeMs);for(const t of this.tc)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Tc()})}Rc(e){this.oc.push(e)}hc(e){const t=this.tc.indexOf(e);this.tc.splice(t,1)}}function Kl(n){let e=n.message||"";return n.stack&&(e=n.stack.includes(n.message)?n.stack:n.message+`
36
+ `+n.stack),e}class jt extends Js{constructor(e,t,r,s){super(e,t,r,s),this.type="firestore",this._queue=new Gl,this._persistenceKey=s?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new Gl(e),this._firestoreClient=void 0,await e}}}function rE(n,e){const t=typeof n=="object"?n:fs(),r=typeof n=="string"?n:vs,s=dr(t,"firestore").getImmediate({identifier:r});if(!s._initialized){const i=ji("firestore");i&&zl(s,...i)}return s}function jn(n){if(n._terminated)throw new D(P.FAILED_PRECONDITION,"The client has already been terminated.");return n._firestoreClient||sE(n),n._firestoreClient}function sE(n){const e=n._freezeSettings(),t=nE(n._databaseId,n._app?.options.appId||"",n._persistenceKey,n._app?.options.apiKey,e);n._componentsProvider||e.localCache?._offlineComponentProvider&&e.localCache?._onlineComponentProvider&&(n._componentsProvider={_offline:e.localCache._offlineComponentProvider,_online:e.localCache._onlineComponentProvider}),n._firestoreClient=new Wy(n._authCredentials,n._appCheckCredentials,n._queue,t,n._componentsProvider&&function(s){const i=s?._online.build();return{_offline:s?._offline.build(i),_online:i}}(n._componentsProvider))}class ze{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ze(we.fromBase64String(e))}catch(t){throw new D(P.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new ze(we.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)}toJSON(){return{type:ze._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(mr(e,ze._jsonSchema))return ze.fromBase64String(e.bytes)}}ze._jsonSchemaVersion="firestore/bytes/1.0",ze._jsonSchema={type:ue("string",ze._jsonSchemaVersion),bytes:ue("string")};class Xo{constructor(...e){for(let t=0;t<e.length;++t)if(e[t].length===0)throw new D(P.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Ee(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class Zo{constructor(e){this._methodName=e}}class ct{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new D(P.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new D(P.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}_compareTo(e){return W(this._lat,e._lat)||W(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:ct._jsonSchemaVersion}}static fromJSON(e){if(mr(e,ct._jsonSchema))return new ct(e.latitude,e.longitude)}}ct._jsonSchemaVersion="firestore/geoPoint/1.0",ct._jsonSchema={type:ue("string",ct._jsonSchemaVersion),latitude:ue("number"),longitude:ue("number")};class Qe{constructor(e){this._values=(e||[]).map(t=>t)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(r,s){if(r.length!==s.length)return!1;for(let i=0;i<r.length;++i)if(r[i]!==s[i])return!1;return!0}(this._values,e._values)}toJSON(){return{type:Qe._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(mr(e,Qe._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(t=>typeof t=="number"))return new Qe(e.vectorValues);throw new D(P.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}Qe._jsonSchemaVersion="firestore/vectorValue/1.0",Qe._jsonSchema={type:ue("string",Qe._jsonSchemaVersion),vectorValues:ue("object")};const iE=/^__.*__$/;class oE{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return this.fieldMask!==null?new Mt(e,this.data,this.fieldMask,t,this.fieldTransforms):new Pr(e,this.data,t,this.fieldTransforms)}}class Ql{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new Mt(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Yl(n){switch(n){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw x(40011,{dataSource:n})}}class ea{constructor(e,t,r,s,i,a){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=s,i===void 0&&this.validatePath(),this.fieldTransforms=i||[],this.fieldMask=a||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(e){return new ea({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(e){const t=this.path?.child(e),r=this.contextWith({path:t,arrayElement:!1});return r.validatePathSegment(e),r}childContextForFieldPath(e){const t=this.path?.child(e),r=this.contextWith({path:t,arrayElement:!1});return r.validatePath(),r}childContextForArray(e){return this.contextWith({path:void 0,arrayElement:!0})}createError(e){return ei(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return this.fieldMask.find(t=>e.isPrefixOf(t))!==void 0||this.fieldTransforms.find(t=>e.isPrefixOf(t.field))!==void 0}validatePath(){if(this.path)for(let e=0;e<this.path.length;e++)this.validatePathSegment(this.path.get(e))}validatePathSegment(e){if(e.length===0)throw this.createError("Document fields must not be empty");if(Yl(this.dataSource)&&iE.test(e))throw this.createError('Document fields cannot begin and end with "__"')}}class aE{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=r||Hs(e)}createContext(e,t,r,s=!1){return new ea({dataSource:e,methodName:t,targetDoc:r,path:Ee.emptyPath(),arrayElement:!1,hasConverter:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ta(n){const e=n._freezeSettings(),t=Hs(n._databaseId);return new aE(n._databaseId,!!e.ignoreUndefinedProperties,t)}function cE(n,e,t,r,s,i={}){const a=n.createContext(i.merge||i.mergeFields?2:0,e,t,s);na("Data must be an object, but it was:",a,r);const c=Xl(r,a);let l,d;if(i.merge)l=new Fe(a.fieldMask),d=a.fieldTransforms;else if(i.mergeFields){const f=[];for(const m of i.mergeFields){const _=hn(e,m,t);if(!a.contains(_))throw new D(P.INVALID_ARGUMENT,`Field '${_}' is specified in your field mask but missing from your input data.`);th(f,_)||f.push(_)}l=new Fe(f),d=a.fieldTransforms.filter(m=>l.covers(m.field))}else l=null,d=a.fieldTransforms;return new oE(new Se(c),l,d)}class Zs extends Zo{_toFieldTransform(e){if(e.dataSource!==2)throw e.dataSource===1?e.createError(`${this._methodName}() can only appear at the top level of your update data`):e.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Zs}}function uE(n,e,t,r){const s=n.createContext(1,e,t);na("Data must be an object, but it was:",s,r);const i=[],a=Se.empty();Dt(r,(l,d)=>{const f=eh(e,l,t);d=Y(d);const m=s.childContextForFieldPath(f);if(d instanceof Zs)i.push(f);else{const _=Or(d,m);_!=null&&(i.push(f),a.set(f,_))}});const c=new Fe(i);return new Ql(a,c,s.fieldTransforms)}function lE(n,e,t,r,s,i){const a=n.createContext(1,e,t),c=[hn(e,r,t)],l=[s];if(i.length%2!=0)throw new D(P.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let _=0;_<i.length;_+=2)c.push(hn(e,i[_])),l.push(i[_+1]);const d=[],f=Se.empty();for(let _=c.length-1;_>=0;--_)if(!th(d,c[_])){const R=c[_];let S=l[_];S=Y(S);const N=a.childContextForFieldPath(R);if(S instanceof Zs)d.push(R);else{const k=Or(S,N);k!=null&&(d.push(R),f.set(R,k))}}const m=new Fe(d);return new Ql(f,m,a.fieldTransforms)}function Jl(n,e,t,r=!1){return Or(t,n.createContext(r?4:3,e))}function Or(n,e){if(Zl(n=Y(n)))return na("Unsupported field value:",e,n),Xl(n,e);if(n instanceof Zo)return function(r,s){if(!Yl(s.dataSource))throw s.createError(`${r._methodName}() can only be used with update() and set()`);if(!s.path)throw s.createError(`${r._methodName}() is not currently supported inside arrays`);const i=r._toFieldTransform(s);i&&s.fieldTransforms.push(i)}(n,e),null;if(n===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),n instanceof Array){if(e.settings.arrayElement&&e.dataSource!==4)throw e.createError("Nested arrays are not supported");return function(r,s){const i=[];let a=0;for(const c of r){let l=Or(c,s.childContextForArray(a));l==null&&(l={nullValue:"NULL_VALUE"}),i.push(l),a++}return{arrayValue:{values:i}}}(n,e)}return function(r,s){if((r=Y(r))===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return zg(s.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){const i=ee.fromDate(r);return{timestampValue:js(s.serializer,i)}}if(r instanceof ee){const i=new ee(r.seconds,1e3*Math.floor(r.nanoseconds/1e3));return{timestampValue:js(s.serializer,i)}}if(r instanceof ct)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof ze)return{bytesValue:Ku(s.serializer,r._byteString)};if(r instanceof de){const i=s.databaseId,a=r.firestore._databaseId;if(!a.isEqual(i))throw s.createError(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:wo(r.firestore._databaseId||s.databaseId,r._key.path)}}if(r instanceof Qe)return function(a,c){const l=a instanceof Qe?a.toArray():a;return{mapValue:{fields:{[au]:{stringValue:cu},[Rs]:{arrayValue:{values:l.map(f=>{if(typeof f!="number")throw c.createError("VectorValues must only contain numeric values.");return _o(c.serializer,f)})}}}}}}(r,s);if(rl(r))return r._toProto(s.serializer);throw s.createError(`Unsupported field value: ${gs(r)}`)}(n,e)}function Xl(n,e){const t={};return eu(n)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):Dt(n,(r,s)=>{const i=Or(s,e.childContextForField(r));i!=null&&(t[r]=i)}),{mapValue:{fields:t}}}function Zl(n){return!(typeof n!="object"||n===null||n instanceof Array||n instanceof Date||n instanceof ee||n instanceof ct||n instanceof ze||n instanceof de||n instanceof Zo||n instanceof Qe||rl(n))}function na(n,e,t){if(!Zl(t)||!Kc(t)){const r=gs(t);throw r==="an object"?e.createError(n+" a custom object"):e.createError(n+" "+r)}}function hn(n,e,t){if((e=Y(e))instanceof Xo)return e._internalPath;if(typeof e=="string")return eh(n,e);throw ei("Field path arguments must be of type string or ",n,!1,void 0,t)}const hE=new RegExp("[~\\*/\\[\\]]");function eh(n,e,t){if(e.search(hE)>=0)throw ei(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,n,!1,void 0,t);try{return new Xo(...e.split("."))._internalPath}catch{throw ei(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,n,!1,void 0,t)}}function ei(n,e,t,r,s){const i=r&&!r.isEmpty(),a=s!==void 0;let c=`Function ${e}() called with invalid data`;t&&(c+=" (via `toFirestore()`)"),c+=". ";let l="";return(i||a)&&(l+=" (found",i&&(l+=` in field ${r}`),a&&(l+=` in document ${s}`),l+=")"),new D(P.INVALID_ARGUMENT,c+n+l)}function th(n,e){return n.some(t=>t.isEqual(e))}class dE{convertValue(e,t="none"){switch(Lt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ae(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(Vt(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw x(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const r={};return Dt(e,(s,i)=>{r[s]=this.convertValue(i,t)}),r}convertVectorValue(e){const t=e.fields?.[Rs].arrayValue?.values?.map(r=>ae(r.doubleValue));return new Qe(t)}convertGeoPoint(e){return new ct(ae(e.latitude),ae(e.longitude))}convertArray(e,t){return(e.values||[]).map(r=>this.convertValue(r,t))}convertServerTimestamp(e,t){switch(t){case"previous":const r=Is(e);return r==null?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(_r(e));default:return null}}convertTimestamp(e){const t=Ot(e);return new ee(t.seconds,t.nanos)}convertDocumentKey(e,t){const r=X.fromString(e);J(nl(r),9688,{name:e});const s=new yr(r.get(1),r.get(3)),i=new L(r.popFirst(5));return s.isEqual(t)||Et(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}class ti extends dE{constructor(e){super(),this.firestore=e}convertBytes(e){return new ze(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new de(this.firestore,null,t)}}const nh="@firebase/firestore",rh="4.12.0";function sh(n){return function(t,r){if(typeof t!="object"||t===null)return!1;const s=t;for(const i of r)if(i in s&&typeof s[i]=="function")return!0;return!1}(n,["next","error","complete"])}class fE{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class pE{constructor(e,t,r){this._userDataWriter=t,this._data=r,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}_fieldsProto(){return new Se({mapValue:{fields:this._data}}).clone().value.mapValue.fields}}class ra{constructor(e,t,r,s,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=s,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new de(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){const e=new mE(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){return this._document?.data.clone().value.mapValue.fields??void 0}get(e){if(this._document){const t=this._document.data.field(hn("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}}class mE extends ra{data(){return super.data()}}function ih(n){if(n.limitType==="L"&&n.explicitOrderBy.length===0)throw new D(P.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class sa{}class ni extends sa{}function oh(n,e,...t){let r=[];e instanceof sa&&r.push(e),r=r.concat(t),function(i){const a=i.filter(l=>l instanceof $n).length,c=i.filter(l=>l instanceof Vr).length;if(a>1||a>0&&c>0)throw new D(P.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const s of r)n=s._apply(n);return n}class Vr extends ni{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new Vr(e,t,r)}_apply(e){const t=this._parse(e);return hh(e._query,t),new at(e.firestore,e.converter,go(e._query,t))}_parse(e){const t=ta(e.firestore);return function(i,a,c,l,d,f,m){let _;if(d.isKeyField()){if(f==="array-contains"||f==="array-contains-any")throw new D(P.INVALID_ARGUMENT,`Invalid Query. You can't perform '${f}' queries on documentId().`);if(f==="in"||f==="not-in"){lh(m,f);const S=[];for(const N of m)S.push(uh(l,i,N));_={arrayValue:{values:S}}}else _=uh(l,i,m)}else f!=="in"&&f!=="not-in"&&f!=="array-contains-any"||lh(m,f),_=Jl(c,a,m,f==="in"||f==="not-in");return le.create(d,f,_)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function ah(n,e,t){const r=e,s=hn("where",n);return Vr._create(s,r,t)}class $n extends sa{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new $n(e,t)}_parse(e){const t=this._queryConstraints.map(r=>r._parse(e)).filter(r=>r.getFilters().length>0);return t.length===1?t[0]:Ke.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return t.getFilters().length===0?e:(function(s,i){let a=s;const c=i.getFlattenedFilters();for(const l of c)hh(a,l),a=go(a,l)}(e._query,t),new at(e.firestore,e.converter,go(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}}function gE(...n){return n.forEach(e=>dh("or",e)),$n._create("or",n)}function _E(...n){return n.forEach(e=>dh("and",e)),$n._create("and",n)}class ia extends ni{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new ia(e,t)}_apply(e){const t=function(s,i,a){if(s.startAt!==null)throw new D(P.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(s.endAt!==null)throw new D(P.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new wr(i,a)}(e._query,this._field,this._direction);return new at(e.firestore,e.converter,Lg(e._query,t))}}function yE(n,e="asc"){const t=e,r=hn("orderBy",n);return ia._create(r,t)}class oa extends ni{constructor(e,t,r){super(),this.type=e,this._limit=t,this._limitType=r}static _create(e,t,r){return new oa(e,t,r)}_apply(e){return new at(e.firestore,e.converter,ks(e._query,this._limit,this._limitType))}}function ch(n){return ig("limit",n),oa._create("limit",n,"F")}class aa extends ni{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new aa(e,t,r)}_apply(e){const t=TE(e,this.type,this._docOrFields,this._inclusive);return new at(e.firestore,e.converter,Mg(e._query,t))}}function EE(...n){return aa._create("startAfter",n,!1)}function TE(n,e,t,r){if(t[0]=Y(t[0]),t[0]instanceof ra)return function(i,a,c,l,d){if(!l)throw new D(P.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${c}().`);const f=[];for(const m of Vn(i))if(m.field.isKeyField())f.push(Ps(a,l.key));else{const _=l.data.field(m.field);if(ws(_))throw new D(P.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+m.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(_===null){const R=m.field.canonicalString();throw new D(P.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${R}' (used as the orderBy) does not exist.`)}f.push(_)}return new On(f,d)}(n._query,n.firestore._databaseId,e,t[0]._document,r);{const s=ta(n.firestore);return function(a,c,l,d,f,m){const _=a.explicitOrderBy;if(f.length>_.length)throw new D(P.INVALID_ARGUMENT,`Too many arguments provided to ${d}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const R=[];for(let S=0;S<f.length;S++){const N=f[S];if(_[S].field.isKeyField()){if(typeof N!="string")throw new D(P.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${d}(), but got a ${typeof N}`);if(!mo(a)&&N.indexOf("/")!==-1)throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${d}() must be a plain document ID, but '${N}' contains a slash.`);const k=a.path.child(X.fromString(N));if(!L.isDocumentKey(k))throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${d}() must result in a valid document path, but '${k}' is not because it contains an odd number of segments.`);const U=new L(k);R.push(Ps(c,U))}else{const k=Jl(l,d,N);R.push(k)}}return new On(R,m)}(n._query,n.firestore._databaseId,s,e,t,r)}}function uh(n,e,t){if(typeof(t=Y(t))=="string"){if(t==="")throw new D(P.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!mo(e)&&t.indexOf("/")!==-1)throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${t}' contains a '/' character.`);const r=e.path.child(X.fromString(t));if(!L.isDocumentKey(r))throw new D(P.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 Ps(n,new L(r))}if(t instanceof de)return Ps(n,t._key);throw new D(P.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${gs(t)}.`)}function lh(n,e){if(!Array.isArray(n)||n.length===0)throw new D(P.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${e.toString()}' filters.`)}function hh(n,e){const t=function(s,i){for(const a of s)for(const c of a.getFlattenedFilters())if(i.indexOf(c.op)>=0)return c.op;return null}(n.filters,function(s){switch(s){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(e.op));if(t!==null)throw t===e.op?new D(P.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new D(P.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${t.toString()}' filters.`)}function dh(n,e){if(!(e instanceof Vr||e instanceof $n))throw new D(P.INVALID_ARGUMENT,`Function ${n}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}function wE(n,e,t){let r;return r=n?t&&(t.merge||t.mergeFields)?n.toFirestore(e,t):n.toFirestore(e):e,r}function IE(){return new fE("count")}function vE(n){return AE(n,{count:IE()})}function AE(n,e){const t=Ge(n.firestore,jt),r=jn(t),s=mg(e,(i,a)=>new e_(a,i.aggregateType,i._internalFieldPath));return Zy(r,n._query,s).then(i=>function(c,l,d){const f=new ti(c);return new pE(l,f,d)}(t,n,i))}class Lr{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class dn extends ra{constructor(e,t,r,s,i,a){super(e,t,r,s,a),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new ri(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){const r=this._document.data.field(hn("DocumentSnapshot.get",e));if(r!==null)return this._userDataWriter.convertValue(r,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new D(P.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");const e=this._document,t={};return t.type=dn._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?t:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),t.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),t)}}dn._jsonSchemaVersion="firestore/documentSnapshot/1.0",dn._jsonSchema={type:ue("string",dn._jsonSchemaVersion),bundleSource:ue("string","DocumentSnapshot"),bundleName:ue("string"),bundle:ue("string")};class ri extends dn{data(e={}){return super.data(e)}}class fn{constructor(e,t,r,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new Lr(s.hasPendingWrites,s.fromCache),this.query=r}get docs(){const e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,t){this._snapshot.docs.forEach(r=>{e.call(t,new ri(this._firestore,this._userDataWriter,r.key,r,new Lr(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new D(P.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,i){if(s._snapshot.oldDocs.isEmpty()){let a=0;return s._snapshot.docChanges.map(c=>{const l=new ri(s._firestore,s._userDataWriter,c.doc.key,c.doc,new Lr(s._snapshot.mutatedKeys.has(c.doc.key),s._snapshot.fromCache),s.query.converter);return c.doc,{type:"added",doc:l,oldIndex:-1,newIndex:a++}})}{let a=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(c=>i||c.type!==3).map(c=>{const l=new ri(s._firestore,s._userDataWriter,c.doc.key,c.doc,new Lr(s._snapshot.mutatedKeys.has(c.doc.key),s._snapshot.fromCache),s.query.converter);let d=-1,f=-1;return c.type!==0&&(d=a.indexOf(c.doc.key),a=a.delete(c.doc.key)),c.type!==1&&(a=a.add(c.doc),f=a.indexOf(c.doc.key)),{type:RE(c.type),doc:l,oldIndex:d,newIndex:f}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new D(P.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");const e={};e.type=fn._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=ro.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;const t=[],r=[],s=[];return this.docs.forEach(i=>{i._document!==null&&(t.push(i._document),r.push(this._userDataWriter.convertObjectMap(i._document.data.value.mapValue.fields,"previous")),s.push(i.ref.path))}),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}}function RE(n){switch(n){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return x(61501,{type:n})}}fn._jsonSchemaVersion="firestore/querySnapshot/1.0",fn._jsonSchema={type:ue("string",fn._jsonSchemaVersion),bundleSource:ue("string","QuerySnapshot"),bundleName:ue("string"),bundle:ue("string")};class bE{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ta(e)}set(e,t,r){this._verifyNotCommitted();const s=ca(e,this._firestore),i=wE(s.converter,t,r),a=cE(this._dataReader,"WriteBatch.set",s._key,i,s.converter!==null,r);return this._mutations.push(a.toMutation(s._key,$e.none())),this}update(e,t,r,...s){this._verifyNotCommitted();const i=ca(e,this._firestore);let a;return a=typeof(t=Y(t))=="string"||t instanceof Xo?lE(this._dataReader,"WriteBatch.update",i._key,t,r,s):uE(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(a.toMutation(i._key,$e.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=ca(e,this._firestore);return this._mutations=this._mutations.concat(new Us(t._key,$e.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new D(P.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function ca(n,e){if((n=Y(n)).firestore!==e)throw new D(P.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return n}function PE(n){n=Ge(n,de);const e=Ge(n.firestore,jt),t=jn(e);return Jy(t,n._key).then(r=>mh(e,n,r))}function CE(n){n=Ge(n,at);const e=Ge(n.firestore,jt),t=jn(e),r=new ti(e);return ih(n._query),Xy(t,n._query).then(s=>new fn(e,r,n,s))}function SE(n){return ph(Ge(n.firestore,jt),[new Us(n._key,$e.none())])}function fh(n,...e){n=Y(n);let t={includeMetadataChanges:!1,source:"default"},r=0;typeof e[r]!="object"||sh(e[r])||(t=e[r++]);const s={includeMetadataChanges:t.includeMetadataChanges,source:t.source};if(sh(e[r])){const d=e[r];e[r]=d.next?.bind(d),e[r+1]=d.error?.bind(d),e[r+2]=d.complete?.bind(d)}let i,a,c;if(n instanceof de)a=Ge(n.firestore,jt),c=Ss(n._key.path),i={next:d=>{e[r]&&e[r](mh(a,n,d))},error:e[r+1],complete:e[r+2]};else{const d=Ge(n,at);a=Ge(d.firestore,jt),c=d._query;const f=new ti(a);i={next:m=>{e[r]&&e[r](new fn(a,f,d,m))},error:e[r+1],complete:e[r+2]},ih(n._query)}const l=jn(a);return Yy(l,c,s,i)}function ph(n,e){const t=jn(n);return eE(t,e)}function mh(n,e,t){const r=t.docs.get(e._key),s=new ti(n);return new dn(n,s,e._key,r,new Lr(t.hasPendingWrites,t.fromCache),e.converter)}function kE(n){return n=Ge(n,jt),jn(n),new bE(n,e=>ph(n,e))}(function(e,t=!0){Gm(nn),Ct(new _t("firestore",(r,{instanceIdentifier:s,options:i})=>{const a=r.getProvider("app").getImmediate(),c=new jt(new Ym(r.getProvider("auth-internal")),new Zm(a,r.getProvider("app-check-internal")),yg(a,s),a);return i={useFetchStreams:t,...i},c._setSettings(i),c},"PUBLIC").setMultipleInstances(!0)),je(nh,rh,e),je(nh,rh,"esm2020")})();class gh{constructor(){this.subscribers=new Set}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notify(e){this.subscribers.forEach(t=>t(e))}get subscribersCount(){return this.subscribers.size}}const Ie=[];for(let n=0;n<256;++n)Ie.push((n+256).toString(16).slice(1));function NE(n,e=0){return(Ie[n[e+0]]+Ie[n[e+1]]+Ie[n[e+2]]+Ie[n[e+3]]+"-"+Ie[n[e+4]]+Ie[n[e+5]]+"-"+Ie[n[e+6]]+Ie[n[e+7]]+"-"+Ie[n[e+8]]+Ie[n[e+9]]+"-"+Ie[n[e+10]]+Ie[n[e+11]]+Ie[n[e+12]]+Ie[n[e+13]]+Ie[n[e+14]]+Ie[n[e+15]]).toLowerCase()}let ua;const DE=new Uint8Array(16);function OE(){if(!ua){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ua=crypto.getRandomValues.bind(crypto)}return ua(DE)}const VE=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),_h={randomUUID:VE};function LE(n,e,t){n=n||{};const r=n.random??n.rng?.()??OE();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,NE(r)}function ME(n,e,t){return _h.randomUUID&&!n?_h.randomUUID():LE(n)}var xE=Object.defineProperty,UE=(n,e,t,r)=>{for(var s=void 0,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(e,t,s)||s);return s&&xE(e,t,s),s},ce;const yh=(ce=class{static registerFactory(n,e,t,r=!1){this._factoryMap[n]={factory:e,annotation:t,isLegacy:r}}static classFactory(n){if(!n)throw new Error("You should provide a class name.");if(!this._factoryMap[n])throw new Error(`You should register class ${n} prior to use.`);return this._factoryMap[n].factory}static registeredClasses(){return Object.entries(this._factoryMap).filter(([,n])=>!n.isLegacy).map(([n])=>n)}static registeredClassesAndLegacyNames(){return Object.keys(this._factoryMap)}static classesExtending(n){return Object.entries(this._factoryMap).filter(([,e])=>new e.factory instanceof n&&!e.isLegacy).map(([e])=>e)}static annotations(n){if(n instanceof ce?n=n.className:typeof n=="string"||(n=new n().className),!this._factoryMap[n])throw new Error(`You should register class ${n} prior to use.`);return this._factoryMap[n].annotation}constructor(n=ME()){this._id=n}get className(){return this.__className}setId(n){this._id=n}get id(){return this._id}afterDeserialize(){}beforeSerialize(){}getPersistentProperties(){return this._persistentProperties?this._persistentProperties.map(n=>({...n,name:n.name.slice(1)})):[]}getPropInfo(n){const e=this.getPersistentProperties().find(t=>t.name===n);if(!e)throw new Error(`Property "${n}" has not been registered.`);return e}isRequired(n){return this.getPropInfo(n).validator!=null}isPropValueValid(n){const e=this.getPropInfo(n);return e.validator?e.validator(this[e.name],e,this):!0}clone(n){const e=n.toObject();return delete e.id,this.fromObject(e)}fromObject(n){return this.fromObj(n),this.afterDeserialize(),this}fromObj(n){return this._persistentProperties?(this._persistentProperties.forEach(e=>{const t=this.removeUnderscore(e),r=n[t];r!=null&&(this[e.name]=this.fromDeepObject(r))}),this):this}toObject(){const n={},e=this.toObj(n);return this.pushDocument(n,this.className,e),{...e,__rootCollections:n}}toObj(n){if(!this._persistentProperties)return{};this.beforeSerialize();const e={};if(!this.className)throw new Error(`You should register \`${this.constructor.name||this.toString()||"this"}\` class prior to streaming it.`);return this._persistentProperties.forEach(t=>{const r=this[t.name],s=this.removeUnderscore(t);r!=null&&(t.isReference?e[s]=this.toReferenceObj(t,n):e[s]=this.toDeepObj(r,n),t.searchableArray&&(e[ce.searchableArrayNameFor(s)]=r.map(i=>i.id)))}),e.__className=this.className,e}static searchableArrayNameFor(n){return`__${n}_searchable`}fromDeepObject(n){if(n==null)return n;if(Array.isArray(n))return n.map(e=>this.fromDeepObject(e));if(n.__documentReference){const e=n,t=ce.createInstance(e);return t.__documentReference=n.__documentReference,t}if(n.__className)return ce.createInstance(n);if(typeof n=="object"){const e={};return Object.entries(n).forEach(([t,r])=>e[t]=this.fromDeepObject(r)),e}return n}toDeepObj(n,e){if(n!=null){if(Array.isArray(n))return n.map(t=>this.toDeepObj(t,e));if(n.__documentReference)return n;if(n instanceof ce)return n.toObj(e);if(typeof n=="object"){const t={};return Object.entries(n).forEach(([r,s])=>t[r]=this.toDeepObj(s,e)),t}return n}}static collectionPath(n,e,t){let r;return typeof e.storeInCollection=="function"?r=e.storeInCollection(n,e,t):r=e.storeInCollection??n.className,r}toReferenceObj(n,e){const t=this[n.name];return Array.isArray(t)?t.map(r=>(n.isPureReference||this.pushDocument(e,ce.collectionPath(r,n),r),this.buildRefObject(r,ce.collectionPath(r,n),n.cachedProps))):(n.isPureReference||this.pushDocument(e,ce.collectionPath(t,n),t),this.buildRefObject(t,ce.collectionPath(t,n),n.cachedProps))}buildRefObject(n,e,t){const r=t?.reduce((s,i)=>(n[i]!==void 0&&(s[i]=n[i]),s),{});return{id:n.id,__className:n.className||n.__className,__documentReference:{storedInCollection:e},...r}}pushDocument(n,e,t){if("__documentReference"in t&&t.__documentReference)return;n[e]||(n[e]=[]);const r=this.toDeepObj(t,n);n[e].push(r)}removeUnderscore(n){return n.name.slice(1)}static createReference(n){const e=ce.createInstance(n);return e.__documentReference=n.__documentReference||{storedInCollection:e.className},e}static createInstance(n){if(typeof n=="string")return new(ce.classFactory(n));try{return new(ce.classFactory(n.__className))().fromObject(n)}catch(e){const t=Object.entries(n).filter(([r,s])=>s!=null&&typeof s!="function").map(([r,s])=>`${r}: ${s}`).join(`,
37
37
  `);throw new Error(`${e}
38
38
  -----> Class name not found in object:
39
39
  {
40
40
  ${t}
41
41
  }
42
- `)}}static propInfo(n,e){return ce.createInstance(n).getPropInfo(e)}static propType(n){if(n.typeName)return Array.isArray(n.typeName)?"undefined[]":n.typeName??"undefined";const e=ce.createInstance(n.ownerClassName())[n.name];if(Array.isArray(e)){if(e.length===0)return"undefined[]";const t=e[0];return t instanceof ce?t.className+"[]":typeof t+"[]"}else return e instanceof ce?e.className:typeof e}static getSystemRegisteredReferencesWithCachedProps(){return ce.registeredClasses().reduce((n,e)=>{const t=ce.createInstance(e).getPersistentProperties().filter(r=>r.cachedProps);return t.length>0&&(n[e]=t),n},{})}},ce._factoryMap={},ce);UE([zn],yh.prototype,"_id");let pe=yh;function zn(n,e){return FE()(n,e)}function FE(n){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,n):e._persistentProperties.push({name:t,ownerClassName:()=>e.className,...n})}}function BE(n,e){return t=>{pe.registerFactory(n,t,e),t.prototype.__className=n}}const Eh=class dp{constructor(e,t,r){if(r){if(!(t instanceof pe))throw new Error(dp.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof pe?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(i=>{i?(t?t.fromObject(i):t=pe.createInstance(i),r(t)):r(void 0)}).catch(i=>s(i))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(i=>s(i))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new qE(this)}query(e={},t){if(t){const r=t instanceof pe?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}onDocumentChange(e,t){return this._stream.onDocumentChange(this.collectionName,e,r=>t($t.toPersistentDocumentChange(r)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,r=>t(r.map(s=>$t.toPersistentDocumentChange(s))))}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(i=>pe.createInstance(i)))).catch(s=>r(s))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;const t=e.operations?.map(r=>{const s=r.value[0]??r.value;return $t.isArrayOperator(r.operator)&&s instanceof pe?{property:pe.searchableArrayNameFor(r.property),operator:r.operator,value:Array.isArray(r.value)?r.value.map(i=>i.id):s.id,aggregate:r.aggregate}:{property:r.property,operator:r.operator,value:r.value instanceof pe?{id:r.value.id}:r.value,aggregate:r.aggregate}})??[];return{...e,operations:t}}};Eh.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let si=Eh;class qE{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(si.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(si.error.invalidQueryOrder);const i=e.split(".");let a={},c=i.length>1?a:r;return i.slice(1).forEach((l,d)=>{a[l]=d<i.length-2?{}:r,a=a[l]}),this.queryObject.operations?.push({property:i[0],operator:t,value:c,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){const t=e instanceof pe?e.className:e;return this.queryObject.operations?.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}getQueryObject(){return this.queryObject}}const Th=class sr{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return sr._dataSource}static getModel(e){if(!sr._dataSource)throw new Error(this.error.shouldBeRegistered);return new si(sr._dataSource,e)}static getModelForSubCollection(e,t){if(!sr._dataSource)throw new Error(this.error.shouldBeRegistered);return new si(sr._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const i=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return i&&(i.__documentReference=void 0),i};return Array.isArray(e)?(await Promise.all(e.map(r=>t(r)))).filter(r=>r):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};Th.error={shouldBeRegistered:"You should register a data source before using the data Store."};let jE=Th;class la{constructor(e){this.handlers=[],this.subscribeToDocumentChangeListener=()=>{throw new Error("The method subscribeToDocumentChangeListener has not been implemented in the concrete data source")},this.collectionsMatchingTemplate=()=>{throw new Error("The method collectionsMatchingTemplate has not been implemented in the concrete data source")},e&&(this.beforeUpdate=e.beforeUpdateDocument,this.afterUpdate=e.afterUpdateDocument,this.onAllPropsUpdatedCallback=e.onAllPropsUpdated)}async installUpdaters(){const e=pe.getSystemRegisteredReferencesWithCachedProps(),t={};return Object.entries(e).forEach(([r,s])=>{s.forEach(i=>{i.typeName&&(Array.isArray(i.typeName)?i.typeName:[i?.typeName??r]).map(a=>pe.collectionPath(pe.createInstance(a),i)).forEach(a=>{t[a]||(t[a]=[]),t[a].push(i)})})}),this.handlers=[],await Promise.all(Object.entries(t).map(async([r,s])=>{const i=await this.subscribeToDocumentChangeListener(r,a=>this.onDocumentChange(a,s));if(i)this.handlers.push(i);else throw new Error("The method documentChangeListener has not been implemented in the concrete data source")})),this.handlers}uninstallUpdaters(){this.handlers.forEach(e=>e.uninstall()),this.handlers=[]}set onAllPropsUpdated(e){this.onAllPropsUpdatedCallback=e}set beforeUpdateDocument(e){this.beforeUpdate=e}set afterUpdateDocument(e){this.afterUpdate=e}set documentChangeListenerSubscriber(e){this.subscribeToDocumentChangeListener=e}set collectionsMatchingTemplateFunction(e){this.collectionsMatchingTemplate=e}async onDocumentChange(e,t){const r=$t.toPersistentDocumentChange(e);r.before&&(await Promise.all(t.map(async s=>{const i=la.ownerCollectionPath(pe.createInstance(s.ownerClassName()),s,r.params),a=await this.collectionsMatchingTemplate(i);await Promise.all(a.map(async c=>{const l=jE.getModel(c);let d=l.find(),f=!1;s.cachedProps?.forEach(g=>{const R=r.before[g],C=r.after[g];R!==C&&(f=!0)}),f&&(s.searchableArray?d=d.where(s.name,"contains",r.before):d=d.where(s.name,"==",r.before));const m=await d.get();return Promise.all([m.map(async g=>{let R=!1;if(s.cachedProps?.forEach(C=>{const N=r.before[C],k=r.after[C];N!==k&&(R=!0)}),R){if(s.searchableArray){const C=g[s.name].findIndex(N=>N.id===r.before.id);g[s.name][C]=r.after}else g[`_${s.name}`]=r.after;this.beforeUpdate?.(g,s),await l.save(g),this.afterUpdate?.(g,s)}else await Promise.resolve()})])}))})),this.onAllPropsUpdatedCallback?.())}static ownerCollectionPath(e,t,r){let s;return typeof t.ownerCollection=="function"?s=t.ownerCollection(e,t,r):s=t.ownerCollection??e.className,s}}class $t{constructor(){this._cachedPropsUpdater=void 0}async installCachedPropsUpdater(e){return this._cachedPropsUpdater=new la(e),this._cachedPropsUpdater.documentChangeListenerSubscriber=this.subscribeToDocumentChangeListener.bind(this),this._cachedPropsUpdater.collectionsMatchingTemplateFunction=this.collectionsMatchingTemplate.bind(this),this._cachedPropsUpdater.installUpdaters()}uninstallCachedPropsUpdater(){this._cachedPropsUpdater?.uninstallUpdaters(),this._cachedPropsUpdater=void 0}get cachedPropsUpdater(){return this._cachedPropsUpdater}static toPropertyPathOperations(e){return e?e.map(t=>{if($t.isArrayOperator(t.operator)&&t.value[0]instanceof pe)return{property:pe.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(i=>i.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPersistentDocumentChange(e){return{...e,before:e.before&&pe.createInstance(e.before),after:e.after&&pe.createInstance(e.after)}}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}static isStringMatchingTemplate(e,t){const r=e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&").replace(/\\\$\\\{[^}]+\\\}/g,"([^/]+)").replace(/\\\{[^}]+\\\}/g,"([^/]+)");return new RegExp("^"+r+"$").test(t)}static extractTemplateParams(e,t){const r=[],s=t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&").replace(/\\\{([^}]+)\\\}/g,(l,d)=>(r.push(d),"([^/]+)")),i=new RegExp("^"+s+"$"),a=e.match(i),c={};return a&&r.forEach((l,d)=>{c[l]=a[d+1]}),c}}const wh=class ir{static registerCloudStorage(e,t){ir._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=ir._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){ir._defaultCloudStorage=e}static get defaultCloudStorage(){if(!ir._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return ir._defaultCloudStorage}};wh._cloudStorageFactoryMap={};let Hn=wh;function Ih(n,e){return Hn.registerCloudStorage(n,e),t=>{t.prototype.__className=n}}var $E=(n,e,t,r)=>{for(var s=e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(s)||s);return s};let ha=class extends Hn{constructor(n=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=n}simulateDelay(n){return this._simulateDelay=n,this}resolveWithDelay(n){if(this._simulateDelay<=0)return Promise.resolve(n);const e=new Promise(t=>{setTimeout(()=>t(n),this._simulateDelay)});return this._pendingPromises.push(e),e.finally(()=>this._pendingPromises=this._pendingPromises.filter(t=>t===e)),e}save(n,e){const t=n;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[n]=JSON.stringify(e),this._onProgress&&this._onProgress(100,100);const r=e instanceof File?e.name:t;return this.resolveWithDelay(r)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:n=>this._onProgress=n}}getUrl(n){return Promise.resolve(this._pathToMockFiles+n)}delete(n){return delete this.mockFileSystem[n],this.resolveWithDelay()}};ha=$E([Ih("MockCloudStorage",()=>new ha)],ha);var zE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Wn=(n,e,t,r)=>{for(var s=r>1?void 0:r?HE(e,t):e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&zE(e,t,s),s};let fn=class extends pe{constructor(){super(...arguments),this._onChange=new gh}async save({data:n,fileName:e,progress:t,cloudStorageProvider:r}={}){const s=n||this._pendingData;s&&(this._reference&&await this.delete(),this.provider=r||Hn.defaultCloudStorage,this._originalFileName=e||(s instanceof File?s.name:void 0),this._reference=await this.provider.save(this.id,s,t),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(n){this._provider=n,this._cloudStorageProviderName=n.className}get provider(){if(!this._provider)try{this._provider=Hn.createInstance(this._cloudStorageProviderName)}catch{this._provider=Hn.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(n){return this._pendingData=n,this._originalFileName=n instanceof File?n.name:void 0,this._mimeType=n instanceof Blob?n.type:void 0,this._onChange.notify({event:1,pendingData:n,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(n){return this._onChange.subscribe(n)}};Wn([zn],fn.prototype,"_reference",2),Wn([zn],fn.prototype,"_url",2),Wn([zn],fn.prototype,"_cloudStorageProviderName",2),Wn([zn],fn.prototype,"_originalFileName",2),Wn([zn],fn.prototype,"_mimeType",2),fn=Wn([BE("StoredFile")],fn);class vh{}const Ah=class xe extends vh{constructor(){if(super(),this._onAuthStateChange=new gh,!xe._authService)throw new Error(xe.error.shouldBeRegistered);xe._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){xe._authService!=e&&(xe._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return xe._authService.signUp(e)}login(e){return xe._authService.login(e)}logout(){return xe._authService.logout()}resetEmailPassword(e){return xe._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return xe._authService.resendVerificationEmail(e,t,r)}refreshToken(){return xe._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return xe._authService.linkAdditionalProvider(e)}unlinkProvider(e){return xe._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};Ah.error={shouldBeRegistered:"You should register an auth service before using Auth."},Ah._instance=void 0;function ii(n){return n?n.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}var WE="firebase",GE="12.8.0";je(WE,GE,"app");function Rh(){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."}}const KE=Rh,bh=new cr("auth","Firebase",Rh());const oi=new zi("@firebase/auth");function QE(n,...e){oi.logLevel<=H.WARN&&oi.warn(`Auth (${nn}): ${n}`,...e)}function ai(n,...e){oi.logLevel<=H.ERROR&&oi.error(`Auth (${nn}): ${n}`,...e)}function He(n,...e){throw fa(n,...e)}function Ye(n,...e){return fa(n,...e)}function da(n,e,t){const r={...KE(),[e]:t};return new cr("auth","Firebase",r).create(e,{appName:n.name})}function ut(n){return da(n,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Ph(n,e,t){const r=t;if(!(e instanceof r))throw r.name!==e.constructor.name&&He(n,"argument-error"),da(n,"argument-error",`Type of ${e.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function fa(n,...e){if(typeof n!="string"){const t=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=n.name),n._errorFactory.create(t,...r)}return bh.create(n,...e)}function M(n,e,...t){if(!n)throw fa(e,...t)}function wt(n){const e="INTERNAL ASSERTION FAILED: "+n;throw ai(e),new Error(e)}function It(n,e){n||wt(e)}function pa(){return typeof self<"u"&&self.location?.href||""}function YE(){return Sh()==="http:"||Sh()==="https:"}function Sh(){return typeof self<"u"&&self.location?.protocol||null}function JE(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(YE()||bp()||"connection"in navigator)?navigator.onLine:!0}function XE(){if(typeof navigator>"u")return null;const n=navigator;return n.languages&&n.languages[0]||n.language||null}class Mr{constructor(e,t){this.shortDelay=e,this.longDelay=t,It(t>e,"Short delay should be less than long delay!"),this.isMobile=vp()||Pp()}get(){return JE()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function ma(n,e){It(n.emulator,"Emulator should always be set here");const{url:t}=n.emulator;return e?`${t}${e.startsWith("/")?e.slice(1):e}`:t}class Ch{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;wt("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;wt("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;wt("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const ZE={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};const eT=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],tT=new Mr(3e4,6e4);function vt(n,e){return n.tenantId&&!e.tenantId?{...e,tenantId:n.tenantId}:e}async function Je(n,e,t,r,s={}){return kh(n,s,async()=>{let i={},a={};r&&(e==="GET"?a=r:i={body:JSON.stringify(r)});const c=ur({key:n.config.apiKey,...a}).slice(1),l=await n._getAdditionalHeaders();l["Content-Type"]="application/json",n.languageCode&&(l["X-Firebase-Locale"]=n.languageCode);const d={method:e,headers:l,...i};return Rp()||(d.referrerPolicy="no-referrer"),n.emulatorConfig&&tt(n.emulatorConfig.host)&&(d.credentials="include"),Ch.fetch()(await Nh(n,n.config.apiHost,t,c),d)})}async function kh(n,e,t){n._canInitEmulator=!1;const r={...ZE,...e};try{const s=new rT(n),i=await Promise.race([t(),s.promise]);s.clearNetworkTimeout();const a=await i.json();if("needConfirmation"in a)throw ci(n,"account-exists-with-different-credential",a);if(i.ok&&!("errorMessage"in a))return a;{const c=i.ok?a.errorMessage:a.error.message,[l,d]=c.split(" : ");if(l==="FEDERATED_USER_ID_ALREADY_LINKED")throw ci(n,"credential-already-in-use",a);if(l==="EMAIL_EXISTS")throw ci(n,"email-already-in-use",a);if(l==="USER_DISABLED")throw ci(n,"user-disabled",a);const f=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(d)throw da(n,f,d);He(n,f)}}catch(s){if(s instanceof We)throw s;He(n,"network-request-failed",{message:String(s)})}}async function xr(n,e,t,r,s={}){const i=await Je(n,e,t,r,s);return"mfaPendingCredential"in i&&He(n,"multi-factor-auth-required",{_serverResponse:i}),i}async function Nh(n,e,t,r){const s=`${e}${t}?${r}`,i=n,a=i.config.emulator?ma(n.config,s):`${n.config.apiScheme}://${s}`;return eT.includes(t)&&(await i._persistenceManagerAvailable,i._getPersistenceType()==="COOKIE")?i._getPersistence()._getFinalTarget(a).toString():a}function nT(n){switch(n){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class rT{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((t,r)=>{this.timer=setTimeout(()=>r(Ye(this.auth,"network-request-failed")),tT.get())})}}function ci(n,e,t){const r={appName:n.name};t.email&&(r.email=t.email),t.phoneNumber&&(r.phoneNumber=t.phoneNumber);const s=Ye(n,e,r);return s.customData._tokenResponse=t,s}function Dh(n){return n!==void 0&&n.enterprise!==void 0}class sT{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return nT(t.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function iT(n,e){return Je(n,"GET","/v2/recaptchaConfig",vt(n,e))}async function oT(n,e){return Je(n,"POST","/v1/accounts:delete",e)}async function aT(n,e){return Je(n,"POST","/v1/accounts:update",e)}async function ui(n,e){return Je(n,"POST","/v1/accounts:lookup",e)}function Ur(n){if(n)try{const e=new Date(Number(n));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function cT(n,e=!1){const t=Q(n),r=await t.getIdToken(e),s=_a(r);M(s&&s.exp&&s.auth_time&&s.iat,t.auth,"internal-error");const i=typeof s.firebase=="object"?s.firebase:void 0,a=i?.sign_in_provider;return{claims:s,token:r,authTime:Ur(ga(s.auth_time)),issuedAtTime:Ur(ga(s.iat)),expirationTime:Ur(ga(s.exp)),signInProvider:a||null,signInSecondFactor:i?.sign_in_second_factor||null}}function ga(n){return Number(n)*1e3}function _a(n){const[e,t,r]=n.split(".");if(e===void 0||t===void 0||r===void 0)return ai("JWT malformed, contained fewer than 3 sections"),null;try{const s=pc(t);return s?JSON.parse(s):(ai("Failed to decode base64 JWT payload"),null)}catch(s){return ai("Caught error parsing JWT payload as JSON",s?.toString()),null}}function Oh(n){const e=_a(n);return M(e,"internal-error"),M(typeof e.exp<"u","internal-error"),M(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Gn(n,e,t=!1){if(t)return e;try{return await e}catch(r){throw r instanceof We&&uT(r)&&n.auth.currentUser===n&&await n.auth.signOut(),r}}function uT({code:n}){return n==="auth/user-disabled"||n==="auth/user-token-expired"}class lT{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,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){if(e){const t=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),t}else{this.errorBackoff=3e4;const r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class ya{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ur(this.lastLoginAt),this.creationTime=Ur(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Fr(n){const e=n.auth,t=await n.getIdToken(),r=await Gn(n,ui(e,{idToken:t}));M(r?.users.length,e,"internal-error");const s=r.users[0];n._notifyReloadListener(s);const i=s.providerUserInfo?.length?Vh(s.providerUserInfo):[],a=dT(n.providerData,i),c=n.isAnonymous,l=!(n.email&&s.passwordHash)&&!a?.length,d=c?l:!1,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new ya(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(n,f)}async function hT(n){const e=Q(n);await Fr(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function dT(n,e){return[...n.filter(r=>!e.some(s=>s.providerId===r.providerId)),...e]}function Vh(n){return n.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}async function fT(n,e){const t=await kh(n,{},async()=>{const r=ur({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:i}=n.config,a=await Nh(n,s,"/v1/token",`key=${i}`),c=await n._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";const l={method:"POST",headers:c,body:r};return n.emulatorConfig&&tt(n.emulatorConfig.host)&&(l.credentials="include"),Ch.fetch()(a,l)});return{accessToken:t.access_token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}async function pT(n,e){return Je(n,"POST","/v2/accounts:revokeToken",vt(n,e))}class Kn{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){M(e.idToken,"internal-error"),M(typeof e.idToken<"u","internal-error"),M(typeof e.refreshToken<"u","internal-error");const t="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):Oh(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){M(e.length!==0,"internal-error");const t=Oh(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return!t&&this.accessToken&&!this.isExpired?this.accessToken:(M(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:s,expiresIn:i}=await fT(e,t);this.updateTokensAndExpiration(r,s,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,t){const{refreshToken:r,accessToken:s,expirationTime:i}=t,a=new Kn;return r&&(M(typeof r=="string","internal-error",{appName:e}),a.refreshToken=r),s&&(M(typeof s=="string","internal-error",{appName:e}),a.accessToken=s),i&&(M(typeof i=="number","internal-error",{appName:e}),a.expirationTime=i),a}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 Kn,this.toJSON())}_performRefresh(){return wt("not implemented")}}function zt(n,e){M(typeof n=="string"||typeof n>"u","internal-error",{appName:e})}class Xe{constructor({uid:e,auth:t,stsTokenManager:r,...s}){this.providerId="firebase",this.proactiveRefresh=new lT(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new ya(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Gn(this,this.stsTokenManager.getToken(this.auth,e));return M(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return cT(this,e)}reload(){return hT(this)}_assign(e){this!==e&&(M(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(t=>({...t})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new Xe({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){M(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Fr(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Ae(this.auth.app))return Promise.reject(ut(this.auth));const e=await this.getIdToken();return await Gn(this,oT(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,s=t.email??void 0,i=t.phoneNumber??void 0,a=t.photoURL??void 0,c=t.tenantId??void 0,l=t._redirectEventId??void 0,d=t.createdAt??void 0,f=t.lastLoginAt??void 0,{uid:m,emailVerified:g,isAnonymous:R,providerData:C,stsTokenManager:N}=t;M(m&&N,e,"internal-error");const k=Kn.fromJSON(this.name,N);M(typeof m=="string",e,"internal-error"),zt(r,e.name),zt(s,e.name),M(typeof g=="boolean",e,"internal-error"),M(typeof R=="boolean",e,"internal-error"),zt(i,e.name),zt(a,e.name),zt(c,e.name),zt(l,e.name),zt(d,e.name),zt(f,e.name);const F=new Xe({uid:m,auth:e,email:s,emailVerified:g,displayName:r,isAnonymous:R,photoURL:a,phoneNumber:i,tenantId:c,stsTokenManager:k,createdAt:d,lastLoginAt:f});return C&&Array.isArray(C)&&(F.providerData=C.map($=>({...$}))),l&&(F._redirectEventId=l),F}static async _fromIdTokenResponse(e,t,r=!1){const s=new Kn;s.updateFromServerResponse(t);const i=new Xe({uid:t.localId,auth:e,stsTokenManager:s,isAnonymous:r});return await Fr(i),i}static async _fromGetAccountInfoResponse(e,t,r){const s=t.users[0];M(s.localId!==void 0,"internal-error");const i=s.providerUserInfo!==void 0?Vh(s.providerUserInfo):[],a=!(s.email&&s.passwordHash)&&!i?.length,c=new Kn;c.updateFromIdToken(r);const l=new Xe({uid:s.localId,auth:e,stsTokenManager:c,isAnonymous:a}),d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:i,metadata:new ya(s.createdAt,s.lastLoginAt),isAnonymous:!(s.email&&s.passwordHash)&&!i?.length};return Object.assign(l,d),l}}const Lh=new Map;function At(n){It(n instanceof Function,"Expected a class definition");let e=Lh.get(n);return e?(It(e instanceof n,"Instance stored in cache mismatched with class"),e):(e=new n,Lh.set(n,e),e)}class Mh{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===void 0?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Mh.type="NONE";const xh=Mh;function li(n,e,t){return`firebase:${n}:${e}:${t}`}class Qn{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:s,name:i}=this.auth;this.fullUserKey=li(this.userKey,s.apiKey,i),this.fullPersistenceKey=li("persistence",s.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(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){const t=await ui(this.auth,{idToken:e}).catch(()=>{});return t?Xe._fromGetAccountInfoResponse(this.auth,t,e):null}return Xe._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new Qn(At(xh),e,r);const s=(await Promise.all(t.map(async d=>{if(await d._isAvailable())return d}))).filter(d=>d);let i=s[0]||At(xh);const a=li(r,e.config.apiKey,e.name);let c=null;for(const d of t)try{const f=await d._get(a);if(f){let m;if(typeof f=="string"){const g=await ui(e,{idToken:f}).catch(()=>{});if(!g)break;m=await Xe._fromGetAccountInfoResponse(e,g,f)}else m=Xe._fromJSON(e,f);d!==i&&(c=m),i=d;break}}catch{}const l=s.filter(d=>d._shouldAllowMigration);return!i._shouldAllowMigration||!l.length?new Qn(i,e,r):(i=l[0],c&&await i._set(a,c.toJSON()),await Promise.all(t.map(async d=>{if(d!==i)try{await d._remove(a)}catch{}})),new Qn(i,e,r))}}function Uh(n){const e=n.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(jh(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Fh(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(zh(e))return"Blackberry";if(Hh(e))return"Webos";if(Bh(e))return"Safari";if((e.includes("chrome/")||qh(e))&&!e.includes("edge/"))return"Chrome";if($h(e))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=n.match(t);if(r?.length===2)return r[1]}return"Other"}function Fh(n=ve()){return/firefox\//i.test(n)}function Bh(n=ve()){const e=n.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function qh(n=ve()){return/crios\//i.test(n)}function jh(n=ve()){return/iemobile/i.test(n)}function $h(n=ve()){return/android/i.test(n)}function zh(n=ve()){return/blackberry/i.test(n)}function Hh(n=ve()){return/webos/i.test(n)}function Ea(n=ve()){return/iphone|ipad|ipod/i.test(n)||/macintosh/i.test(n)&&/mobile/i.test(n)}function mT(n=ve()){return Ea(n)&&!!window.navigator?.standalone}function gT(){return Sp()&&document.documentMode===10}function Wh(n=ve()){return Ea(n)||$h(n)||Hh(n)||zh(n)||/windows phone/i.test(n)||jh(n)}function Gh(n,e=[]){let t;switch(n){case"Browser":t=Uh(ve());break;case"Worker":t=`${Uh(ve())}-${n}`;break;default:t=n}const r=e.length?e.join(","):"FirebaseCore-web";return`${t}/JsCore/${nn}/${r}`}class _T{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const r=i=>new Promise((a,c)=>{try{const l=e(i);a(l)}catch(l){c(l)}});r.onAbort=t,this.queue.push(r);const s=this.queue.length-1;return()=>{this.queue[s]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(r){t.reverse();for(const s of t)try{s()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}}async function yT(n,e={}){return Je(n,"GET","/v2/passwordPolicy",vt(n,e))}const ET=6;class TT{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??ET,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),t.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),t.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),t.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),t.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,s=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),s&&(t.meetsMaxPasswordLength=e.length<=s)}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);let r;for(let s=0;s<e.length;s++)r=e.charAt(s),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,s,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=s)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class wT{constructor(e,t,r,s){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=s,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Kh(this),this.idTokenSubscription=new Kh(this),this.beforeStateQueue=new _T(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=bh,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=s.sdkClientVersion,this._persistenceManagerAvailable=new Promise(i=>this._resolvePersistenceManagerAvailable=i)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=At(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Qn.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const t=await ui(this,{idToken:e}),r=await Xe._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(t){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",t),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(Ae(this.app)){const i=this.app.settings.authIdToken;return i?new Promise(a=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(i).then(a,a))}):this.directlySetCurrentUser(null)}const t=await this.assertedPersistence.getCurrentUser();let r=t,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const i=this.redirectUser?._redirectEventId,a=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!i||i===a)&&c?.user&&(r=c.user,s=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(r)}catch(i){r=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(i))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return M(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Fr(e)}catch(t){if(t?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=XE()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Ae(this.app))return Promise.reject(ut(this));const t=e?Q(e):null;return t&&M(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&M(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Ae(this.app)?Promise.reject(ut(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Ae(this.app)?Promise.reject(ut(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(At(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await yT(this),t=new TT(e);this.tenantId===null?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new cr("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged(()=>{r(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};this.tenantId!=null&&(r.tenantId=this.tenantId),await pT(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&At(e)||this._popupRedirectResolver;M(t,this,"argument-error"),this.redirectPersistenceManager=await Qn.create(this,[At(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,s){if(this._deleted)return()=>{};const i=typeof t=="function"?t:t.next.bind(t);let a=!1;const c=this._isInitialized?Promise.resolve():this._initializationPromise;if(M(c,this,"internal-error"),c.then(()=>{a||i(this.currentUser)}),typeof t=="function"){const l=e.addObserver(t,r,s);return()=>{a=!0,l()}}else{const l=e.addObserver(t);return()=>{a=!0,l()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return M(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Gh(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);const t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(Ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&QE(`Error while retrieving App Check token: ${e.error}`),e?.token}}function lt(n){return Q(n)}class Kh{constructor(e){this.auth=e,this.observer=null,this.addObserver=Mp(t=>this.observer=t)}get next(){return M(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let hi={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function IT(n){hi=n}function Qh(n){return hi.loadJS(n)}function vT(){return hi.recaptchaEnterpriseScript}function AT(){return hi.gapiScript}function RT(n){return`__${n}${Math.floor(Math.random()*1e6)}`}class bT{constructor(){this.enterprise=new PT}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class PT{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}const ST="recaptcha-enterprise",Yh="NO_RECAPTCHA";class CT{constructor(e){this.type=ST,this.auth=lt(e)}async verify(e="verify",t=!1){async function r(i){if(!t){if(i.tenantId==null&&i._agentRecaptchaConfig!=null)return i._agentRecaptchaConfig.siteKey;if(i.tenantId!=null&&i._tenantRecaptchaConfigs[i.tenantId]!==void 0)return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(a,c)=>{iT(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(l=>{if(l.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{const d=new sT(l);return i.tenantId==null?i._agentRecaptchaConfig=d:i._tenantRecaptchaConfigs[i.tenantId]=d,a(d.siteKey)}}).catch(l=>{c(l)})})}function s(i,a,c){const l=window.grecaptcha;Dh(l)?l.enterprise.ready(()=>{l.enterprise.execute(i,{action:e}).then(d=>{a(d)}).catch(()=>{a(Yh)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new bT().execute("siteKey",{action:"verify"}):new Promise((i,a)=>{r(this.auth).then(c=>{if(!t&&Dh(window.grecaptcha))s(c,i,a);else{if(typeof window>"u"){a(new Error("RecaptchaVerifier is only supported in browser"));return}let l=vT();l.length!==0&&(l+=c),Qh(l).then(()=>{s(c,i,a)}).catch(d=>{a(d)})}}).catch(c=>{a(c)})})}}async function Jh(n,e,t,r=!1,s=!1){const i=new CT(n);let a;if(s)a=Yh;else try{a=await i.verify(t)}catch{a=await i.verify(t,!0)}const c={...e};if(t==="mfaSmsEnrollment"||t==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){const l=c.phoneEnrollmentInfo.phoneNumber,d=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:l,recaptchaToken:d,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){const l=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:l,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return r?Object.assign(c,{captchaResp:a}):Object.assign(c,{captchaResponse:a}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function di(n,e,t,r,s){if(n._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await Jh(n,e,t,t==="getOobCode");return r(n,i)}else return r(n,e).catch(async i=>{if(i.code==="auth/missing-recaptcha-token"){console.log(`${t} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const a=await Jh(n,e,t,t==="getOobCode");return r(n,a)}else return Promise.reject(i)})}function kT(n,e){const t=dr(n,"auth");if(t.isInitialized()){const s=t.getImmediate(),i=t.getOptions();if(en(i,e??{}))return s;He(s,"already-initialized")}return t.initialize({options:e})}function NT(n,e){const t=e?.persistence||[],r=(Array.isArray(t)?t:[t]).map(At);e?.errorMap&&n._updateErrorMap(e.errorMap),n._initializeWithPersistence(r,e?.popupRedirectResolver)}function Xh(n,e,t){const r=lt(n);M(/^https?:\/\//.test(e),r,"invalid-emulator-scheme");const s=!1,i=Zh(e),{host:a,port:c}=DT(e),l=c===null?"":`:${c}`,d={url:`${i}//${a}${l}/`},f=Object.freeze({host:a,port:c,protocol:i.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!r._canInitEmulator){M(r.config.emulator&&r.emulatorConfig,r,"emulator-config-failed"),M(en(d,r.config.emulator)&&en(f,r.emulatorConfig),r,"emulator-config-failed");return}r.config.emulator=d,r.emulatorConfig=f,r.settings.appVerificationDisabledForTesting=!0,tt(a)?(ls(`${i}//${a}${l}`),hs("Auth",!0)):OT()}function Zh(n){const e=n.indexOf(":");return e<0?"":n.substr(0,e+1)}function DT(n){const e=Zh(n),t=/(\/\/)?([^?#/]+)/.exec(n.substr(e.length));if(!t)return{host:"",port:null};const r=t[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(r);if(s){const i=s[1];return{host:i,port:ed(r.substr(i.length+1))}}else{const[i,a]=r.split(":");return{host:i,port:ed(a)}}}function ed(n){if(!n)return null;const e=Number(n);return isNaN(e)?null:e}function OT(){function n(){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)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",n):n())}class Ta{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return wt("not implemented")}_getIdTokenResponse(e){return wt("not implemented")}_linkToIdToken(e,t){return wt("not implemented")}_getReauthenticationResolver(e){return wt("not implemented")}}async function VT(n,e){return Je(n,"POST","/v1/accounts:signUp",e)}async function LT(n,e){return xr(n,"POST","/v1/accounts:signInWithPassword",vt(n,e))}async function td(n,e){return Je(n,"POST","/v1/accounts:sendOobCode",vt(n,e))}async function MT(n,e){return td(n,e)}async function xT(n,e){return td(n,e)}async function UT(n,e){return xr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}async function FT(n,e){return xr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}class Br extends Ta{constructor(e,t,r,s=null){super("password",r),this._email=e,this._password=t,this._tenantId=s}static _fromEmailAndPassword(e,t){return new Br(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new Br(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e;if(t?.email&&t?.password){if(t.signInMethod==="password")return this._fromEmailAndPassword(t.email,t.password);if(t.signInMethod==="emailLink")return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":const t={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return di(e,t,"signInWithPassword",LT);case"emailLink":return UT(e,{email:this._email,oobCode:this._password});default:He(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":const r={idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return di(e,r,"signUpPassword",VT);case"emailLink":return FT(e,{idToken:t,email:this._email,oobCode:this._password});default:He(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Yn(n,e){return xr(n,"POST","/v1/accounts:signInWithIdp",vt(n,e))}const BT="http://localhost";class pn extends Ta{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new pn(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):He("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){const t=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:s,...i}=t;if(!r||!s)return null;const a=new pn(r,s);return a.idToken=i.idToken||void 0,a.accessToken=i.accessToken||void 0,a.secret=i.secret,a.nonce=i.nonce,a.pendingToken=i.pendingToken||null,a}_getIdTokenResponse(e){const t=this.buildRequest();return Yn(e,t)}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,Yn(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Yn(e,t)}buildRequest(){const e={requestUri:BT,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=ur(t)}return e}}function qT(n){switch(n){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}}function jT(n){const e=lr(hr(n)).link,t=e?lr(hr(e)).deep_link_id:null,r=lr(hr(n)).deep_link_id;return(r?lr(hr(r)).link:null)||r||t||e||n}class wa{constructor(e){const t=lr(hr(e)),r=t.apiKey??null,s=t.oobCode??null,i=qT(t.mode??null);M(r&&s&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=s,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=jT(e);try{return new wa(t)}catch{return null}}}class Jn{constructor(){this.providerId=Jn.PROVIDER_ID}static credential(e,t){return Br._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=wa.parseLink(t);return M(r,"argument-error"),Br._fromEmailAndCode(e,r.code,r.tenantId)}}Jn.PROVIDER_ID="password",Jn.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Jn.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class fi{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 qr extends fi{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ht extends qr{constructor(){super("facebook.com")}static credential(e){return pn._fromParams({providerId:ht.PROVIDER_ID,signInMethod:ht.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ht.credentialFromTaggedObject(e)}static credentialFromError(e){return ht.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return ht.credential(e.oauthAccessToken)}catch{return null}}}ht.FACEBOOK_SIGN_IN_METHOD="facebook.com",ht.PROVIDER_ID="facebook.com";class dt extends qr{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return pn._fromParams({providerId:dt.PROVIDER_ID,signInMethod:dt.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return dt.credentialFromTaggedObject(e)}static credentialFromError(e){return dt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return dt.credential(t,r)}catch{return null}}}dt.GOOGLE_SIGN_IN_METHOD="google.com",dt.PROVIDER_ID="google.com";class Ht extends qr{constructor(){super("github.com")}static credential(e){return pn._fromParams({providerId:Ht.PROVIDER_ID,signInMethod:Ht.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Ht.credentialFromTaggedObject(e)}static credentialFromError(e){return Ht.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return Ht.credential(e.oauthAccessToken)}catch{return null}}}Ht.GITHUB_SIGN_IN_METHOD="github.com",Ht.PROVIDER_ID="github.com";class Ze extends qr{constructor(){super("twitter.com")}static credential(e,t){return pn._fromParams({providerId:Ze.PROVIDER_ID,signInMethod:Ze.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Ze.credentialFromTaggedObject(e)}static credentialFromError(e){return Ze.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return Ze.credential(t,r)}catch{return null}}}Ze.TWITTER_SIGN_IN_METHOD="twitter.com",Ze.PROVIDER_ID="twitter.com";async function nd(n,e){return xr(n,"POST","/v1/accounts:signUp",vt(n,e))}class Rt{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,s=!1){const i=await Xe._fromIdTokenResponse(e,r,s),a=rd(r);return new Rt({user:i,providerId:a,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const s=rd(r);return new Rt({user:e,providerId:s,_tokenResponse:r,operationType:t})}}function rd(n){return n.providerId?n.providerId:"phoneNumber"in n?"phone":null}async function $T(n){if(Ae(n.app))return Promise.reject(ut(n));const e=lt(n);if(await e._initializationPromise,e.currentUser?.isAnonymous)return new Rt({user:e.currentUser,providerId:null,operationType:"signIn"});const t=await nd(e,{returnSecureToken:!0}),r=await Rt._fromIdTokenResponse(e,"signIn",t,!0);return await e._updateCurrentUser(r.user),r}class pi extends We{constructor(e,t,r,s){super(t.code,t.message),this.operationType=r,this.user=s,Object.setPrototypeOf(this,pi.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,s){return new pi(e,t,r,s)}}function sd(n,e,t,r){return(e==="reauthenticate"?t._getReauthenticationResolver(n):t._getIdTokenResponse(n)).catch(i=>{throw i.code==="auth/multi-factor-auth-required"?pi._fromErrorAndOperation(n,i,e,r):i})}function id(n){return new Set(n.map(({providerId:e})=>e).filter(e=>!!e))}async function zT(n,e){const t=Q(n);await WT(!0,t,e);const{providerUserInfo:r}=await aT(t.auth,{idToken:await t.getIdToken(),deleteProvider:[e]}),s=id(r||[]);return t.providerData=t.providerData.filter(i=>s.has(i.providerId)),s.has("phone")||(t.phoneNumber=null),await t.auth._persistUserIfCurrent(t),t}async function HT(n,e,t=!1){const r=await Gn(n,e._linkToIdToken(n.auth,await n.getIdToken()),t);return Rt._forOperation(n,"link",r)}async function WT(n,e,t){await Fr(e);const r=id(e.providerData);M(r.has(t)===n,e.auth,"no-such-provider")}async function GT(n,e,t=!1){const{auth:r}=n;if(Ae(r.app))return Promise.reject(ut(r));const s="reauthenticate";try{const i=await Gn(n,sd(r,s,e,n),t);M(i.idToken,r,"internal-error");const a=_a(i.idToken);M(a,r,"internal-error");const{sub:c}=a;return M(n.uid===c,r,"user-mismatch"),Rt._forOperation(n,s,i)}catch(i){throw i?.code==="auth/user-not-found"&&He(r,"user-mismatch"),i}}async function od(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r="signIn",s=await sd(n,r,e),i=await Rt._fromIdTokenResponse(n,r,s);return t||await n._updateCurrentUser(i.user),i}async function KT(n,e){return od(lt(n),e)}function QT(n,e,t){M(t.url?.length>0,n,"invalid-continue-uri"),M(typeof t.dynamicLinkDomain>"u"||t.dynamicLinkDomain.length>0,n,"invalid-dynamic-link-domain"),M(typeof t.linkDomain>"u"||t.linkDomain.length>0,n,"invalid-hosting-link-domain"),e.continueUrl=t.url,e.dynamicLinkDomain=t.dynamicLinkDomain,e.linkDomain=t.linkDomain,e.canHandleCodeInApp=t.handleCodeInApp,t.iOS&&(M(t.iOS.bundleId.length>0,n,"missing-ios-bundle-id"),e.iOSBundleId=t.iOS.bundleId),t.android&&(M(t.android.packageName.length>0,n,"missing-android-pkg-name"),e.androidInstallApp=t.android.installApp,e.androidMinimumVersionCode=t.android.minimumVersion,e.androidPackageName=t.android.packageName)}async function ad(n){const e=lt(n);e._getPasswordPolicyInternal()&&await e._updatePasswordPolicy()}async function YT(n,e,t){const r=lt(n);await di(r,{requestType:"PASSWORD_RESET",email:e,clientType:"CLIENT_TYPE_WEB"},"getOobCode",xT)}async function JT(n,e,t){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),a=await di(r,{returnSecureToken:!0,email:e,password:t,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",nd).catch(l=>{throw l.code==="auth/password-does-not-meet-requirements"&&ad(n),l}),c=await Rt._fromIdTokenResponse(r,"signIn",a);return await r._updateCurrentUser(c.user),c}function cd(n,e,t){return Ae(n.app)?Promise.reject(ut(n)):KT(Q(n),Jn.credential(e,t)).catch(async r=>{throw r.code==="auth/password-does-not-meet-requirements"&&ad(n),r})}async function ud(n,e){const t=Q(n),s={requestType:"VERIFY_EMAIL",idToken:await n.getIdToken()};e&&QT(t.auth,s,e);const{email:i}=await MT(t.auth,s);i!==n.email&&await n.reload()}async function XT(n,e){return Je(n,"POST","/v1/accounts:update",e)}async function ZT(n,{displayName:e,photoURL:t}){if(e===void 0&&t===void 0)return;const r=Q(n),i={idToken:await r.getIdToken(),displayName:e,photoUrl:t,returnSecureToken:!0},a=await Gn(r,XT(r.auth,i));r.displayName=a.displayName||null,r.photoURL=a.photoUrl||null;const c=r.providerData.find(({providerId:l})=>l==="password");c&&(c.displayName=r.displayName,c.photoURL=r.photoURL),await r._updateTokensIfNecessary(a)}function ew(n,e,t,r){return Q(n).onIdTokenChanged(e,t,r)}function tw(n,e,t){return Q(n).beforeAuthStateChanged(e,t)}const mi="__sak";class ld{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(mi,"1"),this.storage.removeItem(mi),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const 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()}}const nw=1e3,rw=10;class hd extends ld{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=Wh(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),s=this.localCache[t];r!==s&&e(t,s,r)}}onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((a,c,l)=>{this.notifyListeners(a,l)});return}const r=e.key;t?this.detachListener():this.stopPolling();const s=()=>{const a=this.storage.getItem(r);!t&&this.localCache[r]===a||this.notifyListeners(r,a)},i=this.storage.getItem(r);gT()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(s,rw):s()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)})},nw)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){Object.keys(this.listeners).length===0&&(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),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}hd.type="LOCAL";const sw=hd;class dd extends ld{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}dd.type="SESSION";const fd=dd;function iw(n){return Promise.all(n.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}class gi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find(s=>s.isListeningto(e));if(t)return t;const r=new gi(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:s,data:i}=t.data,a=this.handlersMap[s];if(!a?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:s});const c=Array.from(a).map(async d=>d(t.origin,i)),l=await iw(c);t.ports[0].postMessage({status:"done",eventId:r,eventType:s,response:l})}_subscribe(e,t){Object.keys(this.handlersMap).length===0&&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||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}gi.receivers=[];function Ia(n="",e=10){let t="";for(let r=0;r<e;r++)t+=Math.floor(Math.random()*10);return n+t}class ow{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const s=typeof MessageChannel<"u"?new MessageChannel:null;if(!s)throw new Error("connection_unavailable");let i,a;return new Promise((c,l)=>{const d=Ia("",20);s.port1.start();const f=setTimeout(()=>{l(new Error("unsupported_event"))},r);a={messageChannel:s,onMessage(m){const g=m;if(g.data.eventId===d)switch(g.data.status){case"ack":clearTimeout(f),i=setTimeout(()=>{l(new Error("timeout"))},3e3);break;case"done":clearTimeout(i),c(g.data.response);break;default:clearTimeout(f),clearTimeout(i),l(new Error("invalid_response"));break}}},this.handlers.add(a),s.port1.addEventListener("message",a.onMessage),this.target.postMessage({eventType:e,eventId:d,data:t},[s.port2])}).finally(()=>{a&&this.removeMessageHandler(a)})}}function ft(){return window}function aw(n){ft().location.href=n}function pd(){return typeof ft().WorkerGlobalScope<"u"&&typeof ft().importScripts=="function"}async function cw(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function uw(){return navigator?.serviceWorker?.controller||null}function lw(){return pd()?self:null}const md="firebaseLocalStorageDb",hw=1,_i="firebaseLocalStorage",gd="fbase_key";class jr{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 yi(n,e){return n.transaction([_i],e?"readwrite":"readonly").objectStore(_i)}function dw(){const n=indexedDB.deleteDatabase(md);return new jr(n).toPromise()}function va(){const n=indexedDB.open(md,hw);return new Promise((e,t)=>{n.addEventListener("error",()=>{t(n.error)}),n.addEventListener("upgradeneeded",()=>{const r=n.result;try{r.createObjectStore(_i,{keyPath:gd})}catch(s){t(s)}}),n.addEventListener("success",async()=>{const r=n.result;r.objectStoreNames.contains(_i)?e(r):(r.close(),await dw(),e(await va()))})})}async function _d(n,e,t){const r=yi(n,!0).put({[gd]:e,value:t});return new jr(r).toPromise()}async function fw(n,e){const t=yi(n,!1).get(e),r=await new jr(t).toPromise();return r===void 0?null:r.value}function yd(n,e){const t=yi(n,!0).delete(e);return new jr(t).toPromise()}const pw=800,mw=3;class Ed{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:(this.db=await va(),this.db)}async _withRetries(e){let t=0;for(;;)try{const r=await this._openDb();return await e(r)}catch(r){if(t++>mw)throw r;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return pd()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=gi._getInstance(lw()),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){if(this.activeServiceWorker=await cw(),!this.activeServiceWorker)return;this.sender=new ow(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||uw()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await va();return await _d(e,mi,"1"),await yd(e,mi),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(r=>_d(r,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(r=>fw(r,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>yd(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(s=>{const i=yi(s,!1).getAll();return new jr(i).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const t=[],r=new Set;if(e.length!==0)for(const{fbase_key:s,value:i}of e)r.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(i)&&(this.notifyListeners(s,i),t.push(s));for(const s of Object.keys(this.localCache))this.localCache[s]&&!r.has(s)&&(this.notifyListeners(s,null),t.push(s));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),pw)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){Object.keys(this.listeners).length===0&&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),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}Ed.type="LOCAL";const gw=Ed;new Mr(3e4,6e4);function Aa(n,e){return e?At(e):(M(n._popupRedirectResolver,n,"argument-error"),n._popupRedirectResolver)}class Ra extends Ta{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Yn(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Yn(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Yn(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 _w(n){return od(n.auth,new Ra(n),n.bypassAuthState)}function yw(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),GT(t,new Ra(n),n.bypassAuthState)}async function Ew(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),HT(t,new Ra(n),n.bypassAuthState)}class Td{constructor(e,t,r,s,i=!1){this.auth=e,this.resolver=r,this.user=s,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(r){this.reject(r)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:s,tenantId:i,error:a,type:c}=e;if(a){this.reject(a);return}const l={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(c)(l))}catch(d){this.reject(d)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _w;case"linkViaPopup":case"linkViaRedirect":return Ew;case"reauthViaPopup":case"reauthViaRedirect":return yw;default:He(this.auth,"internal-error")}}resolve(e){It(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){It(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 Tw=new Mr(2e3,1e4);async function ba(n,e,t){if(Ae(n.app))return Promise.reject(Ye(n,"operation-not-supported-in-this-environment"));const r=lt(n);Ph(n,e,fi);const s=Aa(r,t);return new Wt(r,"signInViaPopup",e,s).executeNotNull()}async function wd(n,e,t){const r=Q(n);Ph(r.auth,e,fi);const s=Aa(r.auth,t);return new Wt(r.auth,"linkViaPopup",e,s,r).executeNotNull()}class Wt extends Td{constructor(e,t,r,s,i){super(e,t,s,i),this.provider=r,this.authWindow=null,this.pollId=null,Wt.currentPopupAction&&Wt.currentPopupAction.cancel(),Wt.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return M(e,this.auth,"internal-error"),e}async onExecution(){It(this.filter.length===1,"Popup operations only handle one event");const e=Ia();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(t=>{this.reject(t)}),this.resolver._isIframeWebStorageSupported(this.auth,t=>{t||this.reject(Ye(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(Ye(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Wt.currentPopupAction=null}pollUserCancellation(){const e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ye(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,Tw.get())};e()}}Wt.currentPopupAction=null;const ww="pendingRedirect",Ei=new Map;class Iw extends Td{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=Ei.get(this.auth._key());if(!e){try{const r=await vw(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(r)}catch(t){e=()=>Promise.reject(t)}Ei.set(this.auth._key(),e)}return this.bypassAuthState||Ei.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function vw(n,e){const t=bw(e),r=Rw(n);if(!await r._isAvailable())return!1;const s=await r._get(t)==="true";return await r._remove(t),s}function Aw(n,e){Ei.set(n._key(),e)}function Rw(n){return At(n._redirectPersistence)}function bw(n){return li(ww,n.config.apiKey,n.name)}async function Pw(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),s=Aa(r,e),a=await new Iw(r,s,t).execute();return a&&!t&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,e)),a}const Sw=10*60*1e3;class Cw{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!kw(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!vd(e)){const r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(Ye(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=Sw&&this.cachedEventUids.clear(),this.cachedEventUids.has(Id(e))}saveEventToCache(e){this.cachedEventUids.add(Id(e)),this.lastProcessedEventTime=Date.now()}}function Id(n){return[n.type,n.eventId,n.sessionId,n.tenantId].filter(e=>e).join("-")}function vd({type:n,error:e}){return n==="unknown"&&e?.code==="auth/no-auth-event"}function kw(n){switch(n.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return vd(n);default:return!1}}async function Nw(n,e={}){return Je(n,"GET","/v1/projects",e)}const Dw=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Ow=/^https?/;async function Vw(n){if(n.config.emulator)return;const{authorizedDomains:e}=await Nw(n);for(const t of e)try{if(Lw(t))return}catch{}He(n,"unauthorized-domain")}function Lw(n){const e=pa(),{protocol:t,hostname:r}=new URL(e);if(n.startsWith("chrome-extension://")){const a=new URL(n);return a.hostname===""&&r===""?t==="chrome-extension:"&&n.replace("chrome-extension://","")===e.replace("chrome-extension://",""):t==="chrome-extension:"&&a.hostname===r}if(!Ow.test(t))return!1;if(Dw.test(n))return r===n;const s=n.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(r)}const Mw=new Mr(3e4,6e4);function Ad(){const n=ft().___jsl;if(n?.H){for(const e of Object.keys(n.H))if(n.H[e].r=n.H[e].r||[],n.H[e].L=n.H[e].L||[],n.H[e].r=[...n.H[e].L],n.CP)for(let t=0;t<n.CP.length;t++)n.CP[t]=null}}function xw(n){return new Promise((e,t)=>{function r(){Ad(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Ad(),t(Ye(n,"network-request-failed"))},timeout:Mw.get()})}if(ft().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else if(ft().gapi?.load)r();else{const s=RT("iframefcb");return ft()[s]=()=>{gapi.load?r():t(Ye(n,"network-request-failed"))},Qh(`${AT()}?onload=${s}`).catch(i=>t(i))}}).catch(e=>{throw Ti=null,e})}let Ti=null;function Uw(n){return Ti=Ti||xw(n),Ti}const Fw=new Mr(5e3,15e3),Bw="__/auth/iframe",qw="emulator/auth/iframe",jw={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},$w=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function zw(n){const e=n.config;M(e.authDomain,n,"auth-domain-config-required");const t=e.emulator?ma(e,qw):`https://${n.config.authDomain}/${Bw}`,r={apiKey:e.apiKey,appName:n.name,v:nn},s=$w.get(n.config.apiHost);s&&(r.eid=s);const i=n._getFrameworks();return i.length&&(r.fw=i.join(",")),`${t}?${ur(r).slice(1)}`}async function Hw(n){const e=await Uw(n),t=ft().gapi;return M(t,n,"internal-error"),e.open({where:document.body,url:zw(n),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:jw,dontclear:!0},r=>new Promise(async(s,i)=>{await r.restyle({setHideOnLeave:!1});const a=Ye(n,"network-request-failed"),c=ft().setTimeout(()=>{i(a)},Fw.get());function l(){ft().clearTimeout(c),s(r)}r.ping(l).then(l,()=>{i(a)})}))}const Ww={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},Gw=500,Kw=600,Qw="_blank",Yw="http://localhost";class Rd{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function Jw(n,e,t,r=Gw,s=Kw){const i=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const l={...Ww,width:r.toString(),height:s.toString(),top:i,left:a},d=ve().toLowerCase();t&&(c=qh(d)?Qw:t),Fh(d)&&(e=e||Yw,l.scrollbars="yes");const f=Object.entries(l).reduce((g,[R,C])=>`${g}${R}=${C},`,"");if(mT(d)&&c!=="_self")return Xw(e||"",c),new Rd(null);const m=window.open(e||"",c,f);M(m,n,"popup-blocked");try{m.focus()}catch{}return new Rd(m)}function Xw(n,e){const t=document.createElement("a");t.href=n,t.target=e;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),t.dispatchEvent(r)}const Zw="__/auth/handler",eI="emulator/auth/handler",tI=encodeURIComponent("fac");async function bd(n,e,t,r,s,i){M(n.config.authDomain,n,"auth-domain-config-required"),M(n.config.apiKey,n,"invalid-api-key");const a={apiKey:n.config.apiKey,appName:n.name,authType:t,redirectUrl:r,v:nn,eventId:s};if(e instanceof fi){e.setDefaultLanguage(n.languageCode),a.providerId=e.providerId||"",Lp(e.getCustomParameters())||(a.customParameters=JSON.stringify(e.getCustomParameters()));for(const[f,m]of Object.entries({}))a[f]=m}if(e instanceof qr){const f=e.getScopes().filter(m=>m!=="");f.length>0&&(a.scopes=f.join(","))}n.tenantId&&(a.tid=n.tenantId);const c=a;for(const f of Object.keys(c))c[f]===void 0&&delete c[f];const l=await n._getAppCheckToken(),d=l?`#${tI}=${encodeURIComponent(l)}`:"";return`${nI(n)}?${ur(c).slice(1)}${d}`}function nI({config:n}){return n.emulator?ma(n,eI):`https://${n.authDomain}/${Zw}`}const Pa="webStorageSupport";class rI{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=fd,this._completeRedirectFn=Pw,this._overrideRedirectResult=Aw}async _openPopup(e,t,r,s){It(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const i=await bd(e,t,r,pa(),s);return Jw(e,i,Ia())}async _openRedirect(e,t,r,s){await this._originValidation(e);const i=await bd(e,t,r,pa(),s);return aw(i),new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:s,promise:i}=this.eventManagers[t];return s?Promise.resolve(s):(It(i,"If manager is not set, promise should be"),i)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch(()=>{delete this.eventManagers[t]}),r}async initAndGetManager(e){const t=await Hw(e),r=new Cw(e);return t.register("authEvent",s=>(M(s?.authEvent,e,"invalid-auth-event"),{status:r.onEvent(s.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(Pa,{type:Pa},s=>{const i=s?.[0]?.[Pa];i!==void 0&&t(!!i),He(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Vw(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Wh()||Bh()||Ea()}}const sI=rI;var Pd="@firebase/auth",Sd="1.12.0";class iI{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){M(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function oI(n){switch(n){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function aI(n){St(new _t("auth",(e,{options:t})=>{const r=e.getProvider("app").getImmediate(),s=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:a,authDomain:c}=r.options;M(a&&!a.includes(":"),"invalid-api-key",{appName:r.name});const l={apiKey:a,authDomain:c,clientPlatform:n,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Gh(n)},d=new wT(r,s,i,l);return NT(d,t),d},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),St(new _t("auth-internal",e=>{const t=lt(e.getProvider("auth").getImmediate());return(r=>new iI(r))(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),je(Pd,Sd,oI(n)),je(Pd,Sd,"esm2020")}const cI=5*60,uI=_c("authIdTokenMaxAge")||cI;let Cd=null;const lI=n=>async e=>{const t=e&&await e.getIdTokenResult(),r=t&&(new Date().getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>uI)return;const s=t?.token;Cd!==s&&(Cd=s,await fetch(n,{method:s?"POST":"DELETE",headers:s?{Authorization:`Bearer ${s}`}:{}}))};function hI(n=fs()){const e=dr(n,"auth");if(e.isInitialized())return e.getImmediate();const t=kT(n,{popupRedirectResolver:sI,persistence:[gw,sw,fd]}),r=_c("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const i=new URL(r,location.origin);if(location.origin===i.origin){const a=lI(i.toString());tw(t,a,()=>a(t.currentUser)),ew(t,c=>a(c))}}const s=mc("auth");return s&&Xh(t,`http://${s}`),t}function dI(){return document.getElementsByTagName("head")?.[0]??document}IT({loadJS(n){return new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",n),r.onload=e,r.onerror=s=>{const i=Ye("internal-error");i.customData=s,t(i)},r.type="text/javascript",r.charset="UTF-8",dI().appendChild(r)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="}),aI("Browser");const kd="firebasestorage.googleapis.com",Nd="storageBucket",fI=2*60*1e3,pI=10*60*1e3,mI=1e3;class ie extends We{constructor(e,t,r=0){super(Sa(e),`Firebase Storage: ${t} (${Sa(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,ie.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return Sa(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
43
- ${this.customData.serverResponse}`:this.message=this._baseMessage}}var te;(function(n){n.UNKNOWN="unknown",n.OBJECT_NOT_FOUND="object-not-found",n.BUCKET_NOT_FOUND="bucket-not-found",n.PROJECT_NOT_FOUND="project-not-found",n.QUOTA_EXCEEDED="quota-exceeded",n.UNAUTHENTICATED="unauthenticated",n.UNAUTHORIZED="unauthorized",n.UNAUTHORIZED_APP="unauthorized-app",n.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",n.INVALID_CHECKSUM="invalid-checksum",n.CANCELED="canceled",n.INVALID_EVENT_NAME="invalid-event-name",n.INVALID_URL="invalid-url",n.INVALID_DEFAULT_BUCKET="invalid-default-bucket",n.NO_DEFAULT_BUCKET="no-default-bucket",n.CANNOT_SLICE_BLOB="cannot-slice-blob",n.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",n.NO_DOWNLOAD_URL="no-download-url",n.INVALID_ARGUMENT="invalid-argument",n.INVALID_ARGUMENT_COUNT="invalid-argument-count",n.APP_DELETED="app-deleted",n.INVALID_ROOT_OPERATION="invalid-root-operation",n.INVALID_FORMAT="invalid-format",n.INTERNAL_ERROR="internal-error",n.UNSUPPORTED_ENVIRONMENT="unsupported-environment"})(te||(te={}));function Sa(n){return"storage/"+n}function Ca(){const n="An unknown error occurred, please check the error payload for server response.";return new ie(te.UNKNOWN,n)}function gI(n){return new ie(te.OBJECT_NOT_FOUND,"Object '"+n+"' does not exist.")}function _I(n){return new ie(te.QUOTA_EXCEEDED,"Quota for bucket '"+n+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function yI(){const n="User is not authenticated, please authenticate using Firebase Authentication and try again.";return new ie(te.UNAUTHENTICATED,n)}function EI(){return new ie(te.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}function TI(n){return new ie(te.UNAUTHORIZED,"User does not have permission to access '"+n+"'.")}function Dd(){return new ie(te.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function Od(){return new ie(te.CANCELED,"User canceled the upload/download.")}function wI(n){return new ie(te.INVALID_URL,"Invalid URL '"+n+"'.")}function II(n){return new ie(te.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+n+"'.")}function vI(){return new ie(te.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+Nd+"' property when initializing the app?")}function Vd(){return new ie(te.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function AI(){return new ie(te.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function RI(){return new ie(te.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function bI(n){return new ie(te.UNSUPPORTED_ENVIRONMENT,`${n} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}function ka(n){return new ie(te.INVALID_ARGUMENT,n)}function Ld(){return new ie(te.APP_DELETED,"The Firebase app was deleted.")}function PI(n){return new ie(te.INVALID_ROOT_OPERATION,"The operation '"+n+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function $r(n,e){return new ie(te.INVALID_FORMAT,"String does not match format '"+n+"': "+e)}function zr(n){throw new ie(te.INTERNAL_ERROR,"Internal error: "+n)}class Be{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return this.path.length===0}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let r;try{r=Be.makeFromUrl(e,t)}catch{return new Be(e,"")}if(r.path==="")return r;throw II(e)}static makeFromUrl(e,t){let r=null;const s="([A-Za-z0-9.\\-_]+)";function i(J){J.path.charAt(J.path.length-1)==="/"&&(J.path_=J.path_.slice(0,-1))}const a="(/(.*))?$",c=new RegExp("^gs://"+s+a,"i"),l={bucket:1,path:3};function d(J){J.path_=decodeURIComponent(J.path)}const f="v[A-Za-z0-9_]+",m=t.replace(/[.]/g,"\\."),g="(/([^?#]*).*)?$",R=new RegExp(`^https?://${m}/${f}/b/${s}/o${g}`,"i"),C={bucket:1,path:3},N=t===kd?"(?:storage.googleapis.com|storage.cloud.google.com)":t,k="([^?#]*)",F=new RegExp(`^https?://${N}/${s}/${k}`,"i"),j=[{regex:c,indices:l,postModify:i},{regex:R,indices:C,postModify:d},{regex:F,indices:{bucket:1,path:2},postModify:d}];for(let J=0;J<j.length;J++){const _e=j[J],re=_e.regex.exec(e);if(re){const w=re[_e.indices.bucket];let _=re[_e.indices.path];_||(_=""),r=new Be(w,_),_e.postModify(r);break}}if(r==null)throw wI(e);return r}}class SI{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function CI(n,e,t){let r=1,s=null,i=null,a=!1,c=0;function l(){return c===2}let d=!1;function f(...k){d||(d=!0,e.apply(null,k))}function m(k){s=setTimeout(()=>{s=null,n(R,l())},k)}function g(){i&&clearTimeout(i)}function R(k,...F){if(d){g();return}if(k){g(),f.call(null,k,...F);return}if(l()||a){g(),f.call(null,k,...F);return}r<64&&(r*=2);let j;c===1?(c=2,j=0):j=(r+Math.random())*1e3,m(j)}let C=!1;function N(k){C||(C=!0,g(),!d&&(s!==null?(k||(c=2),clearTimeout(s),m(0)):k||(c=1)))}return m(0),i=setTimeout(()=>{a=!0,N(!0)},t),N}function kI(n){n(!1)}function NI(n){return n!==void 0}function DI(n){return typeof n=="function"}function OI(n){return typeof n=="object"&&!Array.isArray(n)}function wi(n){return typeof n=="string"||n instanceof String}function Md(n){return Na()&&n instanceof Blob}function Na(){return typeof Blob<"u"}function xd(n,e,t,r){if(r<e)throw ka(`Invalid value for '${n}'. Expected ${e} or greater.`);if(r>t)throw ka(`Invalid value for '${n}'. Expected ${t} or less.`)}function Xn(n,e,t){let r=e;return t==null&&(r=`https://${e}`),`${t}://${r}/v0${n}`}function Ud(n){const e=encodeURIComponent;let t="?";for(const r in n)if(n.hasOwnProperty(r)){const s=e(r)+"="+e(n[r]);t=t+s+"&"}return t=t.slice(0,-1),t}var mn;(function(n){n[n.NO_ERROR=0]="NO_ERROR",n[n.NETWORK_ERROR=1]="NETWORK_ERROR",n[n.ABORT=2]="ABORT"})(mn||(mn={}));function Fd(n,e){const t=n>=500&&n<600,s=[408,429].indexOf(n)!==-1,i=e.indexOf(n)!==-1;return t||s||i}class VI{constructor(e,t,r,s,i,a,c,l,d,f,m,g=!0,R=!1){this.url_=e,this.method_=t,this.headers_=r,this.body_=s,this.successCodes_=i,this.additionalRetryCodes_=a,this.callback_=c,this.errorCallback_=l,this.timeout_=d,this.progressCallback_=f,this.connectionFactory_=m,this.retry=g,this.isUsingEmulator=R,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((C,N)=>{this.resolve_=C,this.reject_=N,this.start_()})}start_(){const e=(r,s)=>{if(s){r(!1,new Ii(!1,null,!0));return}const i=this.connectionFactory_();this.pendingConnection_=i;const a=c=>{const l=c.loaded,d=c.lengthComputable?c.total:-1;this.progressCallback_!==null&&this.progressCallback_(l,d)};this.progressCallback_!==null&&i.addUploadProgressListener(a),i.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{this.progressCallback_!==null&&i.removeUploadProgressListener(a),this.pendingConnection_=null;const c=i.getErrorCode()===mn.NO_ERROR,l=i.getStatus();if(!c||Fd(l,this.additionalRetryCodes_)&&this.retry){const f=i.getErrorCode()===mn.ABORT;r(!1,new Ii(!1,null,f));return}const d=this.successCodes_.indexOf(l)!==-1;r(!0,new Ii(d,i))})},t=(r,s)=>{const i=this.resolve_,a=this.reject_,c=s.connection;if(s.wasSuccessCode)try{const l=this.callback_(c,c.getResponse());NI(l)?i(l):i()}catch(l){a(l)}else if(c!==null){const l=Ca();l.serverResponse=c.getErrorText(),this.errorCallback_?a(this.errorCallback_(c,l)):a(l)}else if(s.canceled){const l=this.appDelete_?Ld():Od();a(l)}else{const l=Dd();a(l)}};this.canceled_?t(!1,new Ii(!1,null,!0)):this.backoffId_=CI(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,this.backoffId_!==null&&kI(this.backoffId_),this.pendingConnection_!==null&&this.pendingConnection_.abort()}}class Ii{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function LI(n,e){e!==null&&e.length>0&&(n.Authorization="Firebase "+e)}function MI(n,e){n["X-Firebase-Storage-Version"]="webjs/"+(e??"AppManager")}function xI(n,e){e&&(n["X-Firebase-GMPID"]=e)}function UI(n,e){e!==null&&(n["X-Firebase-AppCheck"]=e)}function FI(n,e,t,r,s,i,a=!0,c=!1){const l=Ud(n.urlParams),d=n.url+l,f=Object.assign({},n.headers);return xI(f,e),LI(f,t),MI(f,i),UI(f,r),new VI(d,n.method,f,n.body,n.successCodes,n.additionalRetryCodes,n.handler,n.errorHandler,n.timeout,n.progressCallback,s,a,c)}function BI(){return typeof BlobBuilder<"u"?BlobBuilder:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:void 0}function qI(...n){const e=BI();if(e!==void 0){const t=new e;for(let r=0;r<n.length;r++)t.append(n[r]);return t.getBlob()}else{if(Na())return new Blob(n);throw new ie(te.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}}function jI(n,e,t){return n.webkitSlice?n.webkitSlice(e,t):n.mozSlice?n.mozSlice(e,t):n.slice?n.slice(e,t):null}function $I(n){if(typeof atob>"u")throw bI("base-64");return atob(n)}const pt={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class Da{constructor(e,t){this.data=e,this.contentType=t||null}}function zI(n,e){switch(n){case pt.RAW:return new Da(Bd(e));case pt.BASE64:case pt.BASE64URL:return new Da(qd(n,e));case pt.DATA_URL:return new Da(WI(e),GI(e))}throw Ca()}function Bd(n){const e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r<=127)e.push(r);else if(r<=2047)e.push(192|r>>6,128|r&63);else if((r&64512)===55296)if(!(t<n.length-1&&(n.charCodeAt(t+1)&64512)===56320))e.push(239,191,189);else{const i=r,a=n.charCodeAt(++t);r=65536|(i&1023)<<10|a&1023,e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}else(r&64512)===56320?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|r&63)}return new Uint8Array(e)}function HI(n){let e;try{e=decodeURIComponent(n)}catch{throw $r(pt.DATA_URL,"Malformed data URL.")}return Bd(e)}function qd(n,e){switch(n){case pt.BASE64:{const s=e.indexOf("-")!==-1,i=e.indexOf("_")!==-1;if(s||i)throw $r(n,"Invalid character '"+(s?"-":"_")+"' found: is it base64url encoded?");break}case pt.BASE64URL:{const s=e.indexOf("+")!==-1,i=e.indexOf("/")!==-1;if(s||i)throw $r(n,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/");break}}let t;try{t=$I(e)}catch(s){throw s.message.includes("polyfill")?s:$r(n,"Invalid character found")}const r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}class jd{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(t===null)throw $r(pt.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const r=t[1]||null;r!=null&&(this.base64=KI(r,";base64"),this.contentType=this.base64?r.substring(0,r.length-7):r),this.rest=e.substring(e.indexOf(",")+1)}}function WI(n){const e=new jd(n);return e.base64?qd(pt.BASE64,e.rest):HI(e.rest)}function GI(n){return new jd(n).contentType}function KI(n,e){return n.length>=e.length?n.substring(n.length-e.length)===e:!1}class Gt{constructor(e,t){let r=0,s="";Md(e)?(this.data_=e,r=e.size,s=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=s}size(){return this.size_}type(){return this.type_}slice(e,t){if(Md(this.data_)){const r=this.data_,s=jI(r,e,t);return s===null?null:new Gt(s)}else{const r=new Uint8Array(this.data_.buffer,e,t-e);return new Gt(r,!0)}}static getBlob(...e){if(Na()){const t=e.map(r=>r instanceof Gt?r.data_:r);return new Gt(qI.apply(null,t))}else{const t=e.map(a=>wi(a)?zI(pt.RAW,a).data:a.data_);let r=0;t.forEach(a=>{r+=a.byteLength});const s=new Uint8Array(r);let i=0;return t.forEach(a=>{for(let c=0;c<a.length;c++)s[i++]=a[c]}),new Gt(s,!0)}}uploadData(){return this.data_}}function $d(n){let e;try{e=JSON.parse(n)}catch{return null}return OI(e)?e:null}function QI(n){if(n.length===0)return null;const e=n.lastIndexOf("/");return e===-1?"":n.slice(0,e)}function YI(n,e){const t=e.split("/").filter(r=>r.length>0).join("/");return n.length===0?t:n+"/"+t}function zd(n){const e=n.lastIndexOf("/",n.length-2);return e===-1?n:n.slice(e+1)}function JI(n,e){return e}class ke{constructor(e,t,r,s){this.server=e,this.local=t||e,this.writable=!!r,this.xform=s||JI}}let vi=null;function XI(n){return!wi(n)||n.length<2?n:zd(n)}function Hd(){if(vi)return vi;const n=[];n.push(new ke("bucket")),n.push(new ke("generation")),n.push(new ke("metageneration")),n.push(new ke("name","fullPath",!0));function e(i,a){return XI(a)}const t=new ke("name");t.xform=e,n.push(t);function r(i,a){return a!==void 0?Number(a):a}const s=new ke("size");return s.xform=r,n.push(s),n.push(new ke("timeCreated")),n.push(new ke("updated")),n.push(new ke("md5Hash",null,!0)),n.push(new ke("cacheControl",null,!0)),n.push(new ke("contentDisposition",null,!0)),n.push(new ke("contentEncoding",null,!0)),n.push(new ke("contentLanguage",null,!0)),n.push(new ke("contentType",null,!0)),n.push(new ke("metadata","customMetadata",!0)),vi=n,vi}function ZI(n,e){function t(){const r=n.bucket,s=n.fullPath,i=new Be(r,s);return e._makeStorageReference(i)}Object.defineProperty(n,"ref",{get:t})}function ev(n,e,t){const r={};r.type="file";const s=t.length;for(let i=0;i<s;i++){const a=t[i];r[a.local]=a.xform(r,e[a.server])}return ZI(r,n),r}function Wd(n,e,t){const r=$d(e);return r===null?null:ev(n,r,t)}function tv(n,e,t,r){const s=$d(e);if(s===null||!wi(s.downloadTokens))return null;const i=s.downloadTokens;if(i.length===0)return null;const a=encodeURIComponent;return i.split(",").map(d=>{const f=n.bucket,m=n.fullPath,g="/b/"+a(f)+"/o/"+a(m),R=Xn(g,t,r),C=Ud({alt:"media",token:d});return R+C})[0]}function Gd(n,e){const t={},r=e.length;for(let s=0;s<r;s++){const i=e[s];i.writable&&(t[i.server]=n[i.local])}return JSON.stringify(t)}class gn{constructor(e,t,r,s){this.url=e,this.method=t,this.handler=r,this.timeout=s,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function bt(n){if(!n)throw Ca()}function Oa(n,e){function t(r,s){const i=Wd(n,s,e);return bt(i!==null),i}return t}function nv(n,e){function t(r,s){const i=Wd(n,s,e);return bt(i!==null),tv(i,s,n.host,n._protocol)}return t}function Hr(n){function e(t,r){let s;return t.getStatus()===401?t.getErrorText().includes("Firebase App Check token is invalid")?s=EI():s=yI():t.getStatus()===402?s=_I(n.bucket):t.getStatus()===403?s=TI(n.path):s=r,s.status=t.getStatus(),s.serverResponse=r.serverResponse,s}return e}function Va(n){const e=Hr(n);function t(r,s){let i=e(r,s);return r.getStatus()===404&&(i=gI(n.path)),i.serverResponse=s.serverResponse,i}return t}function rv(n,e,t){const r=e.fullServerUrl(),s=Xn(r,n.host,n._protocol),i="GET",a=n.maxOperationRetryTime,c=new gn(s,i,Oa(n,t),a);return c.errorHandler=Va(e),c}function sv(n,e,t){const r=e.fullServerUrl(),s=Xn(r,n.host,n._protocol),i="GET",a=n.maxOperationRetryTime,c=new gn(s,i,nv(n,t),a);return c.errorHandler=Va(e),c}function iv(n,e){const t=e.fullServerUrl(),r=Xn(t,n.host,n._protocol),s="DELETE",i=n.maxOperationRetryTime;function a(l,d){}const c=new gn(r,s,a,i);return c.successCodes=[200,204],c.errorHandler=Va(e),c}function ov(n,e){return n&&n.contentType||e&&e.type()||"application/octet-stream"}function Kd(n,e,t){const r=Object.assign({},t);return r.fullPath=n.path,r.size=e.size(),r.contentType||(r.contentType=ov(null,e)),r}function av(n,e,t,r,s){const i=e.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};function c(){let j="";for(let J=0;J<2;J++)j=j+Math.random().toString().slice(2);return j}const l=c();a["Content-Type"]="multipart/related; boundary="+l;const d=Kd(e,r,s),f=Gd(d,t),m="--"+l+`\r
42
+ `)}}static propInfo(n,e){return ce.createInstance(n).getPropInfo(e)}static propType(n){if(n.typeName)return Array.isArray(n.typeName)?"undefined[]":n.typeName??"undefined";const e=ce.createInstance(n.ownerClassName())[n.name];if(Array.isArray(e)){if(e.length===0)return"undefined[]";const t=e[0];return t instanceof ce?t.className+"[]":typeof t+"[]"}else return e instanceof ce?e.className:typeof e}static getSystemRegisteredReferencesWithCachedProps(){return ce.registeredClasses().reduce((n,e)=>{const t=ce.createInstance(e).getPersistentProperties().filter(r=>r.cachedProps);return t.length>0&&(n[e]=t),n},{})}},ce._factoryMap={},ce);UE([zn],yh.prototype,"_id");let pe=yh;function zn(n,e){return FE()(n,e)}function FE(n){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,n):e._persistentProperties.push({name:t,ownerClassName:()=>e.className,...n})}}function BE(n,e){return t=>{pe.registerFactory(n,t,e),t.prototype.__className=n}}const Eh=class dp{constructor(e,t,r){if(r){if(!(t instanceof pe))throw new Error(dp.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof pe?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(i=>{i?(t?t.fromObject(i):t=pe.createInstance(i),r(t)):r(void 0)}).catch(i=>s(i))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(i=>s(i))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new qE(this)}query(e={},t){if(t){const r=t instanceof pe?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}onDocumentChange(e,t){return this._stream.onDocumentChange(this.collectionName,e,r=>t($t.toPersistentDocumentChange(r)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,r=>t(r.map(s=>$t.toPersistentDocumentChange(s))))}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(i=>pe.createInstance(i)))).catch(s=>r(s))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;const t=e.operations?.map(r=>{const s=r.value[0]??r.value;return $t.isArrayOperator(r.operator)&&s instanceof pe?{property:pe.searchableArrayNameFor(r.property),operator:r.operator,value:Array.isArray(r.value)?r.value.map(i=>i.id):s.id,aggregate:r.aggregate}:{property:r.property,operator:r.operator,value:r.value instanceof pe?{id:r.value.id}:r.value,aggregate:r.aggregate}})??[];return{...e,operations:t}}};Eh.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let si=Eh;class qE{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(si.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(si.error.invalidQueryOrder);const i=e.split(".");let a={},c=i.length>1?a:r;return i.slice(1).forEach((l,d)=>{a[l]=d<i.length-2?{}:r,a=a[l]}),this.queryObject.operations?.push({property:i[0],operator:t,value:c,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){const t=e instanceof pe?e.className:e;return this.queryObject.operations?.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}getQueryObject(){return this.queryObject}getQueryModel(){return this.model}}const Th=class sr{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return sr._dataSource}static getModel(e){if(!sr._dataSource)throw new Error(this.error.shouldBeRegistered);return new si(sr._dataSource,e)}static getModelForSubCollection(e,t){if(!sr._dataSource)throw new Error(this.error.shouldBeRegistered);return new si(sr._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const i=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return i&&(i.__documentReference=void 0),i};return Array.isArray(e)?(await Promise.all(e.map(r=>t(r)))).filter(r=>r):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};Th.error={shouldBeRegistered:"You should register a data source before using the data Store."};let jE=Th;class la{constructor(e){this._resolveCollectionPaths=()=>{throw new Error("The method collectionsMatchingTemplate has not been implemented in the concrete data source")},this._disabledChangeListeners=new Set,this._collectionsToWatch={},e&&(this._beforeUpdate=e.beforeUpdateDocument,this._afterUpdate=e.afterUpdateDocument,this._afterDocumentChange=e.afterDocumentChange,this._beforeDocumentChange=e.beforeDocumentChange,this._beforeQueryOwnerCollection=e.beforeQueryOwnerCollection),this.installUpdaters()}installUpdaters(){const e=pe.getSystemRegisteredReferencesWithCachedProps();this._collectionsToWatch={},Object.entries(e).forEach(([t,r])=>{r.forEach(s=>{s.typeName&&(Array.isArray(s.typeName)?s.typeName:[s?.typeName??t]).map(i=>pe.collectionPath(pe.createInstance(i),s)).forEach(i=>{this._collectionsToWatch[i]||(this._collectionsToWatch[i]=[]),this._collectionsToWatch[i].find(a=>a.name===s.name&&a.ownerClassName()===s.ownerClassName())||this._collectionsToWatch[i].push(s)})})})}set beforeDocumentChange(e){this._beforeDocumentChange=e}set afterDocumentChange(e){this._afterDocumentChange=e}set beforeUpdateDocument(e){this._beforeUpdate=e}set afterUpdateDocument(e){this._afterUpdate=e}set beforeQueryOwnerCollection(e){this._beforeQueryOwnerCollection=e}set resolveCollectionPaths(e){this._resolveCollectionPaths=e}get collectionsToWatch(){return this._collectionsToWatch}updateProps(e,t){const r=this._collectionsToWatch[e];if(r)return this.onDocumentChange(t,r)}async onDocumentChange(e,t){const r=$t.toPersistentDocumentChange(e);this._beforeDocumentChange?.(r,t);const s={};r.before&&(r.after?.id&&this._disabledChangeListeners.has(r.after?.id)||(await Promise.all(t.map(async i=>{const a=la.ownerCollectionPath(pe.createInstance(i.ownerClassName()),i,r.params),c=await this._resolveCollectionPaths(a);await Promise.all(c.map(async l=>{const d=jE.getModel(l);let f=d.find(),m=!1;i.cachedProps?.forEach(R=>{const S=r.before[R],N=r.after[R];S!==N&&(m=!0)}),m&&(i.searchableArray?f=f.where(i.name,"contains",r.before):f=f.where(i.name,"==",r.before)),f=this._beforeQueryOwnerCollection?.(f)??f;const _=await f.get();return s[l]={totalDocumentsToUpdate:_.length,updatedDocuments:[],documentsToUpdate:_.map(R=>R.name??R.id)},Promise.all([_.map(async R=>{let S=!1;if(i.cachedProps?.forEach(N=>{const k=r.before[N],U=r.after[N];k!==U&&(S=!0)}),S){if(i.searchableArray){const N=R[i.name].findIndex(k=>k.id===r.before.id);R[i.name][N]=r.after}else R[`_${i.name}`]=r.after;this._beforeUpdate?.(R,i),this.disableChangeListener(R),await d.save(R),this.enableChangeListener(R),s[l]?.updatedDocuments.push(R.id),this._afterUpdate?.(R,i)}else return Promise.resolve()})])}))})),this._afterDocumentChange?.(s,t)))}disableChangeListener(e){this._disabledChangeListeners.add(e.id)}enableChangeListener(e){this._disabledChangeListeners.delete(e.id)}static ownerCollectionPath(e,t,r){let s;return typeof t.ownerCollection=="function"?s=t.ownerCollection(e,t,r):s=t.ownerCollection??e.className,s}}class $t{constructor(){this._cachedPropsUpdater=void 0}installCachedPropsUpdater(e){return this._cachedPropsUpdater=new la(e),this._cachedPropsUpdater.resolveCollectionPaths=this.resolveCollectionPaths.bind(this),this._cachedPropsUpdater}get cachedPropsUpdater(){return this._cachedPropsUpdater}static toPropertyPathOperations(e){return e?e.map(t=>{if($t.isArrayOperator(t.operator)&&t.value[0]instanceof pe)return{property:pe.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(i=>i.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPersistentDocumentChange(e){return{...e,before:e.before&&pe.createInstance(e.before),after:e.after&&pe.createInstance(e.after)}}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}static isStringMatchingTemplate(e,t){const r=e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&").replace(/\\\$\\\{[^}]+\\\}/g,"([^/]+)").replace(/\\\{[^}]+\\\}/g,"([^/]+)");return new RegExp("^"+r+"$").test(t)}static extractTemplateParams(e,t){const r=[],s=t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&").replace(/\\\{([^}]+)\\\}/g,(l,d)=>(r.push(d),"([^/]+)")),i=new RegExp("^"+s+"$"),a=e.match(i),c={};return a&&r.forEach((l,d)=>{c[l]=a[d+1]}),c}}const wh=class ir{static registerCloudStorage(e,t){ir._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=ir._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){ir._defaultCloudStorage=e}static get defaultCloudStorage(){if(!ir._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return ir._defaultCloudStorage}};wh._cloudStorageFactoryMap={};let Hn=wh;function Ih(n,e){return Hn.registerCloudStorage(n,e),t=>{t.prototype.__className=n}}var $E=(n,e,t,r)=>{for(var s=e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(s)||s);return s};let ha=class extends Hn{constructor(n=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=n}simulateDelay(n){return this._simulateDelay=n,this}resolveWithDelay(n){if(this._simulateDelay<=0)return Promise.resolve(n);const e=new Promise(t=>{setTimeout(()=>t(n),this._simulateDelay)});return this._pendingPromises.push(e),e.finally(()=>this._pendingPromises=this._pendingPromises.filter(t=>t===e)),e}save(n,e){const t=n;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[n]=JSON.stringify(e),this._onProgress&&this._onProgress(100,100);const r=e instanceof File?e.name:t;return this.resolveWithDelay(r)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:n=>this._onProgress=n}}getUrl(n){return Promise.resolve(this._pathToMockFiles+n)}delete(n){return delete this.mockFileSystem[n],this.resolveWithDelay()}};ha=$E([Ih("MockCloudStorage",()=>new ha)],ha);var zE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Wn=(n,e,t,r)=>{for(var s=r>1?void 0:r?HE(e,t):e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&zE(e,t,s),s};let pn=class extends pe{constructor(){super(...arguments),this._onChange=new gh}async save({data:n,fileName:e,progress:t,cloudStorageProvider:r}={}){const s=n||this._pendingData;s&&(this._reference&&await this.delete(),this.provider=r||Hn.defaultCloudStorage,this._originalFileName=e||(s instanceof File?s.name:void 0),this._reference=await this.provider.save(this.id,s,t),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(n){this._provider=n,this._cloudStorageProviderName=n.className}get provider(){if(!this._provider)try{this._provider=Hn.createInstance(this._cloudStorageProviderName)}catch{this._provider=Hn.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(n){return this._pendingData=n,this._originalFileName=n instanceof File?n.name:void 0,this._mimeType=n instanceof Blob?n.type:void 0,this._onChange.notify({event:1,pendingData:n,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(n){return this._onChange.subscribe(n)}};Wn([zn],pn.prototype,"_reference",2),Wn([zn],pn.prototype,"_url",2),Wn([zn],pn.prototype,"_cloudStorageProviderName",2),Wn([zn],pn.prototype,"_originalFileName",2),Wn([zn],pn.prototype,"_mimeType",2),pn=Wn([BE("StoredFile")],pn);class vh{}const Ah=class xe extends vh{constructor(){if(super(),this._onAuthStateChange=new gh,!xe._authService)throw new Error(xe.error.shouldBeRegistered);xe._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){xe._authService!=e&&(xe._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return xe._authService.signUp(e)}login(e){return xe._authService.login(e)}logout(){return xe._authService.logout()}resetEmailPassword(e){return xe._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return xe._authService.resendVerificationEmail(e,t,r)}refreshToken(){return xe._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return xe._authService.linkAdditionalProvider(e)}unlinkProvider(e){return xe._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};Ah.error={shouldBeRegistered:"You should register an auth service before using Auth."},Ah._instance=void 0;function ii(n){return n?n.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}var WE="firebase",GE="12.10.0";je(WE,GE,"app");function Rh(){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."}}const KE=Rh,bh=new cr("auth","Firebase",Rh());const oi=new zi("@firebase/auth");function QE(n,...e){oi.logLevel<=H.WARN&&oi.warn(`Auth (${nn}): ${n}`,...e)}function ai(n,...e){oi.logLevel<=H.ERROR&&oi.error(`Auth (${nn}): ${n}`,...e)}function He(n,...e){throw fa(n,...e)}function Ye(n,...e){return fa(n,...e)}function da(n,e,t){const r={...KE(),[e]:t};return new cr("auth","Firebase",r).create(e,{appName:n.name})}function ut(n){return da(n,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Ph(n,e,t){const r=t;if(!(e instanceof r))throw r.name!==e.constructor.name&&He(n,"argument-error"),da(n,"argument-error",`Type of ${e.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function fa(n,...e){if(typeof n!="string"){const t=e[0],r=[...e.slice(1)];return r[0]&&(r[0].appName=n.name),n._errorFactory.create(t,...r)}return bh.create(n,...e)}function M(n,e,...t){if(!n)throw fa(e,...t)}function wt(n){const e="INTERNAL ASSERTION FAILED: "+n;throw ai(e),new Error(e)}function It(n,e){n||wt(e)}function pa(){return typeof self<"u"&&self.location?.href||""}function YE(){return Ch()==="http:"||Ch()==="https:"}function Ch(){return typeof self<"u"&&self.location?.protocol||null}function JE(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(YE()||bp()||"connection"in navigator)?navigator.onLine:!0}function XE(){if(typeof navigator>"u")return null;const n=navigator;return n.languages&&n.languages[0]||n.language||null}class Mr{constructor(e,t){this.shortDelay=e,this.longDelay=t,It(t>e,"Short delay should be less than long delay!"),this.isMobile=vp()||Pp()}get(){return JE()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function ma(n,e){It(n.emulator,"Emulator should always be set here");const{url:t}=n.emulator;return e?`${t}${e.startsWith("/")?e.slice(1):e}`:t}class Sh{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;wt("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;wt("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;wt("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const ZE={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};const eT=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],tT=new Mr(3e4,6e4);function vt(n,e){return n.tenantId&&!e.tenantId?{...e,tenantId:n.tenantId}:e}async function Je(n,e,t,r,s={}){return kh(n,s,async()=>{let i={},a={};r&&(e==="GET"?a=r:i={body:JSON.stringify(r)});const c=ur({key:n.config.apiKey,...a}).slice(1),l=await n._getAdditionalHeaders();l["Content-Type"]="application/json",n.languageCode&&(l["X-Firebase-Locale"]=n.languageCode);const d={method:e,headers:l,...i};return Rp()||(d.referrerPolicy="no-referrer"),n.emulatorConfig&&tt(n.emulatorConfig.host)&&(d.credentials="include"),Sh.fetch()(await Nh(n,n.config.apiHost,t,c),d)})}async function kh(n,e,t){n._canInitEmulator=!1;const r={...ZE,...e};try{const s=new rT(n),i=await Promise.race([t(),s.promise]);s.clearNetworkTimeout();const a=await i.json();if("needConfirmation"in a)throw ci(n,"account-exists-with-different-credential",a);if(i.ok&&!("errorMessage"in a))return a;{const c=i.ok?a.errorMessage:a.error.message,[l,d]=c.split(" : ");if(l==="FEDERATED_USER_ID_ALREADY_LINKED")throw ci(n,"credential-already-in-use",a);if(l==="EMAIL_EXISTS")throw ci(n,"email-already-in-use",a);if(l==="USER_DISABLED")throw ci(n,"user-disabled",a);const f=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(d)throw da(n,f,d);He(n,f)}}catch(s){if(s instanceof We)throw s;He(n,"network-request-failed",{message:String(s)})}}async function xr(n,e,t,r,s={}){const i=await Je(n,e,t,r,s);return"mfaPendingCredential"in i&&He(n,"multi-factor-auth-required",{_serverResponse:i}),i}async function Nh(n,e,t,r){const s=`${e}${t}?${r}`,i=n,a=i.config.emulator?ma(n.config,s):`${n.config.apiScheme}://${s}`;return eT.includes(t)&&(await i._persistenceManagerAvailable,i._getPersistenceType()==="COOKIE")?i._getPersistence()._getFinalTarget(a).toString():a}function nT(n){switch(n){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class rT{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((t,r)=>{this.timer=setTimeout(()=>r(Ye(this.auth,"network-request-failed")),tT.get())})}}function ci(n,e,t){const r={appName:n.name};t.email&&(r.email=t.email),t.phoneNumber&&(r.phoneNumber=t.phoneNumber);const s=Ye(n,e,r);return s.customData._tokenResponse=t,s}function Dh(n){return n!==void 0&&n.enterprise!==void 0}class sT{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],e.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return nT(t.enforcementState);return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function iT(n,e){return Je(n,"GET","/v2/recaptchaConfig",vt(n,e))}async function oT(n,e){return Je(n,"POST","/v1/accounts:delete",e)}async function aT(n,e){return Je(n,"POST","/v1/accounts:update",e)}async function ui(n,e){return Je(n,"POST","/v1/accounts:lookup",e)}function Ur(n){if(n)try{const e=new Date(Number(n));if(!isNaN(e.getTime()))return e.toUTCString()}catch{}}async function cT(n,e=!1){const t=Y(n),r=await t.getIdToken(e),s=_a(r);M(s&&s.exp&&s.auth_time&&s.iat,t.auth,"internal-error");const i=typeof s.firebase=="object"?s.firebase:void 0,a=i?.sign_in_provider;return{claims:s,token:r,authTime:Ur(ga(s.auth_time)),issuedAtTime:Ur(ga(s.iat)),expirationTime:Ur(ga(s.exp)),signInProvider:a||null,signInSecondFactor:i?.sign_in_second_factor||null}}function ga(n){return Number(n)*1e3}function _a(n){const[e,t,r]=n.split(".");if(e===void 0||t===void 0||r===void 0)return ai("JWT malformed, contained fewer than 3 sections"),null;try{const s=pc(t);return s?JSON.parse(s):(ai("Failed to decode base64 JWT payload"),null)}catch(s){return ai("Caught error parsing JWT payload as JSON",s?.toString()),null}}function Oh(n){const e=_a(n);return M(e,"internal-error"),M(typeof e.exp<"u","internal-error"),M(typeof e.iat<"u","internal-error"),Number(e.exp)-Number(e.iat)}async function Gn(n,e,t=!1){if(t)return e;try{return await e}catch(r){throw r instanceof We&&uT(r)&&n.auth.currentUser===n&&await n.auth.signOut(),r}}function uT({code:n}){return n==="auth/user-disabled"||n==="auth/user-token-expired"}class lT{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,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(e){if(e){const t=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),t}else{this.errorBackoff=3e4;const r=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,r)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class ya{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ur(this.lastLoginAt),this.creationTime=Ur(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Fr(n){const e=n.auth,t=await n.getIdToken(),r=await Gn(n,ui(e,{idToken:t}));M(r?.users.length,e,"internal-error");const s=r.users[0];n._notifyReloadListener(s);const i=s.providerUserInfo?.length?Vh(s.providerUserInfo):[],a=dT(n.providerData,i),c=n.isAnonymous,l=!(n.email&&s.passwordHash)&&!a?.length,d=c?l:!1,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new ya(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(n,f)}async function hT(n){const e=Y(n);await Fr(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}function dT(n,e){return[...n.filter(r=>!e.some(s=>s.providerId===r.providerId)),...e]}function Vh(n){return n.map(({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}async function fT(n,e){const t=await kh(n,{},async()=>{const r=ur({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:i}=n.config,a=await Nh(n,s,"/v1/token",`key=${i}`),c=await n._getAdditionalHeaders();c["Content-Type"]="application/x-www-form-urlencoded";const l={method:"POST",headers:c,body:r};return n.emulatorConfig&&tt(n.emulatorConfig.host)&&(l.credentials="include"),Sh.fetch()(a,l)});return{accessToken:t.access_token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}async function pT(n,e){return Je(n,"POST","/v2/accounts:revokeToken",vt(n,e))}class Kn{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){M(e.idToken,"internal-error"),M(typeof e.idToken<"u","internal-error"),M(typeof e.refreshToken<"u","internal-error");const t="expiresIn"in e&&typeof e.expiresIn<"u"?Number(e.expiresIn):Oh(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){M(e.length!==0,"internal-error");const t=Oh(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return!t&&this.accessToken&&!this.isExpired?this.accessToken:(M(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:s,expiresIn:i}=await fT(e,t);this.updateTokensAndExpiration(r,s,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+r*1e3}static fromJSON(e,t){const{refreshToken:r,accessToken:s,expirationTime:i}=t,a=new Kn;return r&&(M(typeof r=="string","internal-error",{appName:e}),a.refreshToken=r),s&&(M(typeof s=="string","internal-error",{appName:e}),a.accessToken=s),i&&(M(typeof i=="number","internal-error",{appName:e}),a.expirationTime=i),a}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 Kn,this.toJSON())}_performRefresh(){return wt("not implemented")}}function zt(n,e){M(typeof n=="string"||typeof n>"u","internal-error",{appName:e})}class Xe{constructor({uid:e,auth:t,stsTokenManager:r,...s}){this.providerId="firebase",this.proactiveRefresh=new lT(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new ya(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Gn(this,this.stsTokenManager.getToken(this.auth,e));return M(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return cT(this,e)}reload(){return hT(this)}_assign(e){this!==e&&(M(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(t=>({...t})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new Xe({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){M(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await Fr(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Ae(this.auth.app))return Promise.reject(ut(this.auth));const e=await this.getIdToken();return await Gn(this,oT(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){const r=t.displayName??void 0,s=t.email??void 0,i=t.phoneNumber??void 0,a=t.photoURL??void 0,c=t.tenantId??void 0,l=t._redirectEventId??void 0,d=t.createdAt??void 0,f=t.lastLoginAt??void 0,{uid:m,emailVerified:_,isAnonymous:R,providerData:S,stsTokenManager:N}=t;M(m&&N,e,"internal-error");const k=Kn.fromJSON(this.name,N);M(typeof m=="string",e,"internal-error"),zt(r,e.name),zt(s,e.name),M(typeof _=="boolean",e,"internal-error"),M(typeof R=="boolean",e,"internal-error"),zt(i,e.name),zt(a,e.name),zt(c,e.name),zt(l,e.name),zt(d,e.name),zt(f,e.name);const U=new Xe({uid:m,auth:e,email:s,emailVerified:_,displayName:r,isAnonymous:R,photoURL:a,phoneNumber:i,tenantId:c,stsTokenManager:k,createdAt:d,lastLoginAt:f});return S&&Array.isArray(S)&&(U.providerData=S.map($=>({...$}))),l&&(U._redirectEventId=l),U}static async _fromIdTokenResponse(e,t,r=!1){const s=new Kn;s.updateFromServerResponse(t);const i=new Xe({uid:t.localId,auth:e,stsTokenManager:s,isAnonymous:r});return await Fr(i),i}static async _fromGetAccountInfoResponse(e,t,r){const s=t.users[0];M(s.localId!==void 0,"internal-error");const i=s.providerUserInfo!==void 0?Vh(s.providerUserInfo):[],a=!(s.email&&s.passwordHash)&&!i?.length,c=new Kn;c.updateFromIdToken(r);const l=new Xe({uid:s.localId,auth:e,stsTokenManager:c,isAnonymous:a}),d={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:i,metadata:new ya(s.createdAt,s.lastLoginAt),isAnonymous:!(s.email&&s.passwordHash)&&!i?.length};return Object.assign(l,d),l}}const Lh=new Map;function At(n){It(n instanceof Function,"Expected a class definition");let e=Lh.get(n);return e?(It(e instanceof n,"Instance stored in cache mismatched with class"),e):(e=new n,Lh.set(n,e),e)}class Mh{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===void 0?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Mh.type="NONE";const xh=Mh;function li(n,e,t){return`firebase:${n}:${e}:${t}`}class Qn{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:s,name:i}=this.auth;this.fullUserKey=li(this.userKey,s.apiKey,i),this.fullPersistenceKey=li("persistence",s.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(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(typeof e=="string"){const t=await ui(this.auth,{idToken:e}).catch(()=>{});return t?Xe._fromGetAccountInfoResponse(this.auth,t,e):null}return Xe._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new Qn(At(xh),e,r);const s=(await Promise.all(t.map(async d=>{if(await d._isAvailable())return d}))).filter(d=>d);let i=s[0]||At(xh);const a=li(r,e.config.apiKey,e.name);let c=null;for(const d of t)try{const f=await d._get(a);if(f){let m;if(typeof f=="string"){const _=await ui(e,{idToken:f}).catch(()=>{});if(!_)break;m=await Xe._fromGetAccountInfoResponse(e,_,f)}else m=Xe._fromJSON(e,f);d!==i&&(c=m),i=d;break}}catch{}const l=s.filter(d=>d._shouldAllowMigration);return!i._shouldAllowMigration||!l.length?new Qn(i,e,r):(i=l[0],c&&await i._set(a,c.toJSON()),await Promise.all(t.map(async d=>{if(d!==i)try{await d._remove(a)}catch{}})),new Qn(i,e,r))}}function Uh(n){const e=n.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(jh(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(Fh(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(zh(e))return"Blackberry";if(Hh(e))return"Webos";if(Bh(e))return"Safari";if((e.includes("chrome/")||qh(e))&&!e.includes("edge/"))return"Chrome";if($h(e))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=n.match(t);if(r?.length===2)return r[1]}return"Other"}function Fh(n=ve()){return/firefox\//i.test(n)}function Bh(n=ve()){const e=n.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function qh(n=ve()){return/crios\//i.test(n)}function jh(n=ve()){return/iemobile/i.test(n)}function $h(n=ve()){return/android/i.test(n)}function zh(n=ve()){return/blackberry/i.test(n)}function Hh(n=ve()){return/webos/i.test(n)}function Ea(n=ve()){return/iphone|ipad|ipod/i.test(n)||/macintosh/i.test(n)&&/mobile/i.test(n)}function mT(n=ve()){return Ea(n)&&!!window.navigator?.standalone}function gT(){return Cp()&&document.documentMode===10}function Wh(n=ve()){return Ea(n)||$h(n)||Hh(n)||zh(n)||/windows phone/i.test(n)||jh(n)}function Gh(n,e=[]){let t;switch(n){case"Browser":t=Uh(ve());break;case"Worker":t=`${Uh(ve())}-${n}`;break;default:t=n}const r=e.length?e.join(","):"FirebaseCore-web";return`${t}/JsCore/${nn}/${r}`}class _T{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const r=i=>new Promise((a,c)=>{try{const l=e(i);a(l)}catch(l){c(l)}});r.onAbort=t,this.queue.push(r);const s=this.queue.length-1;return()=>{this.queue[s]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(r){t.reverse();for(const s of t)try{s()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:r?.message})}}}async function yT(n,e={}){return Je(n,"GET","/v2/passwordPolicy",vt(n,e))}const ET=6;class TT{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??ET,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),t.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),t.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),t.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),t.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,s=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),s&&(t.meetsMaxPasswordLength=e.length<=s)}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);let r;for(let s=0;s<e.length;s++)r=e.charAt(s),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,s,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=s)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class wT{constructor(e,t,r,s){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=s,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Kh(this),this.idTokenSubscription=new Kh(this),this.beforeStateQueue=new _T(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=bh,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=s.sdkClientVersion,this._persistenceManagerAvailable=new Promise(i=>this._resolvePersistenceManagerAvailable=i)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=At(t)),this._initializationPromise=this.queue(async()=>{if(!this._deleted&&(this.persistenceManager=await Qn.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted)){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!e)){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{const t=await ui(this,{idToken:e}),r=await Xe._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(t){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",t),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(Ae(this.app)){const i=this.app.settings.authIdToken;return i?new Promise(a=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(i).then(a,a))}):this.directlySetCurrentUser(null)}const t=await this.assertedPersistence.getCurrentUser();let r=t,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const i=this.redirectUser?._redirectEventId,a=r?._redirectEventId,c=await this.tryRedirectSignIn(e);(!i||i===a)&&c?.user&&(r=c.user,s=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(r)}catch(i){r=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(i))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return M(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch{await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Fr(e)}catch(t){if(t?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=XE()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Ae(this.app))return Promise.reject(ut(this));const t=e?Y(e):null;return t&&M(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&M(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return Ae(this.app)?Promise.reject(ut(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Ae(this.app)?Promise.reject(ut(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(At(e))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await yT(this),t=new TT(e);this.tenantId===null?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new cr("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged(()=>{r(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken(),r={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};this.tenantId!=null&&(r.tenantId=this.tenantId),await pT(this,r)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return e===null?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&At(e)||this._popupRedirectResolver;M(t,this,"argument-error"),this.redirectPersistenceManager=await Qn.create(this,[At(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,s){if(this._deleted)return()=>{};const i=typeof t=="function"?t:t.next.bind(t);let a=!1;const c=this._isInitialized?Promise.resolve():this._initializationPromise;if(M(c,this,"internal-error"),c.then(()=>{a||i(this.currentUser)}),typeof t=="function"){const l=e.addObserver(t,r,s);return()=>{a=!0,l()}}else{const l=e.addObserver(t);return()=>{a=!0,l()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return M(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Gh(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);const t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e["X-Firebase-Client"]=t);const r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if(Ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&QE(`Error while retrieving App Check token: ${e.error}`),e?.token}}function lt(n){return Y(n)}class Kh{constructor(e){this.auth=e,this.observer=null,this.addObserver=Mp(t=>this.observer=t)}get next(){return M(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let hi={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function IT(n){hi=n}function Qh(n){return hi.loadJS(n)}function vT(){return hi.recaptchaEnterpriseScript}function AT(){return hi.gapiScript}function RT(n){return`__${n}${Math.floor(Math.random()*1e6)}`}class bT{constructor(){this.enterprise=new PT}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class PT{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}const CT="recaptcha-enterprise",Yh="NO_RECAPTCHA";class ST{constructor(e){this.type=CT,this.auth=lt(e)}async verify(e="verify",t=!1){async function r(i){if(!t){if(i.tenantId==null&&i._agentRecaptchaConfig!=null)return i._agentRecaptchaConfig.siteKey;if(i.tenantId!=null&&i._tenantRecaptchaConfigs[i.tenantId]!==void 0)return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(a,c)=>{iT(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(l=>{if(l.recaptchaKey===void 0)c(new Error("recaptcha Enterprise site key undefined"));else{const d=new sT(l);return i.tenantId==null?i._agentRecaptchaConfig=d:i._tenantRecaptchaConfigs[i.tenantId]=d,a(d.siteKey)}}).catch(l=>{c(l)})})}function s(i,a,c){const l=window.grecaptcha;Dh(l)?l.enterprise.ready(()=>{l.enterprise.execute(i,{action:e}).then(d=>{a(d)}).catch(()=>{a(Yh)})}):c(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new bT().execute("siteKey",{action:"verify"}):new Promise((i,a)=>{r(this.auth).then(c=>{if(!t&&Dh(window.grecaptcha))s(c,i,a);else{if(typeof window>"u"){a(new Error("RecaptchaVerifier is only supported in browser"));return}let l=vT();l.length!==0&&(l+=c),Qh(l).then(()=>{s(c,i,a)}).catch(d=>{a(d)})}}).catch(c=>{a(c)})})}}async function Jh(n,e,t,r=!1,s=!1){const i=new ST(n);let a;if(s)a=Yh;else try{a=await i.verify(t)}catch{a=await i.verify(t,!0)}const c={...e};if(t==="mfaSmsEnrollment"||t==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in c){const l=c.phoneEnrollmentInfo.phoneNumber,d=c.phoneEnrollmentInfo.recaptchaToken;Object.assign(c,{phoneEnrollmentInfo:{phoneNumber:l,recaptchaToken:d,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in c){const l=c.phoneSignInInfo.recaptchaToken;Object.assign(c,{phoneSignInInfo:{recaptchaToken:l,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return c}return r?Object.assign(c,{captchaResp:a}):Object.assign(c,{captchaResponse:a}),Object.assign(c,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(c,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),c}async function di(n,e,t,r,s){if(n._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await Jh(n,e,t,t==="getOobCode");return r(n,i)}else return r(n,e).catch(async i=>{if(i.code==="auth/missing-recaptcha-token"){console.log(`${t} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const a=await Jh(n,e,t,t==="getOobCode");return r(n,a)}else return Promise.reject(i)})}function kT(n,e){const t=dr(n,"auth");if(t.isInitialized()){const s=t.getImmediate(),i=t.getOptions();if(en(i,e??{}))return s;He(s,"already-initialized")}return t.initialize({options:e})}function NT(n,e){const t=e?.persistence||[],r=(Array.isArray(t)?t:[t]).map(At);e?.errorMap&&n._updateErrorMap(e.errorMap),n._initializeWithPersistence(r,e?.popupRedirectResolver)}function Xh(n,e,t){const r=lt(n);M(/^https?:\/\//.test(e),r,"invalid-emulator-scheme");const s=!1,i=Zh(e),{host:a,port:c}=DT(e),l=c===null?"":`:${c}`,d={url:`${i}//${a}${l}/`},f=Object.freeze({host:a,port:c,protocol:i.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!r._canInitEmulator){M(r.config.emulator&&r.emulatorConfig,r,"emulator-config-failed"),M(en(d,r.config.emulator)&&en(f,r.emulatorConfig),r,"emulator-config-failed");return}r.config.emulator=d,r.emulatorConfig=f,r.settings.appVerificationDisabledForTesting=!0,tt(a)?(ls(`${i}//${a}${l}`),hs("Auth",!0)):OT()}function Zh(n){const e=n.indexOf(":");return e<0?"":n.substr(0,e+1)}function DT(n){const e=Zh(n),t=/(\/\/)?([^?#/]+)/.exec(n.substr(e.length));if(!t)return{host:"",port:null};const r=t[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(r);if(s){const i=s[1];return{host:i,port:ed(r.substr(i.length+1))}}else{const[i,a]=r.split(":");return{host:i,port:ed(a)}}}function ed(n){if(!n)return null;const e=Number(n);return isNaN(e)?null:e}function OT(){function n(){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)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",n):n())}class Ta{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return wt("not implemented")}_getIdTokenResponse(e){return wt("not implemented")}_linkToIdToken(e,t){return wt("not implemented")}_getReauthenticationResolver(e){return wt("not implemented")}}async function VT(n,e){return Je(n,"POST","/v1/accounts:signUp",e)}async function LT(n,e){return xr(n,"POST","/v1/accounts:signInWithPassword",vt(n,e))}async function td(n,e){return Je(n,"POST","/v1/accounts:sendOobCode",vt(n,e))}async function MT(n,e){return td(n,e)}async function xT(n,e){return td(n,e)}async function UT(n,e){return xr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}async function FT(n,e){return xr(n,"POST","/v1/accounts:signInWithEmailLink",vt(n,e))}class Br extends Ta{constructor(e,t,r,s=null){super("password",r),this._email=e,this._password=t,this._tenantId=s}static _fromEmailAndPassword(e,t){return new Br(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new Br(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t=typeof e=="string"?JSON.parse(e):e;if(t?.email&&t?.password){if(t.signInMethod==="password")return this._fromEmailAndPassword(t.email,t.password);if(t.signInMethod==="emailLink")return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":const t={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return di(e,t,"signInWithPassword",LT);case"emailLink":return UT(e,{email:this._email,oobCode:this._password});default:He(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":const r={idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return di(e,r,"signUpPassword",VT);case"emailLink":return FT(e,{idToken:t,email:this._email,oobCode:this._password});default:He(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Yn(n,e){return xr(n,"POST","/v1/accounts:signInWithIdp",vt(n,e))}const BT="http://localhost";class mn extends Ta{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new mn(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):He("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){const t=typeof e=="string"?JSON.parse(e):e,{providerId:r,signInMethod:s,...i}=t;if(!r||!s)return null;const a=new mn(r,s);return a.idToken=i.idToken||void 0,a.accessToken=i.accessToken||void 0,a.secret=i.secret,a.nonce=i.nonce,a.pendingToken=i.pendingToken||null,a}_getIdTokenResponse(e){const t=this.buildRequest();return Yn(e,t)}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,Yn(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Yn(e,t)}buildRequest(){const e={requestUri:BT,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=ur(t)}return e}}function qT(n){switch(n){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}}function jT(n){const e=lr(hr(n)).link,t=e?lr(hr(e)).deep_link_id:null,r=lr(hr(n)).deep_link_id;return(r?lr(hr(r)).link:null)||r||t||e||n}class wa{constructor(e){const t=lr(hr(e)),r=t.apiKey??null,s=t.oobCode??null,i=qT(t.mode??null);M(r&&s&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=s,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){const t=jT(e);try{return new wa(t)}catch{return null}}}class Jn{constructor(){this.providerId=Jn.PROVIDER_ID}static credential(e,t){return Br._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=wa.parseLink(t);return M(r,"argument-error"),Br._fromEmailAndCode(e,r.code,r.tenantId)}}Jn.PROVIDER_ID="password",Jn.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Jn.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class fi{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 qr extends fi{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ht extends qr{constructor(){super("facebook.com")}static credential(e){return mn._fromParams({providerId:ht.PROVIDER_ID,signInMethod:ht.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return ht.credentialFromTaggedObject(e)}static credentialFromError(e){return ht.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return ht.credential(e.oauthAccessToken)}catch{return null}}}ht.FACEBOOK_SIGN_IN_METHOD="facebook.com",ht.PROVIDER_ID="facebook.com";class dt extends qr{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return mn._fromParams({providerId:dt.PROVIDER_ID,signInMethod:dt.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return dt.credentialFromTaggedObject(e)}static credentialFromError(e){return dt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return dt.credential(t,r)}catch{return null}}}dt.GOOGLE_SIGN_IN_METHOD="google.com",dt.PROVIDER_ID="google.com";class Ht extends qr{constructor(){super("github.com")}static credential(e){return mn._fromParams({providerId:Ht.PROVIDER_ID,signInMethod:Ht.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Ht.credentialFromTaggedObject(e)}static credentialFromError(e){return Ht.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return Ht.credential(e.oauthAccessToken)}catch{return null}}}Ht.GITHUB_SIGN_IN_METHOD="github.com",Ht.PROVIDER_ID="github.com";class Ze extends qr{constructor(){super("twitter.com")}static credential(e,t){return mn._fromParams({providerId:Ze.PROVIDER_ID,signInMethod:Ze.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Ze.credentialFromTaggedObject(e)}static credentialFromError(e){return Ze.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return Ze.credential(t,r)}catch{return null}}}Ze.TWITTER_SIGN_IN_METHOD="twitter.com",Ze.PROVIDER_ID="twitter.com";async function nd(n,e){return xr(n,"POST","/v1/accounts:signUp",vt(n,e))}class Rt{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,s=!1){const i=await Xe._fromIdTokenResponse(e,r,s),a=rd(r);return new Rt({user:i,providerId:a,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const s=rd(r);return new Rt({user:e,providerId:s,_tokenResponse:r,operationType:t})}}function rd(n){return n.providerId?n.providerId:"phoneNumber"in n?"phone":null}async function $T(n){if(Ae(n.app))return Promise.reject(ut(n));const e=lt(n);if(await e._initializationPromise,e.currentUser?.isAnonymous)return new Rt({user:e.currentUser,providerId:null,operationType:"signIn"});const t=await nd(e,{returnSecureToken:!0}),r=await Rt._fromIdTokenResponse(e,"signIn",t,!0);return await e._updateCurrentUser(r.user),r}class pi extends We{constructor(e,t,r,s){super(t.code,t.message),this.operationType=r,this.user=s,Object.setPrototypeOf(this,pi.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,s){return new pi(e,t,r,s)}}function sd(n,e,t,r){return(e==="reauthenticate"?t._getReauthenticationResolver(n):t._getIdTokenResponse(n)).catch(i=>{throw i.code==="auth/multi-factor-auth-required"?pi._fromErrorAndOperation(n,i,e,r):i})}function id(n){return new Set(n.map(({providerId:e})=>e).filter(e=>!!e))}async function zT(n,e){const t=Y(n);await WT(!0,t,e);const{providerUserInfo:r}=await aT(t.auth,{idToken:await t.getIdToken(),deleteProvider:[e]}),s=id(r||[]);return t.providerData=t.providerData.filter(i=>s.has(i.providerId)),s.has("phone")||(t.phoneNumber=null),await t.auth._persistUserIfCurrent(t),t}async function HT(n,e,t=!1){const r=await Gn(n,e._linkToIdToken(n.auth,await n.getIdToken()),t);return Rt._forOperation(n,"link",r)}async function WT(n,e,t){await Fr(e);const r=id(e.providerData);M(r.has(t)===n,e.auth,"no-such-provider")}async function GT(n,e,t=!1){const{auth:r}=n;if(Ae(r.app))return Promise.reject(ut(r));const s="reauthenticate";try{const i=await Gn(n,sd(r,s,e,n),t);M(i.idToken,r,"internal-error");const a=_a(i.idToken);M(a,r,"internal-error");const{sub:c}=a;return M(n.uid===c,r,"user-mismatch"),Rt._forOperation(n,s,i)}catch(i){throw i?.code==="auth/user-not-found"&&He(r,"user-mismatch"),i}}async function od(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r="signIn",s=await sd(n,r,e),i=await Rt._fromIdTokenResponse(n,r,s);return t||await n._updateCurrentUser(i.user),i}async function KT(n,e){return od(lt(n),e)}function QT(n,e,t){M(t.url?.length>0,n,"invalid-continue-uri"),M(typeof t.dynamicLinkDomain>"u"||t.dynamicLinkDomain.length>0,n,"invalid-dynamic-link-domain"),M(typeof t.linkDomain>"u"||t.linkDomain.length>0,n,"invalid-hosting-link-domain"),e.continueUrl=t.url,e.dynamicLinkDomain=t.dynamicLinkDomain,e.linkDomain=t.linkDomain,e.canHandleCodeInApp=t.handleCodeInApp,t.iOS&&(M(t.iOS.bundleId.length>0,n,"missing-ios-bundle-id"),e.iOSBundleId=t.iOS.bundleId),t.android&&(M(t.android.packageName.length>0,n,"missing-android-pkg-name"),e.androidInstallApp=t.android.installApp,e.androidMinimumVersionCode=t.android.minimumVersion,e.androidPackageName=t.android.packageName)}async function ad(n){const e=lt(n);e._getPasswordPolicyInternal()&&await e._updatePasswordPolicy()}async function YT(n,e,t){const r=lt(n);await di(r,{requestType:"PASSWORD_RESET",email:e,clientType:"CLIENT_TYPE_WEB"},"getOobCode",xT)}async function JT(n,e,t){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),a=await di(r,{returnSecureToken:!0,email:e,password:t,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",nd).catch(l=>{throw l.code==="auth/password-does-not-meet-requirements"&&ad(n),l}),c=await Rt._fromIdTokenResponse(r,"signIn",a);return await r._updateCurrentUser(c.user),c}function cd(n,e,t){return Ae(n.app)?Promise.reject(ut(n)):KT(Y(n),Jn.credential(e,t)).catch(async r=>{throw r.code==="auth/password-does-not-meet-requirements"&&ad(n),r})}async function ud(n,e){const t=Y(n),s={requestType:"VERIFY_EMAIL",idToken:await n.getIdToken()};e&&QT(t.auth,s,e);const{email:i}=await MT(t.auth,s);i!==n.email&&await n.reload()}async function XT(n,e){return Je(n,"POST","/v1/accounts:update",e)}async function ZT(n,{displayName:e,photoURL:t}){if(e===void 0&&t===void 0)return;const r=Y(n),i={idToken:await r.getIdToken(),displayName:e,photoUrl:t,returnSecureToken:!0},a=await Gn(r,XT(r.auth,i));r.displayName=a.displayName||null,r.photoURL=a.photoUrl||null;const c=r.providerData.find(({providerId:l})=>l==="password");c&&(c.displayName=r.displayName,c.photoURL=r.photoURL),await r._updateTokensIfNecessary(a)}function ew(n,e,t,r){return Y(n).onIdTokenChanged(e,t,r)}function tw(n,e,t){return Y(n).beforeAuthStateChanged(e,t)}const mi="__sak";class ld{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(mi,"1"),this.storage.removeItem(mi),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const 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()}}const nw=1e3,rw=10;class hd extends ld{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=Wh(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),s=this.localCache[t];r!==s&&e(t,s,r)}}onStorageEvent(e,t=!1){if(!e.key){this.forAllChangedKeys((a,c,l)=>{this.notifyListeners(a,l)});return}const r=e.key;t?this.detachListener():this.stopPolling();const s=()=>{const a=this.storage.getItem(r);!t&&this.localCache[r]===a||this.notifyListeners(r,a)},i=this.storage.getItem(r);gT()&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(s,rw):s()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)})},nw)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){Object.keys(this.listeners).length===0&&(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),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}hd.type="LOCAL";const sw=hd;class dd extends ld{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}dd.type="SESSION";const fd=dd;function iw(n){return Promise.all(n.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}class gi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find(s=>s.isListeningto(e));if(t)return t;const r=new gi(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:s,data:i}=t.data,a=this.handlersMap[s];if(!a?.size)return;t.ports[0].postMessage({status:"ack",eventId:r,eventType:s});const c=Array.from(a).map(async d=>d(t.origin,i)),l=await iw(c);t.ports[0].postMessage({status:"done",eventId:r,eventType:s,response:l})}_subscribe(e,t){Object.keys(this.handlersMap).length===0&&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||this.handlersMap[e].size===0)&&delete this.handlersMap[e],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}gi.receivers=[];function Ia(n="",e=10){let t="";for(let r=0;r<e;r++)t+=Math.floor(Math.random()*10);return n+t}class ow{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){const s=typeof MessageChannel<"u"?new MessageChannel:null;if(!s)throw new Error("connection_unavailable");let i,a;return new Promise((c,l)=>{const d=Ia("",20);s.port1.start();const f=setTimeout(()=>{l(new Error("unsupported_event"))},r);a={messageChannel:s,onMessage(m){const _=m;if(_.data.eventId===d)switch(_.data.status){case"ack":clearTimeout(f),i=setTimeout(()=>{l(new Error("timeout"))},3e3);break;case"done":clearTimeout(i),c(_.data.response);break;default:clearTimeout(f),clearTimeout(i),l(new Error("invalid_response"));break}}},this.handlers.add(a),s.port1.addEventListener("message",a.onMessage),this.target.postMessage({eventType:e,eventId:d,data:t},[s.port2])}).finally(()=>{a&&this.removeMessageHandler(a)})}}function ft(){return window}function aw(n){ft().location.href=n}function pd(){return typeof ft().WorkerGlobalScope<"u"&&typeof ft().importScripts=="function"}async function cw(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function uw(){return navigator?.serviceWorker?.controller||null}function lw(){return pd()?self:null}const md="firebaseLocalStorageDb",hw=1,_i="firebaseLocalStorage",gd="fbase_key";class jr{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 yi(n,e){return n.transaction([_i],e?"readwrite":"readonly").objectStore(_i)}function dw(){const n=indexedDB.deleteDatabase(md);return new jr(n).toPromise()}function va(){const n=indexedDB.open(md,hw);return new Promise((e,t)=>{n.addEventListener("error",()=>{t(n.error)}),n.addEventListener("upgradeneeded",()=>{const r=n.result;try{r.createObjectStore(_i,{keyPath:gd})}catch(s){t(s)}}),n.addEventListener("success",async()=>{const r=n.result;r.objectStoreNames.contains(_i)?e(r):(r.close(),await dw(),e(await va()))})})}async function _d(n,e,t){const r=yi(n,!0).put({[gd]:e,value:t});return new jr(r).toPromise()}async function fw(n,e){const t=yi(n,!1).get(e),r=await new jr(t).toPromise();return r===void 0?null:r.value}function yd(n,e){const t=yi(n,!0).delete(e);return new jr(t).toPromise()}const pw=800,mw=3;class Ed{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:(this.db=await va(),this.db)}async _withRetries(e){let t=0;for(;;)try{const r=await this._openDb();return await e(r)}catch(r){if(t++>mw)throw r;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return pd()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=gi._getInstance(lw()),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){if(this.activeServiceWorker=await cw(),!this.activeServiceWorker)return;this.sender=new ow(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(!(!this.sender||!this.activeServiceWorker||uw()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await va();return await _d(e,mi,"1"),await yd(e,mi),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(r=>_d(r,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(r=>fw(r,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>yd(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(s=>{const i=yi(s,!1).getAll();return new jr(i).toPromise()});if(!e)return[];if(this.pendingWrites!==0)return[];const t=[],r=new Set;if(e.length!==0)for(const{fbase_key:s,value:i}of e)r.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(i)&&(this.notifyListeners(s,i),t.push(s));for(const s of Object.keys(this.localCache))this.localCache[s]&&!r.has(s)&&(this.notifyListeners(s,null),t.push(s));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const s of Array.from(r))s(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),pw)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){Object.keys(this.listeners).length===0&&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),this.listeners[e].size===0&&delete this.listeners[e]),Object.keys(this.listeners).length===0&&this.stopPolling()}}Ed.type="LOCAL";const gw=Ed;new Mr(3e4,6e4);function Aa(n,e){return e?At(e):(M(n._popupRedirectResolver,n,"argument-error"),n._popupRedirectResolver)}class Ra extends Ta{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Yn(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Yn(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Yn(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 _w(n){return od(n.auth,new Ra(n),n.bypassAuthState)}function yw(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),GT(t,new Ra(n),n.bypassAuthState)}async function Ew(n){const{auth:e,user:t}=n;return M(t,e,"internal-error"),HT(t,new Ra(n),n.bypassAuthState)}class Td{constructor(e,t,r,s,i=!1){this.auth=e,this.resolver=r,this.user=s,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(r){this.reject(r)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:s,tenantId:i,error:a,type:c}=e;if(a){this.reject(a);return}const l={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(c)(l))}catch(d){this.reject(d)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _w;case"linkViaPopup":case"linkViaRedirect":return Ew;case"reauthViaPopup":case"reauthViaRedirect":return yw;default:He(this.auth,"internal-error")}}resolve(e){It(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){It(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 Tw=new Mr(2e3,1e4);async function ba(n,e,t){if(Ae(n.app))return Promise.reject(Ye(n,"operation-not-supported-in-this-environment"));const r=lt(n);Ph(n,e,fi);const s=Aa(r,t);return new Wt(r,"signInViaPopup",e,s).executeNotNull()}async function wd(n,e,t){const r=Y(n);Ph(r.auth,e,fi);const s=Aa(r.auth,t);return new Wt(r.auth,"linkViaPopup",e,s,r).executeNotNull()}class Wt extends Td{constructor(e,t,r,s,i){super(e,t,s,i),this.provider=r,this.authWindow=null,this.pollId=null,Wt.currentPopupAction&&Wt.currentPopupAction.cancel(),Wt.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return M(e,this.auth,"internal-error"),e}async onExecution(){It(this.filter.length===1,"Popup operations only handle one event");const e=Ia();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(t=>{this.reject(t)}),this.resolver._isIframeWebStorageSupported(this.auth,t=>{t||this.reject(Ye(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(Ye(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Wt.currentPopupAction=null}pollUserCancellation(){const e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ye(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,Tw.get())};e()}}Wt.currentPopupAction=null;const ww="pendingRedirect",Ei=new Map;class Iw extends Td{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=Ei.get(this.auth._key());if(!e){try{const r=await vw(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(r)}catch(t){e=()=>Promise.reject(t)}Ei.set(this.auth._key(),e)}return this.bypassAuthState||Ei.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if(e.type==="signInViaRedirect")return super.onAuthEvent(e);if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function vw(n,e){const t=bw(e),r=Rw(n);if(!await r._isAvailable())return!1;const s=await r._get(t)==="true";return await r._remove(t),s}function Aw(n,e){Ei.set(n._key(),e)}function Rw(n){return At(n._redirectPersistence)}function bw(n){return li(ww,n.config.apiKey,n.name)}async function Pw(n,e,t=!1){if(Ae(n.app))return Promise.reject(ut(n));const r=lt(n),s=Aa(r,e),a=await new Iw(r,s,t).execute();return a&&!t&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,e)),a}const Cw=10*60*1e3;class Sw{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!kw(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!vd(e)){const r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(Ye(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=Cw&&this.cachedEventUids.clear(),this.cachedEventUids.has(Id(e))}saveEventToCache(e){this.cachedEventUids.add(Id(e)),this.lastProcessedEventTime=Date.now()}}function Id(n){return[n.type,n.eventId,n.sessionId,n.tenantId].filter(e=>e).join("-")}function vd({type:n,error:e}){return n==="unknown"&&e?.code==="auth/no-auth-event"}function kw(n){switch(n.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return vd(n);default:return!1}}async function Nw(n,e={}){return Je(n,"GET","/v1/projects",e)}const Dw=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Ow=/^https?/;async function Vw(n){if(n.config.emulator)return;const{authorizedDomains:e}=await Nw(n);for(const t of e)try{if(Lw(t))return}catch{}He(n,"unauthorized-domain")}function Lw(n){const e=pa(),{protocol:t,hostname:r}=new URL(e);if(n.startsWith("chrome-extension://")){const a=new URL(n);return a.hostname===""&&r===""?t==="chrome-extension:"&&n.replace("chrome-extension://","")===e.replace("chrome-extension://",""):t==="chrome-extension:"&&a.hostname===r}if(!Ow.test(t))return!1;if(Dw.test(n))return r===n;const s=n.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(r)}const Mw=new Mr(3e4,6e4);function Ad(){const n=ft().___jsl;if(n?.H){for(const e of Object.keys(n.H))if(n.H[e].r=n.H[e].r||[],n.H[e].L=n.H[e].L||[],n.H[e].r=[...n.H[e].L],n.CP)for(let t=0;t<n.CP.length;t++)n.CP[t]=null}}function xw(n){return new Promise((e,t)=>{function r(){Ad(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Ad(),t(Ye(n,"network-request-failed"))},timeout:Mw.get()})}if(ft().gapi?.iframes?.Iframe)e(gapi.iframes.getContext());else if(ft().gapi?.load)r();else{const s=RT("iframefcb");return ft()[s]=()=>{gapi.load?r():t(Ye(n,"network-request-failed"))},Qh(`${AT()}?onload=${s}`).catch(i=>t(i))}}).catch(e=>{throw Ti=null,e})}let Ti=null;function Uw(n){return Ti=Ti||xw(n),Ti}const Fw=new Mr(5e3,15e3),Bw="__/auth/iframe",qw="emulator/auth/iframe",jw={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},$w=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function zw(n){const e=n.config;M(e.authDomain,n,"auth-domain-config-required");const t=e.emulator?ma(e,qw):`https://${n.config.authDomain}/${Bw}`,r={apiKey:e.apiKey,appName:n.name,v:nn},s=$w.get(n.config.apiHost);s&&(r.eid=s);const i=n._getFrameworks();return i.length&&(r.fw=i.join(",")),`${t}?${ur(r).slice(1)}`}async function Hw(n){const e=await Uw(n),t=ft().gapi;return M(t,n,"internal-error"),e.open({where:document.body,url:zw(n),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:jw,dontclear:!0},r=>new Promise(async(s,i)=>{await r.restyle({setHideOnLeave:!1});const a=Ye(n,"network-request-failed"),c=ft().setTimeout(()=>{i(a)},Fw.get());function l(){ft().clearTimeout(c),s(r)}r.ping(l).then(l,()=>{i(a)})}))}const Ww={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},Gw=500,Kw=600,Qw="_blank",Yw="http://localhost";class Rd{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function Jw(n,e,t,r=Gw,s=Kw){const i=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const l={...Ww,width:r.toString(),height:s.toString(),top:i,left:a},d=ve().toLowerCase();t&&(c=qh(d)?Qw:t),Fh(d)&&(e=e||Yw,l.scrollbars="yes");const f=Object.entries(l).reduce((_,[R,S])=>`${_}${R}=${S},`,"");if(mT(d)&&c!=="_self")return Xw(e||"",c),new Rd(null);const m=window.open(e||"",c,f);M(m,n,"popup-blocked");try{m.focus()}catch{}return new Rd(m)}function Xw(n,e){const t=document.createElement("a");t.href=n,t.target=e;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),t.dispatchEvent(r)}const Zw="__/auth/handler",eI="emulator/auth/handler",tI=encodeURIComponent("fac");async function bd(n,e,t,r,s,i){M(n.config.authDomain,n,"auth-domain-config-required"),M(n.config.apiKey,n,"invalid-api-key");const a={apiKey:n.config.apiKey,appName:n.name,authType:t,redirectUrl:r,v:nn,eventId:s};if(e instanceof fi){e.setDefaultLanguage(n.languageCode),a.providerId=e.providerId||"",Lp(e.getCustomParameters())||(a.customParameters=JSON.stringify(e.getCustomParameters()));for(const[f,m]of Object.entries({}))a[f]=m}if(e instanceof qr){const f=e.getScopes().filter(m=>m!=="");f.length>0&&(a.scopes=f.join(","))}n.tenantId&&(a.tid=n.tenantId);const c=a;for(const f of Object.keys(c))c[f]===void 0&&delete c[f];const l=await n._getAppCheckToken(),d=l?`#${tI}=${encodeURIComponent(l)}`:"";return`${nI(n)}?${ur(c).slice(1)}${d}`}function nI({config:n}){return n.emulator?ma(n,eI):`https://${n.authDomain}/${Zw}`}const Pa="webStorageSupport";class rI{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=fd,this._completeRedirectFn=Pw,this._overrideRedirectResult=Aw}async _openPopup(e,t,r,s){It(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const i=await bd(e,t,r,pa(),s);return Jw(e,i,Ia())}async _openRedirect(e,t,r,s){await this._originValidation(e);const i=await bd(e,t,r,pa(),s);return aw(i),new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:s,promise:i}=this.eventManagers[t];return s?Promise.resolve(s):(It(i,"If manager is not set, promise should be"),i)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch(()=>{delete this.eventManagers[t]}),r}async initAndGetManager(e){const t=await Hw(e),r=new Sw(e);return t.register("authEvent",s=>(M(s?.authEvent,e,"invalid-auth-event"),{status:r.onEvent(s.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(Pa,{type:Pa},s=>{const i=s?.[0]?.[Pa];i!==void 0&&t(!!i),He(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Vw(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Wh()||Bh()||Ea()}}const sI=rI;var Pd="@firebase/auth",Cd="1.12.1";class iI{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(r=>{e(r?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){M(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function oI(n){switch(n){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function aI(n){Ct(new _t("auth",(e,{options:t})=>{const r=e.getProvider("app").getImmediate(),s=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:a,authDomain:c}=r.options;M(a&&!a.includes(":"),"invalid-api-key",{appName:r.name});const l={apiKey:a,authDomain:c,clientPlatform:n,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Gh(n)},d=new wT(r,s,i,l);return NT(d,t),d},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),Ct(new _t("auth-internal",e=>{const t=lt(e.getProvider("auth").getImmediate());return(r=>new iI(r))(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),je(Pd,Cd,oI(n)),je(Pd,Cd,"esm2020")}const cI=5*60,uI=_c("authIdTokenMaxAge")||cI;let Sd=null;const lI=n=>async e=>{const t=e&&await e.getIdTokenResult(),r=t&&(new Date().getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>uI)return;const s=t?.token;Sd!==s&&(Sd=s,await fetch(n,{method:s?"POST":"DELETE",headers:s?{Authorization:`Bearer ${s}`}:{}}))};function hI(n=fs()){const e=dr(n,"auth");if(e.isInitialized())return e.getImmediate();const t=kT(n,{popupRedirectResolver:sI,persistence:[gw,sw,fd]}),r=_c("authTokenSyncURL");if(r&&typeof isSecureContext=="boolean"&&isSecureContext){const i=new URL(r,location.origin);if(location.origin===i.origin){const a=lI(i.toString());tw(t,a,()=>a(t.currentUser)),ew(t,c=>a(c))}}const s=mc("auth");return s&&Xh(t,`http://${s}`),t}function dI(){return document.getElementsByTagName("head")?.[0]??document}IT({loadJS(n){return new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",n),r.onload=e,r.onerror=s=>{const i=Ye("internal-error");i.customData=s,t(i)},r.type="text/javascript",r.charset="UTF-8",dI().appendChild(r)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="}),aI("Browser");const kd="firebasestorage.googleapis.com",Nd="storageBucket",fI=2*60*1e3,pI=10*60*1e3,mI=1e3;class ie extends We{constructor(e,t,r=0){super(Ca(e),`Firebase Storage: ${t} (${Ca(e)})`),this.status_=r,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,ie.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return Ca(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
43
+ ${this.customData.serverResponse}`:this.message=this._baseMessage}}var te;(function(n){n.UNKNOWN="unknown",n.OBJECT_NOT_FOUND="object-not-found",n.BUCKET_NOT_FOUND="bucket-not-found",n.PROJECT_NOT_FOUND="project-not-found",n.QUOTA_EXCEEDED="quota-exceeded",n.UNAUTHENTICATED="unauthenticated",n.UNAUTHORIZED="unauthorized",n.UNAUTHORIZED_APP="unauthorized-app",n.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",n.INVALID_CHECKSUM="invalid-checksum",n.CANCELED="canceled",n.INVALID_EVENT_NAME="invalid-event-name",n.INVALID_URL="invalid-url",n.INVALID_DEFAULT_BUCKET="invalid-default-bucket",n.NO_DEFAULT_BUCKET="no-default-bucket",n.CANNOT_SLICE_BLOB="cannot-slice-blob",n.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",n.NO_DOWNLOAD_URL="no-download-url",n.INVALID_ARGUMENT="invalid-argument",n.INVALID_ARGUMENT_COUNT="invalid-argument-count",n.APP_DELETED="app-deleted",n.INVALID_ROOT_OPERATION="invalid-root-operation",n.INVALID_FORMAT="invalid-format",n.INTERNAL_ERROR="internal-error",n.UNSUPPORTED_ENVIRONMENT="unsupported-environment"})(te||(te={}));function Ca(n){return"storage/"+n}function Sa(){const n="An unknown error occurred, please check the error payload for server response.";return new ie(te.UNKNOWN,n)}function gI(n){return new ie(te.OBJECT_NOT_FOUND,"Object '"+n+"' does not exist.")}function _I(n){return new ie(te.QUOTA_EXCEEDED,"Quota for bucket '"+n+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function yI(){const n="User is not authenticated, please authenticate using Firebase Authentication and try again.";return new ie(te.UNAUTHENTICATED,n)}function EI(){return new ie(te.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}function TI(n){return new ie(te.UNAUTHORIZED,"User does not have permission to access '"+n+"'.")}function Dd(){return new ie(te.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function Od(){return new ie(te.CANCELED,"User canceled the upload/download.")}function wI(n){return new ie(te.INVALID_URL,"Invalid URL '"+n+"'.")}function II(n){return new ie(te.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+n+"'.")}function vI(){return new ie(te.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+Nd+"' property when initializing the app?")}function Vd(){return new ie(te.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function AI(){return new ie(te.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function RI(){return new ie(te.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function bI(n){return new ie(te.UNSUPPORTED_ENVIRONMENT,`${n} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}function ka(n){return new ie(te.INVALID_ARGUMENT,n)}function Ld(){return new ie(te.APP_DELETED,"The Firebase app was deleted.")}function PI(n){return new ie(te.INVALID_ROOT_OPERATION,"The operation '"+n+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function $r(n,e){return new ie(te.INVALID_FORMAT,"String does not match format '"+n+"': "+e)}function zr(n){throw new ie(te.INTERNAL_ERROR,"Internal error: "+n)}class Be{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return this.path.length===0}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let r;try{r=Be.makeFromUrl(e,t)}catch{return new Be(e,"")}if(r.path==="")return r;throw II(e)}static makeFromUrl(e,t){let r=null;const s="([A-Za-z0-9.\\-_]+)";function i(Q){Q.path.charAt(Q.path.length-1)==="/"&&(Q.path_=Q.path_.slice(0,-1))}const a="(/(.*))?$",c=new RegExp("^gs://"+s+a,"i"),l={bucket:1,path:3};function d(Q){Q.path_=decodeURIComponent(Q.path)}const f="v[A-Za-z0-9_]+",m=t.replace(/[.]/g,"\\."),_="(/([^?#]*).*)?$",R=new RegExp(`^https?://${m}/${f}/b/${s}/o${_}`,"i"),S={bucket:1,path:3},N=t===kd?"(?:storage.googleapis.com|storage.cloud.google.com)":t,k="([^?#]*)",U=new RegExp(`^https?://${N}/${s}/${k}`,"i"),j=[{regex:c,indices:l,postModify:i},{regex:R,indices:S,postModify:d},{regex:U,indices:{bucket:1,path:2},postModify:d}];for(let Q=0;Q<j.length;Q++){const _e=j[Q],re=_e.regex.exec(e);if(re){const w=re[_e.indices.bucket];let g=re[_e.indices.path];g||(g=""),r=new Be(w,g),_e.postModify(r);break}}if(r==null)throw wI(e);return r}}class CI{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}function SI(n,e,t){let r=1,s=null,i=null,a=!1,c=0;function l(){return c===2}let d=!1;function f(...k){d||(d=!0,e.apply(null,k))}function m(k){s=setTimeout(()=>{s=null,n(R,l())},k)}function _(){i&&clearTimeout(i)}function R(k,...U){if(d){_();return}if(k){_(),f.call(null,k,...U);return}if(l()||a){_(),f.call(null,k,...U);return}r<64&&(r*=2);let j;c===1?(c=2,j=0):j=(r+Math.random())*1e3,m(j)}let S=!1;function N(k){S||(S=!0,_(),!d&&(s!==null?(k||(c=2),clearTimeout(s),m(0)):k||(c=1)))}return m(0),i=setTimeout(()=>{a=!0,N(!0)},t),N}function kI(n){n(!1)}function NI(n){return n!==void 0}function DI(n){return typeof n=="function"}function OI(n){return typeof n=="object"&&!Array.isArray(n)}function wi(n){return typeof n=="string"||n instanceof String}function Md(n){return Na()&&n instanceof Blob}function Na(){return typeof Blob<"u"}function xd(n,e,t,r){if(r<e)throw ka(`Invalid value for '${n}'. Expected ${e} or greater.`);if(r>t)throw ka(`Invalid value for '${n}'. Expected ${t} or less.`)}function Xn(n,e,t){let r=e;return t==null&&(r=`https://${e}`),`${t}://${r}/v0${n}`}function Ud(n){const e=encodeURIComponent;let t="?";for(const r in n)if(n.hasOwnProperty(r)){const s=e(r)+"="+e(n[r]);t=t+s+"&"}return t=t.slice(0,-1),t}var gn;(function(n){n[n.NO_ERROR=0]="NO_ERROR",n[n.NETWORK_ERROR=1]="NETWORK_ERROR",n[n.ABORT=2]="ABORT"})(gn||(gn={}));function Fd(n,e){const t=n>=500&&n<600,s=[408,429].indexOf(n)!==-1,i=e.indexOf(n)!==-1;return t||s||i}class VI{constructor(e,t,r,s,i,a,c,l,d,f,m,_=!0,R=!1){this.url_=e,this.method_=t,this.headers_=r,this.body_=s,this.successCodes_=i,this.additionalRetryCodes_=a,this.callback_=c,this.errorCallback_=l,this.timeout_=d,this.progressCallback_=f,this.connectionFactory_=m,this.retry=_,this.isUsingEmulator=R,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((S,N)=>{this.resolve_=S,this.reject_=N,this.start_()})}start_(){const e=(r,s)=>{if(s){r(!1,new Ii(!1,null,!0));return}const i=this.connectionFactory_();this.pendingConnection_=i;const a=c=>{const l=c.loaded,d=c.lengthComputable?c.total:-1;this.progressCallback_!==null&&this.progressCallback_(l,d)};this.progressCallback_!==null&&i.addUploadProgressListener(a),i.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{this.progressCallback_!==null&&i.removeUploadProgressListener(a),this.pendingConnection_=null;const c=i.getErrorCode()===gn.NO_ERROR,l=i.getStatus();if(!c||Fd(l,this.additionalRetryCodes_)&&this.retry){const f=i.getErrorCode()===gn.ABORT;r(!1,new Ii(!1,null,f));return}const d=this.successCodes_.indexOf(l)!==-1;r(!0,new Ii(d,i))})},t=(r,s)=>{const i=this.resolve_,a=this.reject_,c=s.connection;if(s.wasSuccessCode)try{const l=this.callback_(c,c.getResponse());NI(l)?i(l):i()}catch(l){a(l)}else if(c!==null){const l=Sa();l.serverResponse=c.getErrorText(),this.errorCallback_?a(this.errorCallback_(c,l)):a(l)}else if(s.canceled){const l=this.appDelete_?Ld():Od();a(l)}else{const l=Dd();a(l)}};this.canceled_?t(!1,new Ii(!1,null,!0)):this.backoffId_=SI(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,this.backoffId_!==null&&kI(this.backoffId_),this.pendingConnection_!==null&&this.pendingConnection_.abort()}}class Ii{constructor(e,t,r){this.wasSuccessCode=e,this.connection=t,this.canceled=!!r}}function LI(n,e){e!==null&&e.length>0&&(n.Authorization="Firebase "+e)}function MI(n,e){n["X-Firebase-Storage-Version"]="webjs/"+(e??"AppManager")}function xI(n,e){e&&(n["X-Firebase-GMPID"]=e)}function UI(n,e){e!==null&&(n["X-Firebase-AppCheck"]=e)}function FI(n,e,t,r,s,i,a=!0,c=!1){const l=Ud(n.urlParams),d=n.url+l,f=Object.assign({},n.headers);return xI(f,e),LI(f,t),MI(f,i),UI(f,r),new VI(d,n.method,f,n.body,n.successCodes,n.additionalRetryCodes,n.handler,n.errorHandler,n.timeout,n.progressCallback,s,a,c)}function BI(){return typeof BlobBuilder<"u"?BlobBuilder:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:void 0}function qI(...n){const e=BI();if(e!==void 0){const t=new e;for(let r=0;r<n.length;r++)t.append(n[r]);return t.getBlob()}else{if(Na())return new Blob(n);throw new ie(te.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}}function jI(n,e,t){return n.webkitSlice?n.webkitSlice(e,t):n.mozSlice?n.mozSlice(e,t):n.slice?n.slice(e,t):null}function $I(n){if(typeof atob>"u")throw bI("base-64");return atob(n)}const pt={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class Da{constructor(e,t){this.data=e,this.contentType=t||null}}function zI(n,e){switch(n){case pt.RAW:return new Da(Bd(e));case pt.BASE64:case pt.BASE64URL:return new Da(qd(n,e));case pt.DATA_URL:return new Da(WI(e),GI(e))}throw Sa()}function Bd(n){const e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r<=127)e.push(r);else if(r<=2047)e.push(192|r>>6,128|r&63);else if((r&64512)===55296)if(!(t<n.length-1&&(n.charCodeAt(t+1)&64512)===56320))e.push(239,191,189);else{const i=r,a=n.charCodeAt(++t);r=65536|(i&1023)<<10|a&1023,e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}else(r&64512)===56320?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|r&63)}return new Uint8Array(e)}function HI(n){let e;try{e=decodeURIComponent(n)}catch{throw $r(pt.DATA_URL,"Malformed data URL.")}return Bd(e)}function qd(n,e){switch(n){case pt.BASE64:{const s=e.indexOf("-")!==-1,i=e.indexOf("_")!==-1;if(s||i)throw $r(n,"Invalid character '"+(s?"-":"_")+"' found: is it base64url encoded?");break}case pt.BASE64URL:{const s=e.indexOf("+")!==-1,i=e.indexOf("/")!==-1;if(s||i)throw $r(n,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/");break}}let t;try{t=$I(e)}catch(s){throw s.message.includes("polyfill")?s:$r(n,"Invalid character found")}const r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}class jd{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(t===null)throw $r(pt.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const r=t[1]||null;r!=null&&(this.base64=KI(r,";base64"),this.contentType=this.base64?r.substring(0,r.length-7):r),this.rest=e.substring(e.indexOf(",")+1)}}function WI(n){const e=new jd(n);return e.base64?qd(pt.BASE64,e.rest):HI(e.rest)}function GI(n){return new jd(n).contentType}function KI(n,e){return n.length>=e.length?n.substring(n.length-e.length)===e:!1}class Gt{constructor(e,t){let r=0,s="";Md(e)?(this.data_=e,r=e.size,s=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),r=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),r=e.length),this.size_=r,this.type_=s}size(){return this.size_}type(){return this.type_}slice(e,t){if(Md(this.data_)){const r=this.data_,s=jI(r,e,t);return s===null?null:new Gt(s)}else{const r=new Uint8Array(this.data_.buffer,e,t-e);return new Gt(r,!0)}}static getBlob(...e){if(Na()){const t=e.map(r=>r instanceof Gt?r.data_:r);return new Gt(qI.apply(null,t))}else{const t=e.map(a=>wi(a)?zI(pt.RAW,a).data:a.data_);let r=0;t.forEach(a=>{r+=a.byteLength});const s=new Uint8Array(r);let i=0;return t.forEach(a=>{for(let c=0;c<a.length;c++)s[i++]=a[c]}),new Gt(s,!0)}}uploadData(){return this.data_}}function $d(n){let e;try{e=JSON.parse(n)}catch{return null}return OI(e)?e:null}function QI(n){if(n.length===0)return null;const e=n.lastIndexOf("/");return e===-1?"":n.slice(0,e)}function YI(n,e){const t=e.split("/").filter(r=>r.length>0).join("/");return n.length===0?t:n+"/"+t}function zd(n){const e=n.lastIndexOf("/",n.length-2);return e===-1?n:n.slice(e+1)}function JI(n,e){return e}class ke{constructor(e,t,r,s){this.server=e,this.local=t||e,this.writable=!!r,this.xform=s||JI}}let vi=null;function XI(n){return!wi(n)||n.length<2?n:zd(n)}function Hd(){if(vi)return vi;const n=[];n.push(new ke("bucket")),n.push(new ke("generation")),n.push(new ke("metageneration")),n.push(new ke("name","fullPath",!0));function e(i,a){return XI(a)}const t=new ke("name");t.xform=e,n.push(t);function r(i,a){return a!==void 0?Number(a):a}const s=new ke("size");return s.xform=r,n.push(s),n.push(new ke("timeCreated")),n.push(new ke("updated")),n.push(new ke("md5Hash",null,!0)),n.push(new ke("cacheControl",null,!0)),n.push(new ke("contentDisposition",null,!0)),n.push(new ke("contentEncoding",null,!0)),n.push(new ke("contentLanguage",null,!0)),n.push(new ke("contentType",null,!0)),n.push(new ke("metadata","customMetadata",!0)),vi=n,vi}function ZI(n,e){function t(){const r=n.bucket,s=n.fullPath,i=new Be(r,s);return e._makeStorageReference(i)}Object.defineProperty(n,"ref",{get:t})}function ev(n,e,t){const r={};r.type="file";const s=t.length;for(let i=0;i<s;i++){const a=t[i];r[a.local]=a.xform(r,e[a.server])}return ZI(r,n),r}function Wd(n,e,t){const r=$d(e);return r===null?null:ev(n,r,t)}function tv(n,e,t,r){const s=$d(e);if(s===null||!wi(s.downloadTokens))return null;const i=s.downloadTokens;if(i.length===0)return null;const a=encodeURIComponent;return i.split(",").map(d=>{const f=n.bucket,m=n.fullPath,_="/b/"+a(f)+"/o/"+a(m),R=Xn(_,t,r),S=Ud({alt:"media",token:d});return R+S})[0]}function Gd(n,e){const t={},r=e.length;for(let s=0;s<r;s++){const i=e[s];i.writable&&(t[i.server]=n[i.local])}return JSON.stringify(t)}class _n{constructor(e,t,r,s){this.url=e,this.method=t,this.handler=r,this.timeout=s,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function bt(n){if(!n)throw Sa()}function Oa(n,e){function t(r,s){const i=Wd(n,s,e);return bt(i!==null),i}return t}function nv(n,e){function t(r,s){const i=Wd(n,s,e);return bt(i!==null),tv(i,s,n.host,n._protocol)}return t}function Hr(n){function e(t,r){let s;return t.getStatus()===401?t.getErrorText().includes("Firebase App Check token is invalid")?s=EI():s=yI():t.getStatus()===402?s=_I(n.bucket):t.getStatus()===403?s=TI(n.path):s=r,s.status=t.getStatus(),s.serverResponse=r.serverResponse,s}return e}function Va(n){const e=Hr(n);function t(r,s){let i=e(r,s);return r.getStatus()===404&&(i=gI(n.path)),i.serverResponse=s.serverResponse,i}return t}function rv(n,e,t){const r=e.fullServerUrl(),s=Xn(r,n.host,n._protocol),i="GET",a=n.maxOperationRetryTime,c=new _n(s,i,Oa(n,t),a);return c.errorHandler=Va(e),c}function sv(n,e,t){const r=e.fullServerUrl(),s=Xn(r,n.host,n._protocol),i="GET",a=n.maxOperationRetryTime,c=new _n(s,i,nv(n,t),a);return c.errorHandler=Va(e),c}function iv(n,e){const t=e.fullServerUrl(),r=Xn(t,n.host,n._protocol),s="DELETE",i=n.maxOperationRetryTime;function a(l,d){}const c=new _n(r,s,a,i);return c.successCodes=[200,204],c.errorHandler=Va(e),c}function ov(n,e){return n&&n.contentType||e&&e.type()||"application/octet-stream"}function Kd(n,e,t){const r=Object.assign({},t);return r.fullPath=n.path,r.size=e.size(),r.contentType||(r.contentType=ov(null,e)),r}function av(n,e,t,r,s){const i=e.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};function c(){let j="";for(let Q=0;Q<2;Q++)j=j+Math.random().toString().slice(2);return j}const l=c();a["Content-Type"]="multipart/related; boundary="+l;const d=Kd(e,r,s),f=Gd(d,t),m="--"+l+`\r
44
44
  Content-Type: application/json; charset=utf-8\r
45
45
  \r
46
46
  `+f+`\r
47
47
  --`+l+`\r
48
48
  Content-Type: `+d.contentType+`\r
49
49
  \r
50
- `,g=`\r
51
- --`+l+"--",R=Gt.getBlob(m,r,g);if(R===null)throw Vd();const C={name:d.fullPath},N=Xn(i,n.host,n._protocol),k="POST",F=n.maxUploadRetryTime,$=new gn(N,k,Oa(n,t),F);return $.urlParams=C,$.headers=a,$.body=R.uploadData(),$.errorHandler=Hr(e),$}class Ai{constructor(e,t,r,s){this.current=e,this.total=t,this.finalized=!!r,this.metadata=s||null}}function La(n,e){let t=null;try{t=n.getResponseHeader("X-Goog-Upload-Status")}catch{bt(!1)}return bt(!!t&&(e||["active"]).indexOf(t)!==-1),t}function cv(n,e,t,r,s){const i=e.bucketOnlyServerUrl(),a=Kd(e,r,s),c={name:a.fullPath},l=Xn(i,n.host,n._protocol),d="POST",f={"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"},m=Gd(a,t),g=n.maxUploadRetryTime;function R(N){La(N);let k;try{k=N.getResponseHeader("X-Goog-Upload-URL")}catch{bt(!1)}return bt(wi(k)),k}const C=new gn(l,d,R,g);return C.urlParams=c,C.headers=f,C.body=m,C.errorHandler=Hr(e),C}function uv(n,e,t,r){const s={"X-Goog-Upload-Command":"query"};function i(d){const f=La(d,["active","final"]);let m=null;try{m=d.getResponseHeader("X-Goog-Upload-Size-Received")}catch{bt(!1)}m||bt(!1);const g=Number(m);return bt(!isNaN(g)),new Ai(g,r.size(),f==="final")}const a="POST",c=n.maxUploadRetryTime,l=new gn(t,a,i,c);return l.headers=s,l.errorHandler=Hr(e),l}const Qd=256*1024;function lv(n,e,t,r,s,i,a,c){const l=new Ai(0,0);if(a?(l.current=a.current,l.total=a.total):(l.current=0,l.total=r.size()),r.size()!==l.total)throw AI();const d=l.total-l.current;let f=d;s>0&&(f=Math.min(f,s));const m=l.current,g=m+f;let R="";f===0?R="finalize":d===f?R="upload, finalize":R="upload";const C={"X-Goog-Upload-Command":R,"X-Goog-Upload-Offset":`${l.current}`},N=r.slice(m,g);if(N===null)throw Vd();function k(J,_e){const re=La(J,["active","final"]),w=l.current+f,_=r.size();let E;return re==="final"?E=Oa(e,i)(J,_e):E=null,new Ai(w,_,re==="final",E)}const F="POST",$=e.maxUploadRetryTime,j=new gn(t,F,k,$);return j.headers=C,j.body=N.uploadData(),j.progressCallback=c||null,j.errorHandler=Hr(n),j}const Ve={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Ma(n){switch(n){case"running":case"pausing":case"canceling":return Ve.RUNNING;case"paused":return Ve.PAUSED;case"success":return Ve.SUCCESS;case"canceled":return Ve.CANCELED;case"error":return Ve.ERROR;default:return Ve.ERROR}}class hv{constructor(e,t,r){if(DI(e)||t!=null||r!=null)this.next=e,this.error=t??void 0,this.complete=r??void 0;else{const i=e;this.next=i.next,this.error=i.error,this.complete=i.complete}}}function Zn(n){return(...e)=>{Promise.resolve().then(()=>n(...e))}}class dv{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=mn.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=mn.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=mn.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,s,i){if(this.sent_)throw zr("cannot .send() more than once");if(tt(e)&&r&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(t,e,!0),i!==void 0)for(const a in i)i.hasOwnProperty(a)&&this.xhr_.setRequestHeader(a,i[a].toString());return s!==void 0?this.xhr_.send(s):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw zr("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw zr("cannot .getStatus() before sending");try{return this.xhr_.status}catch{return-1}}getResponse(){if(!this.sent_)throw zr("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw zr("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.removeEventListener("progress",e)}}class fv extends dv{initXhr(){this.xhr_.responseType="text"}}function _n(){return new fv}class pv{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=Hd(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=s=>{if(this._request=void 0,this._chunkMultiplier=1,s._codeEquals(te.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const i=this.isExponentialBackoffExpired();if(Fd(s.status,[]))if(i)s=Dd();else{this.sleepTime=Math.max(this.sleepTime*2,mI),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=s,this._transition("error")}},this._metadataErrorHandler=s=>{this._request=void 0,s._codeEquals(te.CANCELED)?this.completeTransitions_():(this._error=s,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((s,i)=>{this._resolve=s,this._reject=i,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>256*1024}_start(){this._state==="running"&&this._request===void 0&&(this._resumable?this._uploadUrl===void 0?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([t,r])=>{switch(this._state){case"running":e(t,r);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((e,t)=>{const r=cv(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),s=this._ref.storage._makeRequest(r,_n,e,t);this._request=s,s.getPromise().then(i=>{this._request=void 0,this._uploadUrl=i,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const e=this._uploadUrl;this._resolveToken((t,r)=>{const s=uv(this._ref.storage,this._ref._location,e,this._blob),i=this._ref.storage._makeRequest(s,_n,t,r);this._request=i,i.getPromise().then(a=>{a=a,this._request=void 0,this._updateProgress(a.current),this._needToFetchStatus=!1,a.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const e=Qd*this._chunkMultiplier,t=new Ai(this._transferred,this._blob.size()),r=this._uploadUrl;this._resolveToken((s,i)=>{let a;try{a=lv(this._ref._location,this._ref.storage,r,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(l){this._error=l,this._transition("error");return}const c=this._ref.storage._makeRequest(a,_n,s,i,!1);this._request=c,c.getPromise().then(l=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(l.current),l.finalized?(this._metadata=l.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){Qd*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{const r=rv(this._ref.storage,this._ref._location,this._mappings),s=this._ref.storage._makeRequest(r,_n,e,t);this._request=s,s.getPromise().then(i=>{this._request=void 0,this._metadata=i,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{const r=av(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),s=this._ref.storage._makeRequest(r,_n,e,t);this._request=s,s.getPromise().then(i=>{this._request=void 0,this._metadata=i,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){const 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,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t=this._state==="paused";this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Od(),this._state=e,this._notifyObservers();break;case"error":this._state=e,this._notifyObservers();break;case"success":this._state=e,this._notifyObservers();break}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start();break}}get snapshot(){const e=Ma(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,s){const i=new hv(t||void 0,r||void 0,s||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){const t=this._observers.indexOf(e);t!==-1&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(t=>{this._notifyObserver(t)})}_finishPromise(){if(this._resolve!==void 0){let e=!0;switch(Ma(this._state)){case Ve.SUCCESS:Zn(this._resolve.bind(null,this.snapshot))();break;case Ve.CANCELED:case Ve.ERROR:const t=this._reject;Zn(t.bind(null,this._error))();break;default:e=!1;break}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Ma(this._state)){case Ve.RUNNING:case Ve.PAUSED:e.next&&Zn(e.next.bind(e,this.snapshot))();break;case Ve.SUCCESS:e.complete&&Zn(e.complete.bind(e))();break;case Ve.CANCELED:case Ve.ERROR:e.error&&Zn(e.error.bind(e,this._error))();break;default:e.error&&Zn(e.error.bind(e,this._error))()}}resume(){const e=this._state==="paused"||this._state==="pausing";return e&&this._transition("running"),e}pause(){const e=this._state==="running";return e&&this._transition("pausing"),e}cancel(){const e=this._state==="running"||this._state==="pausing";return e&&this._transition("canceling"),e}}class yn{constructor(e,t){this._service=e,t instanceof Be?this._location=t:this._location=Be.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new yn(e,t)}get root(){const e=new Be(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return zd(this._location.path)}get storage(){return this._service}get parent(){const e=QI(this._location.path);if(e===null)return null;const t=new Be(this._location.bucket,e);return new yn(this._service,t)}_throwIfRoot(e){if(this._location.path==="")throw PI(e)}}function mv(n,e,t){return n._throwIfRoot("uploadBytesResumable"),new pv(n,new Gt(e),t)}function gv(n){n._throwIfRoot("getDownloadURL");const e=sv(n.storage,n._location,Hd());return n.storage.makeRequestWithTokens(e,_n).then(t=>{if(t===null)throw RI();return t})}function _v(n){n._throwIfRoot("deleteObject");const e=iv(n.storage,n._location);return n.storage.makeRequestWithTokens(e,_n)}function yv(n,e){const t=YI(n._location.path,e),r=new Be(n._location.bucket,t);return new yn(n.storage,r)}function Ev(n){return/^[A-Za-z]+:\/\//.test(n)}function Tv(n,e){return new yn(n,e)}function Yd(n,e){if(n instanceof xa){const t=n;if(t._bucket==null)throw vI();const r=new yn(t,t._bucket);return e!=null?Yd(r,e):r}else return e!==void 0?yv(n,e):n}function wv(n,e){if(e&&Ev(e)){if(n instanceof xa)return Tv(n,e);throw ka("To use ref(service, url), the first argument must be a Storage instance.")}else return Yd(n,e)}function Jd(n,e){const t=e?.[Nd];return t==null?null:Be.makeFromBucketSpec(t,n)}function Iv(n,e,t,r={}){n.host=`${e}:${t}`;const s=tt(e);s&&(ls(`https://${n.host}/b`),hs("Storage",!0)),n._isUsingEmulator=!0,n._protocol=s?"https":"http";const{mockUserToken:i}=r;i&&(n._overrideAuthToken=typeof i=="string"?i:yc(i,n.app.options.projectId))}class xa{constructor(e,t,r,s,i,a=!1){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=s,this._firebaseVersion=i,this._isUsingEmulator=a,this._bucket=null,this._host=kd,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=fI,this._maxUploadRetryTime=pI,this._requests=new Set,s!=null?this._bucket=Be.makeFromBucketSpec(s,this._host):this._bucket=Jd(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,this._url!=null?this._bucket=Be.makeFromBucketSpec(this._url,e):this._bucket=Jd(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){xd("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){xd("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){const t=await e.getToken();if(t!==null)return t.accessToken}return null}async _getAppCheckToken(){if(Ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;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 yn(this,e)}_makeRequest(e,t,r,s,i=!0){if(this._deleted)return new SI(Ld());{const a=FI(e,this._appId,r,s,t,this._firebaseVersion,i,this._isUsingEmulator);return this._requests.add(a),a.getPromise().then(()=>this._requests.delete(a),()=>this._requests.delete(a)),a}}async makeRequestWithTokens(e,t){const[r,s]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,s).getPromise()}}const Xd="@firebase/storage",Zd="0.14.0";const ef="storage";function vv(n,e,t){return n=Q(n),mv(n,e,t)}function Av(n){return n=Q(n),gv(n)}function Rv(n){return n=Q(n),_v(n)}function Ua(n,e){return n=Q(n),wv(n,e)}function bv(n=fs(),e){n=Q(n);const r=dr(n,ef).getImmediate({identifier:e}),s=ji("storage");return s&&tf(r,...s),r}function tf(n,e,t,r={}){Iv(n,e,t,r)}function Pv(n,{instanceIdentifier:e}){const t=n.getProvider("app").getImmediate(),r=n.getProvider("auth-internal"),s=n.getProvider("app-check-internal");return new xa(t,r,s,e,nn)}function Sv(){St(new _t(ef,Pv,"PUBLIC").setMultipleInstances(!0)),je(Xd,Zd,""),je(Xd,Zd,"esm2020")}Sv();const Cv="type.googleapis.com/google.protobuf.Int64Value",kv="type.googleapis.com/google.protobuf.UInt64Value";function nf(n,e){const t={};for(const r in n)n.hasOwnProperty(r)&&(t[r]=e(n[r]));return t}function Ri(n){if(n==null)return null;if(n instanceof Number&&(n=n.valueOf()),typeof n=="number"&&isFinite(n)||n===!0||n===!1||Object.prototype.toString.call(n)==="[object String]")return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(e=>Ri(e));if(typeof n=="function"||typeof n=="object")return nf(n,e=>Ri(e));throw new Error("Data cannot be encoded in JSON: "+n)}function er(n){if(n==null)return n;if(n["@type"])switch(n["@type"]){case Cv:case kv:{const e=Number(n.value);if(isNaN(e))throw new Error("Data cannot be decoded from JSON: "+n);return e}default:throw new Error("Data cannot be decoded from JSON: "+n)}return Array.isArray(n)?n.map(e=>er(e)):typeof n=="function"||typeof n=="object"?nf(n,e=>er(e)):n}const Fa="functions";const rf={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 Le extends We{constructor(e,t,r){super(`${Fa}/${e}`,t||""),this.details=r,Object.setPrototypeOf(this,Le.prototype)}}function Nv(n){if(n>=200&&n<300)return"ok";switch(n){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"}function bi(n,e){let t=Nv(n),r=t,s;try{const i=e&&e.error;if(i){const a=i.status;if(typeof a=="string"){if(!rf[a])return new Le("internal","internal");t=rf[a],r=a}const c=i.message;typeof c=="string"&&(r=c),s=i.details,s!==void 0&&(s=er(s))}}catch{}return t==="ok"?null:new Le(t,r,s)}class Dv{constructor(e,t,r,s){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,Ae(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=t.getImmediate({optional:!0}),this.messaging=r.getImmediate({optional:!0}),this.auth||t.get().then(i=>this.auth=i,()=>{}),this.messaging||r.get().then(i=>this.messaging=i,()=>{}),this.appCheck||s?.get().then(i=>this.appCheck=i,()=>{})}async getAuthToken(){if(this.auth)try{return(await this.auth.getToken())?.accessToken}catch{return}}async getMessagingToken(){if(!(!this.messaging||!("Notification"in self)||Notification.permission!=="granted"))try{return await this.messaging.getToken()}catch{return}}async getAppCheckToken(e){if(this.serverAppAppCheckToken)return this.serverAppAppCheckToken;if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){const t=await this.getAuthToken(),r=await this.getMessagingToken(),s=await this.getAppCheckToken(e);return{authToken:t,messagingToken:r,appCheckToken:s}}}const Ba="us-central1",Ov=/^data: (.*?)(?:\n|$)/;function Vv(n){let e=null;return{promise:new Promise((t,r)=>{e=setTimeout(()=>{r(new Le("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{e&&clearTimeout(e)}}}class Lv{constructor(e,t,r,s,i=Ba,a=(...c)=>fetch(...c)){this.app=e,this.fetchImpl=a,this.emulatorOrigin=null,this.contextProvider=new Dv(e,t,r,s),this.cancelAllRequests=new Promise(c=>{this.deleteService=()=>Promise.resolve(c())});try{const c=new URL(i);this.customDomain=c.origin+(c.pathname==="/"?"":c.pathname),this.region=Ba}catch{this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;return this.emulatorOrigin!==null?`${this.emulatorOrigin}/${t}/${this.region}/${e}`:this.customDomain!==null?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function Mv(n,e,t){const r=tt(e);n.emulatorOrigin=`http${r?"s":""}://${e}:${t}`,r&&(ls(n.emulatorOrigin+"/backends"),hs("Functions",!0))}function xv(n,e,t){const r=s=>Fv(n,e,s,{});return r.stream=(s,i)=>qv(n,e,s,i),r}function sf(n){return n.emulatorOrigin&&tt(n.emulatorOrigin)?"include":void 0}async function Uv(n,e,t,r,s){t["Content-Type"]="application/json";let i;try{i=await r(n,{method:"POST",body:JSON.stringify(e),headers:t,credentials:sf(s)})}catch{return{status:0,json:null}}let a=null;try{a=await i.json()}catch{}return{status:i.status,json:a}}async function of(n,e){const t={},r=await n.contextProvider.getContext(e.limitedUseAppCheckTokens);return r.authToken&&(t.Authorization="Bearer "+r.authToken),r.messagingToken&&(t["Firebase-Instance-ID-Token"]=r.messagingToken),r.appCheckToken!==null&&(t["X-Firebase-AppCheck"]=r.appCheckToken),t}function Fv(n,e,t,r){const s=n._url(e);return Bv(n,s,t,r)}async function Bv(n,e,t,r){t=Ri(t);const s={data:t},i=await of(n,r),a=r.timeout||7e4,c=Vv(a),l=await Promise.race([Uv(e,s,i,n.fetchImpl,n),c.promise,n.cancelAllRequests]);if(c.cancel(),!l)throw new Le("cancelled","Firebase Functions instance was deleted.");const d=bi(l.status,l.json);if(d)throw d;if(!l.json)throw new Le("internal","Response is not valid JSON object.");let f=l.json.data;if(typeof f>"u"&&(f=l.json.result),typeof f>"u")throw new Le("internal","Response is missing data field.");return{data:er(f)}}function qv(n,e,t,r){const s=n._url(e);return jv(n,s,t,r||{})}async function jv(n,e,t,r){t=Ri(t);const s={data:t},i=await of(n,r);i["Content-Type"]="application/json",i.Accept="text/event-stream";let a;try{a=await n.fetchImpl(e,{method:"POST",body:JSON.stringify(s),headers:i,signal:r?.signal,credentials:sf(n)})}catch(g){if(g instanceof Error&&g.name==="AbortError"){const C=new Le("cancelled","Request was cancelled.");return{data:Promise.reject(C),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(C)}}}}}}const R=bi(0,null);return{data:Promise.reject(R),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(R)}}}}}}let c,l;const d=new Promise((g,R)=>{c=g,l=R});r?.signal?.addEventListener("abort",()=>{const g=new Le("cancelled","Request was cancelled.");l(g)});const f=a.body.getReader(),m=$v(f,c,l,r?.signal);return{stream:{[Symbol.asyncIterator](){const g=m.getReader();return{async next(){const{value:R,done:C}=await g.read();return{value:R,done:C}},async return(){return await g.cancel(),{done:!0,value:void 0}}}}},data:d}}function $v(n,e,t,r){const s=(a,c)=>{const l=a.match(Ov);if(!l)return;const d=l[1];try{const f=JSON.parse(d);if("result"in f){e(er(f.result));return}if("message"in f){c.enqueue(er(f.message));return}if("error"in f){const m=bi(0,f);c.error(m),t(m);return}}catch(f){if(f instanceof Le){c.error(f),t(f);return}}},i=new TextDecoder;return new ReadableStream({start(a){let c="";return l();async function l(){if(r?.aborted){const d=new Le("cancelled","Request was cancelled");return a.error(d),t(d),Promise.resolve()}try{const{value:d,done:f}=await n.read();if(f){c.trim()&&s(c.trim(),a),a.close();return}if(r?.aborted){const g=new Le("cancelled","Request was cancelled");a.error(g),t(g),await n.cancel();return}c+=i.decode(d,{stream:!0});const m=c.split(`
52
- `);c=m.pop()||"";for(const g of m)g.trim()&&s(g.trim(),a);return l()}catch(d){const f=d instanceof Le?d:bi(0,null);a.error(f),t(f)}}},cancel(){return n.cancel()}})}const af="@firebase/functions",cf="0.13.1";const zv="auth-internal",Hv="app-check-internal",Wv="messaging-internal";function Gv(n){const e=(t,{instanceIdentifier:r})=>{const s=t.getProvider("app").getImmediate(),i=t.getProvider(zv),a=t.getProvider(Wv),c=t.getProvider(Hv);return new Lv(s,i,a,c,r)};St(new _t(Fa,e,"PUBLIC").setMultipleInstances(!0)),je(af,cf,n),je(af,cf,"esm2020")}function Kv(n=fs(),e=Ba){const r=dr(Q(n),Fa).getImmediate({identifier:e}),s=ji("functions");return s&&uf(r,...s),r}function uf(n,e,t){Mv(Q(n),e,t)}function Qv(n,e,t){return xv(Q(n),e)}Gv();const et=class et{static setFirebaseConfig(e){et._firebaseConfig=e}static useEmulator(e){this._emulatorConfig={...et.defaultEmulatorConfig,emulate:!0,...e}}static get emulator(){return this._emulatorConfig}constructor(){if(!et._firebaseConfig)throw new Error("You should set a firebase config object before using Firebase");this._firebaseApp=Sc(et._firebaseConfig)}static get instance(){return this._instance||(this._instance=new et)}firestore(){return rE(this._firebaseApp)}storage(){return bv(this._firebaseApp)}auth(){return hI(this._firebaseApp)}functions(){return Kv(this._firebaseApp,et._region)}static setRegion(e){this._region=e}};et.defaultEmulatorConfig={host:"localhost",firestorePort:8080,storagePort:9199,authPort:9099,functionsPort:5001,emulate:!1},et._emulatorConfig=et.defaultEmulatorConfig;let q=et;class Yv extends $t{constructor(e){if(super(),this._lastLimit=0,e&&q.useEmulator(e),q.emulator?.emulate){const{host:t,firestorePort:r}=q.emulator;zl(q.instance.firestore(),t,r)}}findById(e,t){const r=q.instance.firestore();return new Promise(async s=>{try{const i=await PE(Xs(r,t,e));s(i.data())}catch(i){return console.log(i),null}})}save(e){const t=q.instance.firestore(),r=kE(t);return Object.entries(e).forEach(([s,i])=>{i?.forEach(a=>{const c=Xs(t,s,a.id);r.set(c,a)})}),r.commit()}find(e,t){const r=this.queryObjectToQueryConstraints(e,t);return this.getFromQuery(r)}async count(e,t){const r=this.queryObjectToQueryConstraints(e,t);return(await vE(r)).data().count}delete(e,t){const r=q.instance.firestore();return CE(Xs(r,t,e))}next(e){if(!this._lastConstraints||!this._lastCollectionName)throw new Error("You should perform a query prior to using method next");const t=q.instance.firestore();this._lastLimit=e||this._lastLimit;const r=this._lastConstraints.nonFilterConstraints.concat(ch(this._lastLimit),EE(this._lastDocRetrieved));return this.getFromQuery(oh(Hl(t,this._lastCollectionName),...r))}onCollectionChange(e,t,r){const s=this.queryObjectToQueryConstraints(e,t);return fh(s,i=>{const a=i.docChanges().map(c=>({after:c.doc.data(),type:c.type==="added"?"create":c.type==="removed"?"delete":"update",before:void 0,params:{}}));r(a)})}onDocumentChange(e,t,r){const s=q.instance.firestore();return fh(Xs(s,e,t),i=>{r({type:"update",before:void 0,after:i.data(),params:{}})})}queryObjectToQueryConstraints(e,t){const r=q.instance.firestore(),s=[],i=[],a=[];return $t.toPropertyPathOperations(e.operations).forEach(c=>{const l=this.toFirebaseOperator(c.operator);c.aggregate?i.push(ah(c.property,l,c.value)):s.push(ah(c.property,l,c.value))}),e.sort?.propertyName&&a.push(yE(e.sort.propertyName,e.sort.order)),this._lastConstraints={orConstraints:i,andConstraints:s,nonFilterConstraints:a},this._lastCollectionName=t,e.limit&&(this._lastLimit=e.limit,a.push(ch(e.limit))),oh(Hl(r,t),gE(...i,_E(...s)),...a)}toFirebaseOperator(e){switch(e){case"==":case"!=":case"<":case"<=":case">":case">=":return e;case"contains":return"array-contains";case"containsAny":return"array-contains-any";default:return e}}getFromQuery(e){return new Promise(async t=>{const r=await SE(e);this._lastDocRetrieved=r.docs[r.docs.length-1],t(r.docs.map(s=>s.data()))})}subscribeToDocumentChangeListener(e,t){throw new Error("Method not implemented.")}collectionsMatchingTemplate(e){throw new Error("Method not implemented.")}}var Jv=Object.getOwnPropertyDescriptor,Xv=(n,e,t,r)=>{for(var s=r>1?void 0:r?Jv(e,t):e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(s)||s);return s};Ue.FirebaseCloudStorage=class extends Hn{constructor(e){if(super(),e&&q.useEmulator(e),q.emulator?.emulate){const{host:t,storagePort:r}=q.emulator;tf(q.instance.storage(),t,r)}}save(e,t,r){const s=q.instance.storage();return new Promise((i,a)=>{if(this._uploadTask=vv(Ua(s,e),t),r)var c=this._uploadTask.on("state_changed",l=>{r(l.bytesTransferred,l.totalBytes)},null,()=>c());this._uploadTask.then(()=>i(e)).catch(l=>a(l))})}getUrl(e){if(!e)return Promise.reject("needs a reference");const t=q.instance.storage();return Av(Ua(t,e))}uploadControl(){if(!this._uploadTask)throw new Error("You should call save() before uploadControl()");return{cancel:()=>this._uploadTask?.cancel(),pause:()=>this._uploadTask?.pause(),resume:()=>this._uploadTask?.resume(),onProgress:e=>this._uploadTask?.on("state_changed",t=>{e&&e(t.bytesTransferred,t.totalBytes)})}}delete(e){const t=q.instance.storage();return Rv(Ua(t,e))}},Ue.FirebaseCloudStorage=Xv([Ih("FirebaseCloudStorage",()=>new Ue.FirebaseCloudStorage)],Ue.FirebaseCloudStorage);const lf={twitter:()=>new Ze,facebook:()=>new ht,google:()=>new dt};class qa extends vh{constructor(e){if(super(),this.credentialProviders={},e&&q.useEmulator(e),q.emulator?.emulate){const{host:t,authPort:r}=q.emulator;if(!t||!r)throw new Error("You should define a host and an auth emulator port to use the emulator");Xh(q.instance.auth(),`http://${t}:${r}`)}this.registerCredentialProviders()}signUp(e){const{authProvider:t,verificationLink:r}=e;return t.slice(0,5)==="email"?new Promise(async(s,i)=>{try{const a=this.credentialProviders["email-sign-up"];if(!a)throw new Error(`The provider ${t} is not registered`);const c=await a(e);e.name&&await ZT(c.user,{displayName:e.name}),r&&await ud(c.user,{url:r}),s(await this.toUserCredentials(c.user))}catch(a){i({code:ii(a.code.slice(5)),message:a.message})}}):this.login(e)}login(e){const{authProvider:t}=e;return new Promise(async(r,s)=>{try{const i=this.credentialProviders[t];if(!i)throw new Error(`The provider ${t} is not registered`);const a=await i(e);r(await this.toUserCredentials(a.user))}catch(i){s({code:i.code===400?"missingPassword":ii(i.code.slice(5)),message:i.message})}})}logout(){return q.instance.auth().signOut()}resetEmailPassword(e){return new Promise(async(t,r)=>{try{await YT(q.instance.auth(),e),t()}catch(s){r({code:ii(s.code.slice(5)),message:s.message})}})}resendVerificationEmail(e,t,r){return new Promise(async(s,i)=>{try{await cd(q.instance.auth(),e,t);const a=q.instance.auth().currentUser;if(!a){i({code:"userNotFound",message:"There is no logged in user"});return}await ud(a,{url:r}),s()}catch(a){i({code:ii(a.code.slice(5)),message:r})}})}refreshToken(){return q.instance.auth().currentUser?.getIdToken(!0)}onAuthStateChange(e){q.instance.auth().onAuthStateChanged(async t=>{e(t?await this.toUserCredentials(t):void 0)})}linkAdditionalProvider(e){const t=lf[e](),r=q.instance.auth().currentUser;if(!r)throw new Error("There is no logged in user");return wd(r,t)}unlinkProvider(e){const{currentUser:t}=q.instance.auth();if(!t)throw new Error("There is no logged in user");return t.providerData,zT(t,lf[e]().providerId)}async toUserCredentials(e){if(!e)throw new Error("The user in user credentials is not defined");const t=(await e.getIdTokenResult()).claims;return qa.convertCredentials(e,t)}static convertCredentials(e,t){return{id:e.uid,email:e.email??"",name:e.displayName??void 0,pictureUrl:e.photoURL??void 0,phoneNumber:e.phoneNumber??void 0,emailVerified:e.emailVerified,customData:{...t},lastLogin:Date.now(),creationDate:e.metadata.creationTime?new Date(e.metadata.creationTime).getTime():void 0}}registerCredentialProvider(e,t){this.credentialProviders[e]=t}registerCredentialProviders(){this.registerCredentialProvider("email-sign-up",e=>{if(!e.email||!e.password)throw new Error("Email and password are required");return JT(q.instance.auth(),e.email,e.password)}),this.registerCredentialProvider("email",e=>{if(!e.email||!e.password)throw new Error("Email and password are required");return cd(q.instance.auth(),e.email,e.password)}),this.registerCredentialProvider("google",()=>ba(q.instance.auth(),new dt)),this.registerCredentialProvider("facebook",()=>ba(q.instance.auth(),new ht)),this.registerCredentialProvider("twitter",()=>ba(q.instance.auth(),new Ze)),this.registerCredentialProvider("link-twitter",()=>{const e=q.instance.auth().currentUser;if(!e)throw new Error("There is no logged in user");return wd(e,new Ze)}),this.registerCredentialProvider("anonymous",()=>$T(q.instance.auth()))}}class Zv{constructor(e,t){if(e&&q.setRegion(e),t&&q.useEmulator(t),q.emulator?.emulate){const{host:r,functionsPort:s}=q.emulator;uf(q.instance.functions(),r,s)}}retrieveFunction(e){return Qv(q.instance.functions(),e)}async callFunction(e,t){return(await e(t)).data}}Ue.FirebaseAuth=qa,Ue.FirebaseCloudFunctions=Zv,Ue.FirebaseDatasource=Yv,Ue.FirebaseHelper=q,Object.defineProperty(Ue,Symbol.toStringTag,{value:"Module"})});
50
+ `,_=`\r
51
+ --`+l+"--",R=Gt.getBlob(m,r,_);if(R===null)throw Vd();const S={name:d.fullPath},N=Xn(i,n.host,n._protocol),k="POST",U=n.maxUploadRetryTime,$=new _n(N,k,Oa(n,t),U);return $.urlParams=S,$.headers=a,$.body=R.uploadData(),$.errorHandler=Hr(e),$}class Ai{constructor(e,t,r,s){this.current=e,this.total=t,this.finalized=!!r,this.metadata=s||null}}function La(n,e){let t=null;try{t=n.getResponseHeader("X-Goog-Upload-Status")}catch{bt(!1)}return bt(!!t&&(e||["active"]).indexOf(t)!==-1),t}function cv(n,e,t,r,s){const i=e.bucketOnlyServerUrl(),a=Kd(e,r,s),c={name:a.fullPath},l=Xn(i,n.host,n._protocol),d="POST",f={"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"},m=Gd(a,t),_=n.maxUploadRetryTime;function R(N){La(N);let k;try{k=N.getResponseHeader("X-Goog-Upload-URL")}catch{bt(!1)}return bt(wi(k)),k}const S=new _n(l,d,R,_);return S.urlParams=c,S.headers=f,S.body=m,S.errorHandler=Hr(e),S}function uv(n,e,t,r){const s={"X-Goog-Upload-Command":"query"};function i(d){const f=La(d,["active","final"]);let m=null;try{m=d.getResponseHeader("X-Goog-Upload-Size-Received")}catch{bt(!1)}m||bt(!1);const _=Number(m);return bt(!isNaN(_)),new Ai(_,r.size(),f==="final")}const a="POST",c=n.maxUploadRetryTime,l=new _n(t,a,i,c);return l.headers=s,l.errorHandler=Hr(e),l}const Qd=256*1024;function lv(n,e,t,r,s,i,a,c){const l=new Ai(0,0);if(a?(l.current=a.current,l.total=a.total):(l.current=0,l.total=r.size()),r.size()!==l.total)throw AI();const d=l.total-l.current;let f=d;s>0&&(f=Math.min(f,s));const m=l.current,_=m+f;let R="";f===0?R="finalize":d===f?R="upload, finalize":R="upload";const S={"X-Goog-Upload-Command":R,"X-Goog-Upload-Offset":`${l.current}`},N=r.slice(m,_);if(N===null)throw Vd();function k(Q,_e){const re=La(Q,["active","final"]),w=l.current+f,g=r.size();let E;return re==="final"?E=Oa(e,i)(Q,_e):E=null,new Ai(w,g,re==="final",E)}const U="POST",$=e.maxUploadRetryTime,j=new _n(t,U,k,$);return j.headers=S,j.body=N.uploadData(),j.progressCallback=c||null,j.errorHandler=Hr(n),j}const Ve={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Ma(n){switch(n){case"running":case"pausing":case"canceling":return Ve.RUNNING;case"paused":return Ve.PAUSED;case"success":return Ve.SUCCESS;case"canceled":return Ve.CANCELED;case"error":return Ve.ERROR;default:return Ve.ERROR}}class hv{constructor(e,t,r){if(DI(e)||t!=null||r!=null)this.next=e,this.error=t??void 0,this.complete=r??void 0;else{const i=e;this.next=i.next,this.error=i.error,this.complete=i.complete}}}function Zn(n){return(...e)=>{Promise.resolve().then(()=>n(...e))}}class dv{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=gn.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=gn.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=gn.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,r,s,i){if(this.sent_)throw zr("cannot .send() more than once");if(tt(e)&&r&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(t,e,!0),i!==void 0)for(const a in i)i.hasOwnProperty(a)&&this.xhr_.setRequestHeader(a,i[a].toString());return s!==void 0?this.xhr_.send(s):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw zr("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw zr("cannot .getStatus() before sending");try{return this.xhr_.status}catch{return-1}}getResponse(){if(!this.sent_)throw zr("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw zr("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.removeEventListener("progress",e)}}class fv extends dv{initXhr(){this.xhr_.responseType="text"}}function yn(){return new fv}class pv{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,t,r=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=r,this._mappings=Hd(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=s=>{if(this._request=void 0,this._chunkMultiplier=1,s._codeEquals(te.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const i=this.isExponentialBackoffExpired();if(Fd(s.status,[]))if(i)s=Dd();else{this.sleepTime=Math.max(this.sleepTime*2,mI),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=s,this._transition("error")}},this._metadataErrorHandler=s=>{this._request=void 0,s._codeEquals(te.CANCELED)?this.completeTransitions_():(this._error=s,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((s,i)=>{this._resolve=s,this._reject=i,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>256*1024}_start(){this._state==="running"&&this._request===void 0&&(this._resumable?this._uploadUrl===void 0?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([t,r])=>{switch(this._state){case"running":e(t,r);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((e,t)=>{const r=cv(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),s=this._ref.storage._makeRequest(r,yn,e,t);this._request=s,s.getPromise().then(i=>{this._request=void 0,this._uploadUrl=i,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const e=this._uploadUrl;this._resolveToken((t,r)=>{const s=uv(this._ref.storage,this._ref._location,e,this._blob),i=this._ref.storage._makeRequest(s,yn,t,r);this._request=i,i.getPromise().then(a=>{a=a,this._request=void 0,this._updateProgress(a.current),this._needToFetchStatus=!1,a.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const e=Qd*this._chunkMultiplier,t=new Ai(this._transferred,this._blob.size()),r=this._uploadUrl;this._resolveToken((s,i)=>{let a;try{a=lv(this._ref._location,this._ref.storage,r,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(l){this._error=l,this._transition("error");return}const c=this._ref.storage._makeRequest(a,yn,s,i,!1);this._request=c,c.getPromise().then(l=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(l.current),l.finalized?(this._metadata=l.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){Qd*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{const r=rv(this._ref.storage,this._ref._location,this._mappings),s=this._ref.storage._makeRequest(r,yn,e,t);this._request=s,s.getPromise().then(i=>{this._request=void 0,this._metadata=i,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{const r=av(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),s=this._ref.storage._makeRequest(r,yn,e,t);this._request=s,s.getPromise().then(i=>{this._request=void 0,this._metadata=i,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){const 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,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t=this._state==="paused";this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Od(),this._state=e,this._notifyObservers();break;case"error":this._state=e,this._notifyObservers();break;case"success":this._state=e,this._notifyObservers();break}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start();break}}get snapshot(){const e=Ma(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,r,s){const i=new hv(t||void 0,r||void 0,s||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){const t=this._observers.indexOf(e);t!==-1&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(t=>{this._notifyObserver(t)})}_finishPromise(){if(this._resolve!==void 0){let e=!0;switch(Ma(this._state)){case Ve.SUCCESS:Zn(this._resolve.bind(null,this.snapshot))();break;case Ve.CANCELED:case Ve.ERROR:const t=this._reject;Zn(t.bind(null,this._error))();break;default:e=!1;break}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Ma(this._state)){case Ve.RUNNING:case Ve.PAUSED:e.next&&Zn(e.next.bind(e,this.snapshot))();break;case Ve.SUCCESS:e.complete&&Zn(e.complete.bind(e))();break;case Ve.CANCELED:case Ve.ERROR:e.error&&Zn(e.error.bind(e,this._error))();break;default:e.error&&Zn(e.error.bind(e,this._error))()}}resume(){const e=this._state==="paused"||this._state==="pausing";return e&&this._transition("running"),e}pause(){const e=this._state==="running";return e&&this._transition("pausing"),e}cancel(){const e=this._state==="running"||this._state==="pausing";return e&&this._transition("canceling"),e}}class En{constructor(e,t){this._service=e,t instanceof Be?this._location=t:this._location=Be.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new En(e,t)}get root(){const e=new Be(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return zd(this._location.path)}get storage(){return this._service}get parent(){const e=QI(this._location.path);if(e===null)return null;const t=new Be(this._location.bucket,e);return new En(this._service,t)}_throwIfRoot(e){if(this._location.path==="")throw PI(e)}}function mv(n,e,t){return n._throwIfRoot("uploadBytesResumable"),new pv(n,new Gt(e),t)}function gv(n){n._throwIfRoot("getDownloadURL");const e=sv(n.storage,n._location,Hd());return n.storage.makeRequestWithTokens(e,yn).then(t=>{if(t===null)throw RI();return t})}function _v(n){n._throwIfRoot("deleteObject");const e=iv(n.storage,n._location);return n.storage.makeRequestWithTokens(e,yn)}function yv(n,e){const t=YI(n._location.path,e),r=new Be(n._location.bucket,t);return new En(n.storage,r)}function Ev(n){return/^[A-Za-z]+:\/\//.test(n)}function Tv(n,e){return new En(n,e)}function Yd(n,e){if(n instanceof xa){const t=n;if(t._bucket==null)throw vI();const r=new En(t,t._bucket);return e!=null?Yd(r,e):r}else return e!==void 0?yv(n,e):n}function wv(n,e){if(e&&Ev(e)){if(n instanceof xa)return Tv(n,e);throw ka("To use ref(service, url), the first argument must be a Storage instance.")}else return Yd(n,e)}function Jd(n,e){const t=e?.[Nd];return t==null?null:Be.makeFromBucketSpec(t,n)}function Iv(n,e,t,r={}){n.host=`${e}:${t}`;const s=tt(e);s&&(ls(`https://${n.host}/b`),hs("Storage",!0)),n._isUsingEmulator=!0,n._protocol=s?"https":"http";const{mockUserToken:i}=r;i&&(n._overrideAuthToken=typeof i=="string"?i:yc(i,n.app.options.projectId))}class xa{constructor(e,t,r,s,i,a=!1){this.app=e,this._authProvider=t,this._appCheckProvider=r,this._url=s,this._firebaseVersion=i,this._isUsingEmulator=a,this._bucket=null,this._host=kd,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=fI,this._maxUploadRetryTime=pI,this._requests=new Set,s!=null?this._bucket=Be.makeFromBucketSpec(s,this._host):this._bucket=Jd(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,this._url!=null?this._bucket=Be.makeFromBucketSpec(this._url,e):this._bucket=Jd(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){xd("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){xd("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){const t=await e.getToken();if(t!==null)return t.accessToken}return null}async _getAppCheckToken(){if(Ae(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;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 En(this,e)}_makeRequest(e,t,r,s,i=!0){if(this._deleted)return new CI(Ld());{const a=FI(e,this._appId,r,s,t,this._firebaseVersion,i,this._isUsingEmulator);return this._requests.add(a),a.getPromise().then(()=>this._requests.delete(a),()=>this._requests.delete(a)),a}}async makeRequestWithTokens(e,t){const[r,s]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,r,s).getPromise()}}const Xd="@firebase/storage",Zd="0.14.1";const ef="storage";function vv(n,e,t){return n=Y(n),mv(n,e,t)}function Av(n){return n=Y(n),gv(n)}function Rv(n){return n=Y(n),_v(n)}function Ua(n,e){return n=Y(n),wv(n,e)}function bv(n=fs(),e){n=Y(n);const r=dr(n,ef).getImmediate({identifier:e}),s=ji("storage");return s&&tf(r,...s),r}function tf(n,e,t,r={}){Iv(n,e,t,r)}function Pv(n,{instanceIdentifier:e}){const t=n.getProvider("app").getImmediate(),r=n.getProvider("auth-internal"),s=n.getProvider("app-check-internal");return new xa(t,r,s,e,nn)}function Cv(){Ct(new _t(ef,Pv,"PUBLIC").setMultipleInstances(!0)),je(Xd,Zd,""),je(Xd,Zd,"esm2020")}Cv();const Sv="type.googleapis.com/google.protobuf.Int64Value",kv="type.googleapis.com/google.protobuf.UInt64Value";function nf(n,e){const t={};for(const r in n)n.hasOwnProperty(r)&&(t[r]=e(n[r]));return t}function Ri(n){if(n==null)return null;if(n instanceof Number&&(n=n.valueOf()),typeof n=="number"&&isFinite(n)||n===!0||n===!1||Object.prototype.toString.call(n)==="[object String]")return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(e=>Ri(e));if(typeof n=="function"||typeof n=="object")return nf(n,e=>Ri(e));throw new Error("Data cannot be encoded in JSON: "+n)}function er(n){if(n==null)return n;if(n["@type"])switch(n["@type"]){case Sv:case kv:{const e=Number(n.value);if(isNaN(e))throw new Error("Data cannot be decoded from JSON: "+n);return e}default:throw new Error("Data cannot be decoded from JSON: "+n)}return Array.isArray(n)?n.map(e=>er(e)):typeof n=="function"||typeof n=="object"?nf(n,e=>er(e)):n}const Fa="functions";const rf={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 Le extends We{constructor(e,t,r){super(`${Fa}/${e}`,t||""),this.details=r,Object.setPrototypeOf(this,Le.prototype)}}function Nv(n){if(n>=200&&n<300)return"ok";switch(n){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"}function bi(n,e){let t=Nv(n),r=t,s;try{const i=e&&e.error;if(i){const a=i.status;if(typeof a=="string"){if(!rf[a])return new Le("internal","internal");t=rf[a],r=a}const c=i.message;typeof c=="string"&&(r=c),s=i.details,s!==void 0&&(s=er(s))}}catch{}return t==="ok"?null:new Le(t,r,s)}class Dv{constructor(e,t,r,s){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,Ae(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=t.getImmediate({optional:!0}),this.messaging=r.getImmediate({optional:!0}),this.auth||t.get().then(i=>this.auth=i,()=>{}),this.messaging||r.get().then(i=>this.messaging=i,()=>{}),this.appCheck||s?.get().then(i=>this.appCheck=i,()=>{})}async getAuthToken(){if(this.auth)try{return(await this.auth.getToken())?.accessToken}catch{return}}async getMessagingToken(){if(!(!this.messaging||!("Notification"in self)||Notification.permission!=="granted"))try{return await this.messaging.getToken()}catch{return}}async getAppCheckToken(e){if(this.serverAppAppCheckToken)return this.serverAppAppCheckToken;if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){const t=await this.getAuthToken(),r=await this.getMessagingToken(),s=await this.getAppCheckToken(e);return{authToken:t,messagingToken:r,appCheckToken:s}}}const Ba="us-central1",Ov=/^data: (.*?)(?:\n|$)/;function Vv(n){let e=null;return{promise:new Promise((t,r)=>{e=setTimeout(()=>{r(new Le("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{e&&clearTimeout(e)}}}class Lv{constructor(e,t,r,s,i=Ba,a=(...c)=>fetch(...c)){this.app=e,this.fetchImpl=a,this.emulatorOrigin=null,this.contextProvider=new Dv(e,t,r,s),this.cancelAllRequests=new Promise(c=>{this.deleteService=()=>Promise.resolve(c())});try{const c=new URL(i);this.customDomain=c.origin+(c.pathname==="/"?"":c.pathname),this.region=Ba}catch{this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;return this.emulatorOrigin!==null?`${this.emulatorOrigin}/${t}/${this.region}/${e}`:this.customDomain!==null?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function Mv(n,e,t){const r=tt(e);n.emulatorOrigin=`http${r?"s":""}://${e}:${t}`,r&&(ls(n.emulatorOrigin+"/backends"),hs("Functions",!0))}function xv(n,e,t){const r=s=>Fv(n,e,s,{});return r.stream=(s,i)=>qv(n,e,s,i),r}function sf(n){return n.emulatorOrigin&&tt(n.emulatorOrigin)?"include":void 0}async function Uv(n,e,t,r,s){t["Content-Type"]="application/json";let i;try{i=await r(n,{method:"POST",body:JSON.stringify(e),headers:t,credentials:sf(s)})}catch{return{status:0,json:null}}let a=null;try{a=await i.json()}catch{}return{status:i.status,json:a}}async function of(n,e){const t={},r=await n.contextProvider.getContext(e.limitedUseAppCheckTokens);return r.authToken&&(t.Authorization="Bearer "+r.authToken),r.messagingToken&&(t["Firebase-Instance-ID-Token"]=r.messagingToken),r.appCheckToken!==null&&(t["X-Firebase-AppCheck"]=r.appCheckToken),t}function Fv(n,e,t,r){const s=n._url(e);return Bv(n,s,t,r)}async function Bv(n,e,t,r){t=Ri(t);const s={data:t},i=await of(n,r),a=r.timeout||7e4,c=Vv(a),l=await Promise.race([Uv(e,s,i,n.fetchImpl,n),c.promise,n.cancelAllRequests]);if(c.cancel(),!l)throw new Le("cancelled","Firebase Functions instance was deleted.");const d=bi(l.status,l.json);if(d)throw d;if(!l.json)throw new Le("internal","Response is not valid JSON object.");let f=l.json.data;if(typeof f>"u"&&(f=l.json.result),typeof f>"u")throw new Le("internal","Response is missing data field.");return{data:er(f)}}function qv(n,e,t,r){const s=n._url(e);return jv(n,s,t,r||{})}async function jv(n,e,t,r){t=Ri(t);const s={data:t},i=await of(n,r);i["Content-Type"]="application/json",i.Accept="text/event-stream";let a;try{a=await n.fetchImpl(e,{method:"POST",body:JSON.stringify(s),headers:i,signal:r?.signal,credentials:sf(n)})}catch(_){if(_ instanceof Error&&_.name==="AbortError"){const S=new Le("cancelled","Request was cancelled.");return{data:Promise.reject(S),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(S)}}}}}}const R=bi(0,null);return{data:Promise.reject(R),stream:{[Symbol.asyncIterator](){return{next(){return Promise.reject(R)}}}}}}let c,l;const d=new Promise((_,R)=>{c=_,l=R});r?.signal?.addEventListener("abort",()=>{const _=new Le("cancelled","Request was cancelled.");l(_)});const f=a.body.getReader(),m=$v(f,c,l,r?.signal);return{stream:{[Symbol.asyncIterator](){const _=m.getReader();return{async next(){const{value:R,done:S}=await _.read();return{value:R,done:S}},async return(){return await _.cancel(),{done:!0,value:void 0}}}}},data:d}}function $v(n,e,t,r){const s=(a,c)=>{const l=a.match(Ov);if(!l)return;const d=l[1];try{const f=JSON.parse(d);if("result"in f){e(er(f.result));return}if("message"in f){c.enqueue(er(f.message));return}if("error"in f){const m=bi(0,f);c.error(m),t(m);return}}catch(f){if(f instanceof Le){c.error(f),t(f);return}}},i=new TextDecoder;return new ReadableStream({start(a){let c="";return l();async function l(){if(r?.aborted){const d=new Le("cancelled","Request was cancelled");return a.error(d),t(d),Promise.resolve()}try{const{value:d,done:f}=await n.read();if(f){c.trim()&&s(c.trim(),a),a.close();return}if(r?.aborted){const _=new Le("cancelled","Request was cancelled");a.error(_),t(_),await n.cancel();return}c+=i.decode(d,{stream:!0});const m=c.split(`
52
+ `);c=m.pop()||"";for(const _ of m)_.trim()&&s(_.trim(),a);return l()}catch(d){const f=d instanceof Le?d:bi(0,null);a.error(f),t(f)}}},cancel(){return n.cancel()}})}const af="@firebase/functions",cf="0.13.2";const zv="auth-internal",Hv="app-check-internal",Wv="messaging-internal";function Gv(n){const e=(t,{instanceIdentifier:r})=>{const s=t.getProvider("app").getImmediate(),i=t.getProvider(zv),a=t.getProvider(Wv),c=t.getProvider(Hv);return new Lv(s,i,a,c,r)};Ct(new _t(Fa,e,"PUBLIC").setMultipleInstances(!0)),je(af,cf,n),je(af,cf,"esm2020")}function Kv(n=fs(),e=Ba){const r=dr(Y(n),Fa).getImmediate({identifier:e}),s=ji("functions");return s&&uf(r,...s),r}function uf(n,e,t){Mv(Y(n),e,t)}function Qv(n,e,t){return xv(Y(n),e)}Gv();const et=class et{static setFirebaseConfig(e){et._firebaseConfig=e}static useEmulator(e){this._emulatorConfig={...et.defaultEmulatorConfig,emulate:!0,...e}}static get emulator(){return this._emulatorConfig}constructor(){if(!et._firebaseConfig)throw new Error("You should set a firebase config object before using Firebase");this._firebaseApp=Cc(et._firebaseConfig)}static get instance(){return this._instance||(this._instance=new et)}firestore(){return rE(this._firebaseApp)}storage(){return bv(this._firebaseApp)}auth(){return hI(this._firebaseApp)}functions(){return Kv(this._firebaseApp,et._region)}static setRegion(e){this._region=e}};et.defaultEmulatorConfig={host:"localhost",firestorePort:8080,storagePort:9199,authPort:9099,functionsPort:5001,emulate:!1},et._emulatorConfig=et.defaultEmulatorConfig;let q=et;class Yv extends $t{constructor(e){if(super(),this._lastLimit=0,e&&q.useEmulator(e),q.emulator?.emulate){const{host:t,firestorePort:r}=q.emulator;zl(q.instance.firestore(),t,r)}}findById(e,t){const r=q.instance.firestore();return new Promise(async s=>{try{const i=await PE(Xs(r,t,e));s(i.data())}catch(i){return console.log(i),null}})}save(e){const t=q.instance.firestore(),r=kE(t);return Object.entries(e).forEach(([s,i])=>{i?.forEach(a=>{const c=Xs(t,s,a.id);r.set(c,a)})}),r.commit()}find(e,t){const r=this.queryObjectToQueryConstraints(e,t);return this.getFromQuery(r)}async count(e,t){const r=this.queryObjectToQueryConstraints(e,t);return(await vE(r)).data().count}delete(e,t){const r=q.instance.firestore();return SE(Xs(r,t,e))}next(e){if(!this._lastConstraints||!this._lastCollectionName)throw new Error("You should perform a query prior to using method next");const t=q.instance.firestore();this._lastLimit=e||this._lastLimit;const r=this._lastConstraints.nonFilterConstraints.concat(ch(this._lastLimit),EE(this._lastDocRetrieved));return this.getFromQuery(oh(Hl(t,this._lastCollectionName),...r))}onCollectionChange(e,t,r){const s=this.queryObjectToQueryConstraints(e,t);return fh(s,i=>{const a=i.docChanges().map(c=>({after:c.doc.data(),type:c.type==="added"?"create":c.type==="removed"?"delete":"update",before:void 0,params:{}}));r(a)})}onDocumentChange(e,t,r){const s=q.instance.firestore();return fh(Xs(s,e,t),i=>{r({type:"update",before:void 0,after:i.data(),params:{}})})}queryObjectToQueryConstraints(e,t){const r=q.instance.firestore(),s=[],i=[],a=[];return $t.toPropertyPathOperations(e.operations).forEach(c=>{const l=this.toFirebaseOperator(c.operator);c.aggregate?i.push(ah(c.property,l,c.value)):s.push(ah(c.property,l,c.value))}),e.sort?.propertyName&&a.push(yE(e.sort.propertyName,e.sort.order)),this._lastConstraints={orConstraints:i,andConstraints:s,nonFilterConstraints:a},this._lastCollectionName=t,e.limit&&(this._lastLimit=e.limit,a.push(ch(e.limit))),oh(Hl(r,t),gE(...i,_E(...s)),...a)}toFirebaseOperator(e){switch(e){case"==":case"!=":case"<":case"<=":case">":case">=":return e;case"contains":return"array-contains";case"containsAny":return"array-contains-any";default:return e}}getFromQuery(e){return new Promise(async t=>{const r=await CE(e);this._lastDocRetrieved=r.docs[r.docs.length-1],t(r.docs.map(s=>s.data()))})}resolveCollectionPaths(e){throw new Error("Method not implemented.")}}var Jv=Object.getOwnPropertyDescriptor,Xv=(n,e,t,r)=>{for(var s=r>1?void 0:r?Jv(e,t):e,i=n.length-1,a;i>=0;i--)(a=n[i])&&(s=a(s)||s);return s};Ue.FirebaseCloudStorage=class extends Hn{constructor(e){if(super(),e&&q.useEmulator(e),q.emulator?.emulate){const{host:t,storagePort:r}=q.emulator;tf(q.instance.storage(),t,r)}}save(e,t,r){const s=q.instance.storage();return new Promise((i,a)=>{if(this._uploadTask=vv(Ua(s,e),t),r)var c=this._uploadTask.on("state_changed",l=>{r(l.bytesTransferred,l.totalBytes)},null,()=>c());this._uploadTask.then(()=>i(e)).catch(l=>a(l))})}getUrl(e){if(!e)return Promise.reject("needs a reference");const t=q.instance.storage();return Av(Ua(t,e))}uploadControl(){if(!this._uploadTask)throw new Error("You should call save() before uploadControl()");return{cancel:()=>this._uploadTask?.cancel(),pause:()=>this._uploadTask?.pause(),resume:()=>this._uploadTask?.resume(),onProgress:e=>this._uploadTask?.on("state_changed",t=>{e&&e(t.bytesTransferred,t.totalBytes)})}}delete(e){const t=q.instance.storage();return Rv(Ua(t,e))}},Ue.FirebaseCloudStorage=Xv([Ih("FirebaseCloudStorage",()=>new Ue.FirebaseCloudStorage)],Ue.FirebaseCloudStorage);const lf={twitter:()=>new Ze,facebook:()=>new ht,google:()=>new dt};class qa extends vh{constructor(e){if(super(),this.credentialProviders={},e&&q.useEmulator(e),q.emulator?.emulate){const{host:t,authPort:r}=q.emulator;if(!t||!r)throw new Error("You should define a host and an auth emulator port to use the emulator");Xh(q.instance.auth(),`http://${t}:${r}`)}this.registerCredentialProviders()}signUp(e){const{authProvider:t,verificationLink:r}=e;return t.slice(0,5)==="email"?new Promise(async(s,i)=>{try{const a=this.credentialProviders["email-sign-up"];if(!a)throw new Error(`The provider ${t} is not registered`);const c=await a(e);e.name&&await ZT(c.user,{displayName:e.name}),r&&await ud(c.user,{url:r}),s(await this.toUserCredentials(c.user))}catch(a){i({code:ii(a.code.slice(5)),message:a.message})}}):this.login(e)}login(e){const{authProvider:t}=e;return new Promise(async(r,s)=>{try{const i=this.credentialProviders[t];if(!i)throw new Error(`The provider ${t} is not registered`);const a=await i(e);r(await this.toUserCredentials(a.user))}catch(i){s({code:i.code===400?"missingPassword":ii(i.code.slice(5)),message:i.message})}})}logout(){return q.instance.auth().signOut()}resetEmailPassword(e){return new Promise(async(t,r)=>{try{await YT(q.instance.auth(),e),t()}catch(s){r({code:ii(s.code.slice(5)),message:s.message})}})}resendVerificationEmail(e,t,r){return new Promise(async(s,i)=>{try{await cd(q.instance.auth(),e,t);const a=q.instance.auth().currentUser;if(!a){i({code:"userNotFound",message:"There is no logged in user"});return}await ud(a,{url:r}),s()}catch(a){i({code:ii(a.code.slice(5)),message:r})}})}refreshToken(){return q.instance.auth().currentUser?.getIdToken(!0)}onAuthStateChange(e){q.instance.auth().onAuthStateChanged(async t=>{e(t?await this.toUserCredentials(t):void 0)})}linkAdditionalProvider(e){const t=lf[e](),r=q.instance.auth().currentUser;if(!r)throw new Error("There is no logged in user");return wd(r,t)}unlinkProvider(e){const{currentUser:t}=q.instance.auth();if(!t)throw new Error("There is no logged in user");return t.providerData,zT(t,lf[e]().providerId)}async toUserCredentials(e){if(!e)throw new Error("The user in user credentials is not defined");const t=(await e.getIdTokenResult()).claims;return qa.convertCredentials(e,t)}static convertCredentials(e,t){return{id:e.uid,email:e.email??"",name:e.displayName??void 0,pictureUrl:e.photoURL??void 0,phoneNumber:e.phoneNumber??void 0,emailVerified:e.emailVerified,customData:{...t},lastLogin:Date.now(),creationDate:e.metadata.creationTime?new Date(e.metadata.creationTime).getTime():void 0}}registerCredentialProvider(e,t){this.credentialProviders[e]=t}registerCredentialProviders(){this.registerCredentialProvider("email-sign-up",e=>{if(!e.email||!e.password)throw new Error("Email and password are required");return JT(q.instance.auth(),e.email,e.password)}),this.registerCredentialProvider("email",e=>{if(!e.email||!e.password)throw new Error("Email and password are required");return cd(q.instance.auth(),e.email,e.password)}),this.registerCredentialProvider("google",()=>ba(q.instance.auth(),new dt)),this.registerCredentialProvider("facebook",()=>ba(q.instance.auth(),new ht)),this.registerCredentialProvider("twitter",()=>ba(q.instance.auth(),new Ze)),this.registerCredentialProvider("link-twitter",()=>{const e=q.instance.auth().currentUser;if(!e)throw new Error("There is no logged in user");return wd(e,new Ze)}),this.registerCredentialProvider("anonymous",()=>$T(q.instance.auth()))}}class Zv{constructor(e,t){if(e&&q.setRegion(e),t&&q.useEmulator(t),q.emulator?.emulate){const{host:r,functionsPort:s}=q.emulator;uf(q.instance.functions(),r,s)}}retrieveFunction(e){return Qv(q.instance.functions(),e)}async callFunction(e,t){return(await e(t)).data}}Ue.FirebaseAuth=qa,Ue.FirebaseCloudFunctions=Zv,Ue.FirebaseDatasource=Yv,Ue.FirebaseHelper=q,Object.defineProperty(Ue,Symbol.toStringTag,{value:"Module"})});
53
53
  //# sourceMappingURL=entropic-bond-firebase.umd.cjs.map