(()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})}};e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var t={};e.r(t),e.d(t,{FirebaseError:()=>I,SDK_VERSION:()=>We,_DEFAULT_ENTRY_NAME:()=>Ee,_addComponent:()=>Ne,_addOrOverwriteComponent:()=>Ae,_apps:()=>Se,_clearComponents:()=>Fe,_components:()=>Re,_getProvider:()=>De,_isFirebaseApp:()=>Le,_isFirebaseServerApp:()=>Me,_registerComponent:()=>Oe,_removeServiceInstance:()=>xe,_serverApps:()=>Pe,deleteApp:()=>$e,getApp:()=>ze,getApps:()=>He,initializeApp:()=>Ve,initializeServerApp:()=>Be,onLog:()=>Ge,registerVersion:()=>Ke,setLogLevel:()=>Ye});const n=function(e,t){if(!e)throw i(t)},i=function(e){return new Error("Firebase Database (${JSCORE_VERSION}) INTERNAL ASSERT FAILED: "+e)},r=function(e){const t=[];let n=0;for(let i=0;i>6|192,t[n++]=63&r|128):55296==(64512&r)&&i+1>18|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>12|224,t[n++]=r>>6&63|128,t[n++]=63&r|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let t=0;t>2,h=(3&r)<<4|o>>4;let u=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(u=64)),i.push(n[l],n[h],n[u],n[d])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,i=0;for(;n191&&r<224){const s=e[n++];t[i++]=String.fromCharCode((31&r)<<6|63&s)}else if(r>239&&r<365){const s=((7&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[i++]=String.fromCharCode(55296+(s>>10)),t[i++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],o=e[n++];t[i++]=String.fromCharCode((15&r)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let t=0;t>4;if(i.push(l),64!==a){const e=s<<4&240|a>>2;if(i.push(e),64!==c){const e=a<<6&192|c;i.push(e)}}}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class o extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const a=function(e){const t=r(e);return s.encodeByteArray(t,!0)},c=function(e){return a(e).replace(/\./g,"")},l=function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function h(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=h(e[n],t[n]));return e}const u=()=>{try{return function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==e.g)return e.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&l(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},d=()=>{var e;return null===(e=u())||void 0===e?void 0:e.config};class p{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function f(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function _(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(f())}function m(){var t;const n=null===(t=u())||void 0===t?void 0:t.forceEnvironment;if("node"===n)return!0;if("browser"===n)return!1;try{return"[object process]"===Object.prototype.toString.call(e.g.process)}catch(e){return!1}}function g(){return"object"==typeof self&&self.self===self}function v(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function y(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function w(){const e=f();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}function b(){try{return"object"==typeof indexedDB}catch(e){return!1}}class I extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,I.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,C.prototype.create)}}class C{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,r=this.errors[e],s=r?function(e,t){return e.replace(T,((e,n)=>{const i=t[n];return null!=i?String(i):`<${n}?>`}))}(r,n):"Error",o=`${this.serviceName}: ${s} (${i}).`;return new I(i,o,n)}}const T=/\{\$([^}]+)}/g;function E(e){return JSON.parse(e)}function k(e){return JSON.stringify(e)}const S=function(e){let t={},n={},i={},r="";try{const s=e.split(".");t=E(l(s[0])||""),n=E(l(s[1])||""),r=s[2],i=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:i,signature:r}};function P(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function N(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function A(e,t,n){const i={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function O(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);for(const r of n){if(!i.includes(r))return!1;const n=e[r],s=t[r];if(D(n)&&D(s)){if(!O(n,s))return!1}else if(n!==s)return!1}for(const e of i)if(!n.includes(e))return!1;return!0}function D(e){return null!==e&&"object"==typeof e}function x(e){const t=[];for(const[n,i]of Object.entries(e))Array.isArray(i)?i.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""}function L(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,i]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(i)}})),t}function M(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class F{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e>>31)}let i,r,s=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],l=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(i=c^o&(a^c),r=1518500249):(i=o^a^c,r=1859775393):e<60?(i=o&a|c&(o|a),r=2400959708):(i=o^a^c,r=3395469782);const t=(s<<5|s>>>27)+i+l+r+n[e]&4294967295;l=c,c=a,a=4294967295&(o<<30|o>>>2),o=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let i=0;const r=this.buf_;let s=this.inbuf_;for(;i=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let i=24;i>=0;i-=8)e[n]=this.chain_[t]>>i&255,++n;return e}}function U(e,t){const n=new q(e,t);return n.subscribe.bind(n)}class q{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let i;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");i=function(e,t){if("object"!=typeof e||null===e)return!1;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}(e)?e:{next:e,error:t,complete:n},void 0===i.next&&(i.next=j),void 0===i.error&&(i.error=j),void 0===i.complete&&(i.complete=j);const r=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch(e){}})),this.observers.push(i),r}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function j(){}const W=function(e,t,n,i){let r;if(in&&(r=0===n?"none":"no more than "+n),r)throw new Error(e+" failed: Was called with "+i+(1===i?" argument.":" arguments.")+" Expects "+r+".")};function V(e,t){return`${e} failed: ${t} argument `}function B(e,t,n,i){if((!i||n)&&"function"!=typeof n)throw new Error(V(e,t)+"must be a valid function.")}function z(e,t,n,i){if((!i||n)&&("object"!=typeof n||null===n))throw new Error(V(e,t)+"must be a valid context object.")}const H=function(e){let t=0;for(let n=0;n=55296&&i<=56319?(t+=4,n++):t+=3}return t};function $(e){return e&&e._delegate?e._delegate:e}class K{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const G="[DEFAULT]";class Y{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 e=new p;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),i=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(i)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(i)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:G})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=G){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=G){return this.instances.has(e)}getOptions(e=G){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(i);return i}onInit(e,t){var n;const i=this.normalizeInstanceIdentifier(t),r=null!==(n=this.onInitCallbacks.get(i))&&void 0!==n?n:new Set;r.add(e),this.onInitCallbacks.set(i,r);const s=this.instances.get(i);return s&&e(s,i),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const i of n)try{i(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(i=e,i===G?void 0:i),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var i;return n||null}normalizeInstanceIdentifier(e=G){return this.component?this.component.multipleInstances?e:G:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class J{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 Y(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const Q=[];var X;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(X||(X={}));const Z={debug:X.DEBUG,verbose:X.VERBOSE,info:X.INFO,warn:X.WARN,error:X.ERROR,silent:X.SILENT},ee=X.INFO,te={[X.DEBUG]:"log",[X.VERBOSE]:"log",[X.INFO]:"info",[X.WARN]:"warn",[X.ERROR]:"error"},ne=(e,t,...n)=>{if(tt.some((t=>e instanceof t));let se,oe;const ae=new WeakMap,ce=new WeakMap,le=new WeakMap,he=new WeakMap,ue=new WeakMap;let de={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return ce.get(e);if("objectStoreNames"===t)return e.objectStoreNames||le.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return fe(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function pe(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(oe||(oe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(_e(this),e),fe(ae.get(this))}:function(...e){return fe(t.apply(_e(this),e))}:function(e,...n){const i=t.call(_e(this),e,...n);return le.set(i,e.sort?e.sort():[e]),fe(i)}:(e instanceof IDBTransaction&&function(e){if(ce.has(e))return;const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",s),e.removeEventListener("abort",s)},r=()=>{t(),i()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",r),e.addEventListener("error",s),e.addEventListener("abort",s)}));ce.set(e,t)}(e),re(e,se||(se=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,de):e);var t}function fe(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("success",r),e.removeEventListener("error",s)},r=()=>{t(fe(e.result)),i()},s=()=>{n(e.error),i()};e.addEventListener("success",r),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&ae.set(t,e)})).catch((()=>{})),ue.set(t,e),t}(e);if(he.has(e))return he.get(e);const t=pe(e);return t!==e&&(he.set(e,t),ue.set(t,e)),t}const _e=e=>ue.get(e),me=["get","getKey","getAll","getAllKeys","count"],ge=["put","add","delete","clear"],ve=new Map;function ye(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(ve.get(t))return ve.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,r=ge.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!r&&!me.includes(n))return;const s=async function(e,...t){const s=this.transaction(e,r?"readwrite":"readonly");let o=s.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),r&&s.done]))[0]};return ve.set(t,s),s}var we;we=de,de={...we,get:(e,t,n)=>ye(e,t)||we.get(e,t,n),has:(e,t)=>!!ye(e,t)||we.has(e,t)};class be{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const Ie="@firebase/app",Ce="0.10.5",Te=new ie("@firebase/app"),Ee="[DEFAULT]",ke={[Ie]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai-preview":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},Se=new Map,Pe=new Map,Re=new Map;function Ne(e,t){try{e.container.addComponent(t)}catch(n){Te.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function Ae(e,t){e.container.addOrOverwriteComponent(t)}function Oe(e){const t=e.name;if(Re.has(t))return Te.debug(`There were multiple attempts to register component ${t}.`),!1;Re.set(t,e);for(const t of Se.values())Ne(t,e);for(const t of Pe.values())Ne(t,e);return!0}function De(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function xe(e,t,n=Ee){De(e,t).clearInstance(n)}function Le(e){return void 0!==e.options}function Me(e){return void 0!==e.settings}function Fe(){Re.clear()}const Ue=new C("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class qe{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new K("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 Ue.create("app-deleted",{appName:this._name})}}class je extends qe{constructor(e,t,n,i){const r=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,s={name:n,automaticDataCollectionEnabled:r};void 0!==e.apiKey?super(e,s,i):super(e.options,s,i),this._serverConfig=Object.assign({automaticDataCollectionEnabled:r},t),this._finalizationRegistry=new FinalizationRegistry((()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,Ke(Ie,Ce,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){$e(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw Ue.create("server-app-deleted")}}const We="10.12.2";function Ve(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});const i=Object.assign({name:Ee,automaticDataCollectionEnabled:!1},t),r=i.name;if("string"!=typeof r||!r)throw Ue.create("bad-app-name",{appName:String(r)});if(n||(n=d()),!n)throw Ue.create("no-options");const s=Se.get(r);if(s){if(O(n,s.options)&&O(i,s.config))return s;throw Ue.create("duplicate-app",{appName:r})}const o=new J(r);for(const e of Re.values())o.addComponent(e);const a=new qe(n,i,o);return Se.set(r,a),a}function Be(e,t){if(g())throw Ue.create("invalid-server-app-environment");let n;void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1),n=Le(e)?e.options:e;const i=Object.assign(Object.assign({},t),n);if(void 0!==i.releaseOnDeref&&delete i.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw Ue.create("finalization-registry-not-supported",{});const r=""+(s=JSON.stringify(i),[...s].reduce(((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0),0));var s;const o=Pe.get(r);if(o)return o.incRefCount(t.releaseOnDeref),o;const a=new J(r);for(const e of Re.values())a.addComponent(e);const c=new je(n,t,r,a);return Pe.set(r,c),c}function ze(e=Ee){const t=Se.get(e);if(!t&&e===Ee&&d())return Ve();if(!t)throw Ue.create("no-app",{appName:e});return t}function He(){return Array.from(Se.values())}async function $e(e){let t=!1;const n=e.name;Se.has(n)?(t=!0,Se.delete(n)):Pe.has(n)&&e.decRefCount()<=0&&(Pe.delete(n),t=!0),t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function Ke(e,t,n){var i;let r=null!==(i=ke[e])&&void 0!==i?i:e;n&&(r+=`-${n}`);const s=r.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${r}" with version "${t}":`];return s&&e.push(`library name "${r}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void Te.warn(e.join(" "))}Oe(new K(`${r}-version`,(()=>({library:r,version:t})),"VERSION"))}function Ge(e,t){if(null!==e&&"function"!=typeof e)throw Ue.create("invalid-log-argument");!function(e,t){for(const n of Q){let i=null;t&&t.level&&(i=Z[t.level]),n.userLogHandler=null===e?null:(t,n,...r)=>{const s=r.map((e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}})).filter((e=>e)).join(" ");n>=(null!=i?i:t.logLevel)&&e({level:X[n].toLowerCase(),message:s,args:r,type:t.name})}}}(e,t)}function Ye(e){var t;t=e,Q.forEach((e=>{e.setLogLevel(t)}))}const Je="firebase-heartbeat-database",Qe=1,Xe="firebase-heartbeat-store";let Ze=null;function et(){return Ze||(Ze=function(e,t,{blocked:n,upgrade:i,blocking:r,terminated:s}={}){const o=indexedDB.open(e,t),a=fe(o);return i&&o.addEventListener("upgradeneeded",(e=>{i(fe(o.result),e.oldVersion,e.newVersion,fe(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),r&&e.addEventListener("versionchange",(e=>r(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(Je,Qe,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Xe)}catch(e){console.warn(e)}}}).catch((e=>{throw Ue.create("idb-open",{originalErrorMessage:e.message})}))),Ze}async function tt(e,t){try{const n=(await et()).transaction(Xe,"readwrite"),i=n.objectStore(Xe);await i.put(t,nt(e)),await n.done}catch(e){if(e instanceof I)Te.warn(e.message);else{const t=Ue.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});Te.warn(t.message)}}}function nt(e){return`${e.name}!${e.options.appId}`}class it{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new st(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e,t;const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=rt();if((null!=(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats)))&&this._heartbeatsCache.lastSentHeartbeatDate!==i&&!this._heartbeatsCache.heartbeats.some((e=>e.date===i)))return this._heartbeatsCache.heartbeats.push({date:i,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){var e;if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=rt(),{heartbeatsToSend:n,unsentEntries:i}=function(e,t=1024){const n=[];let i=e.slice();for(const r of e){const e=n.find((e=>e.agent===r.agent));if(e){if(e.dates.push(r.date),ot(n)>t){e.dates.pop();break}}else if(n.push({agent:r.agent,dates:[r.date]}),ot(n)>t){n.pop();break}i=i.slice(1)}return{heartbeatsToSend:n,unsentEntries:i}}(this._heartbeatsCache.heartbeats),r=c(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}}function rt(){return(new Date).toISOString().substring(0,10)}class st{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!b()&&new Promise(((e,t)=>{try{let n=!0;const i="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(i);r.onsuccess=()=>{r.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},r.onupgradeneeded=()=>{n=!1},r.onerror=()=>{var e;t((null===(e=r.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}})).then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await et()).transaction(Xe),n=await t.objectStore(Xe).get(nt(e));return await t.done,n}catch(e){if(e instanceof I)Te.warn(e.message);else{const t=Ue.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});Te.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return tt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return tt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function ot(e){return c(JSON.stringify({version:2,heartbeats:e})).length}Oe(new K("platform-logger",(e=>new be(e)),"PRIVATE")),Oe(new K("heartbeat",(e=>new it(e)),"PRIVATE")),Ke(Ie,Ce,""),Ke(Ie,Ce,"esm2017"),Ke("fire-js","");class at{constructor(e,t){this._delegate=e,this.firebase=t,Ne(e,new K("app-compat",(()=>this),"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise((e=>{this._delegate.checkDestroyed(),e()})).then((()=>(this.firebase.INTERNAL.removeApp(this.name),$e(this._delegate))))}_getService(e,t=Ee){var n;this._delegate.checkDestroyed();const i=this._delegate.container.getProvider(e);return i.isInitialized()||"EXPLICIT"!==(null===(n=i.getComponent())||void 0===n?void 0:n.instantiationMode)||i.initialize(),i.getImmediate({identifier:t})}_removeServiceInstance(e,t=Ee){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Ne(this._delegate,e)}_addOrOverwriteComponent(e){Ae(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const ct=new C("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."}),lt=function e(){const n=function(e){const n={},i={__esModule:!0,initializeApp:function(t,r={}){const s=Ve(t,r);if(P(n,s.name))return n[s.name];const o=new e(s,i);return n[s.name]=o,o},app:r,registerVersion:Ke,setLogLevel:Ye,onLog:Ge,apps:null,SDK_VERSION:We,INTERNAL:{registerComponent:function(t){const n=t.name,s=n.replace("-compat","");if(Oe(t)&&"PUBLIC"===t.type){const o=(e=r())=>{if("function"!=typeof e[s])throw ct.create("invalid-app-argument",{appName:n});return e[s]()};void 0!==t.serviceProps&&h(o,t.serviceProps),i[s]=o,e.prototype[s]=function(...e){return this._getService.bind(this,n).apply(this,t.multipleInstances?e:[])}}return"PUBLIC"===t.type?i[s]:null},removeApp:function(e){delete n[e]},useAsService:function(e,t){return"serverAuth"===t?null:t},modularAPIs:t}};function r(e){if(!P(n,e=e||Ee))throw ct.create("no-app",{appName:e});return n[e]}return i.default=i,Object.defineProperty(i,"apps",{get:function(){return Object.keys(n).map((e=>n[e]))}}),r.App=e,i}(at);return n.INTERNAL=Object.assign(Object.assign({},n.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){h(n,e)},createSubscribe:U,ErrorFactory:C,deepExtend:h}),n}(),ht=new ie("@firebase/app-compat");if(g()&&void 0!==self.firebase){ht.warn("\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n ");const e=self.firebase.SDK_VERSION;e&&e.indexOf("LITE")>=0&&ht.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n ")}const ut=lt;Ke("@firebase/app-compat","0.2.35",void 0),ut.registerVersion("firebase","10.12.2","app-compat");const dt="@firebase/database",pt="1.0.5";let ft="";function _t(e){ft=e}class mt{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),k(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:E(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class gt{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return P(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const vt=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new mt(t)}}catch(e){}return new gt},yt=vt("localStorage"),wt=vt("sessionStorage"),bt=new ie("@firebase/database"),It=function(){let e=1;return function(){return e++}}(),Ct=function(e){const t=function(e){const t=[];let i=0;for(let r=0;r=55296&&s<=56319){const t=s-55296;r++,n(r>6|192,t[i++]=63&s|128):s<65536?(t[i++]=s>>12|224,t[i++]=s>>6&63|128,t[i++]=63&s|128):(t[i++]=s>>18|240,t[i++]=s>>12&63|128,t[i++]=s>>6&63|128,t[i++]=63&s|128)}return t}(e),i=new F;i.update(t);const r=i.digest();return s.encodeByteArray(r)},Tt=function(...e){let t="";for(let n=0;nn?i.push(e.substring(r,n)):i.push(e.substring(r,r+t));return i};function Wt(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const Vt=function(e){n(!Dt(e),"Invalid JSON number");let t,i,r,s,o;0===e?(i=0,r=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(s=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),i=s+1023,r=Math.round(e*Math.pow(2,52-s)-Math.pow(2,52))):(i=0,r=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(r%2?1:0),r=Math.floor(r/2);for(o=11;o;o-=1)a.push(i%2?1:0),i=Math.floor(i/2);a.push(t?1:0),a.reverse();const c=a.join("");let l="";for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()},Bt=new RegExp("^-?(0*)\\d{1,10}$"),zt=function(e){if(Bt.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},Ht=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw Ot("Exception was thrown by user callback.",t),e}),Math.floor(0))}},$t=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class Kt{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then((e=>this.appCheck=e))}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){Ot(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class Gt{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(Pt("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Ot(e)}}class Yt{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Yt.OWNER="owner";const Jt="5",Qt=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Xt="ac",Zt="websocket",en="long_polling";class tn{constructor(e,t,n,i,r=!1,s="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=yt.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&yt.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function nn(e,t,i){let r;if(n("string"==typeof t,"typeof type must == string"),n("object"==typeof i,"typeof params must == object"),t===Zt)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==en)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(i.ns=e.namespace);const s=[];return Wt(i,((e,t)=>{s.push(e+"="+t)})),r+s.join("&")}class rn{constructor(){this.counters_={}}incrementCounter(e,t=1){P(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return h(void 0,this.counters_)}}const sn={},on={};function an(e){const t=e.toString();return sn[t]||(sn[t]=new rn),sn[t]}class cn{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse{this.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const ln="start";class hn{constructor(e,t,n,i,r,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Rt(e),this.stats_=an(t),this.urlFn=e=>(this.appCheckToken&&(e[Xt]=this.appCheckToken),nn(t,en,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new cn(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&n()})),window.attachEvent("onload",n))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new un(((...e)=>{const[t,n,i,r,s]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ln)this.id=n,this.password=i;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,(()=>{this.onClosed_()}))):this.onClosed_()}}),((...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[ln]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v=Jt,this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[Xt]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Qt.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){hn.forceAllow_=!0}static forceDisallow(){hn.forceDisallow_=!0}static isAvailable(){return!(!hn.forceAllow_&&(hn.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI))}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=k(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=a(t),i=jt(n,1840);for(let e=0;edocument.domain="'+document.domain+'";<\/script>');const i=""+n+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){Pt("frame writing exception"),e.stack&&Pt(e.stack),Pt(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||Pt("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+n.length<=1870;){const e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(i),n()}))}addTag(e,t){setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{Pt("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}let dn=null;"undefined"!=typeof MozWebSocket?dn=MozWebSocket:"undefined"!=typeof WebSocket&&(dn=WebSocket);class pn{constructor(e,t,n,i,r,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Rt(this.connId),this.stats_=an(t),this.connURL=pn.connectionURL_(t,s,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i,r){const s={};return s.v=Jt,"undefined"!=typeof location&&location.hostname&&Qt.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),i&&(s[Xt]=i),r&&(s.p=r),nn(e,Zt,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,yt.set("previous_websocket_failure",!0);try{let e;0,this.mySock=new dn(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){pn.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==dn&&!pn.forceDisallow_}static previouslyFailed(){return yt.isInMemoryStorage||!0===yt.get("previous_websocket_failure")}markConnectionHealthy(){yt.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=E(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(n(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=k(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=jt(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e{this.mySock&&this.sendString_("0"),this.resetKeepAlive()}),Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}pn.responsesRequiredToBeHealthy=2,pn.healthyTimeout=3e4;class fn{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[hn,pn]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=pn&&pn.isAvailable();let n=t&&!pn.previouslyFailed();if(e.webSocketOnly&&(t||Ot("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[pn];else{const e=this.transports_=[];for(const t of fn.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);fn.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}fn.globalTransportInitialized_=!1;class mn{constructor(e,t,n,i,r,s,o,a,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Rt("c:"+this.id+":"),this.transportManager_=new fn(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((()=>{this.conn_&&this.conn_.open(t,n)}),Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=$t((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=Ut("t",e),n=Ut("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=Ut("t",e),n=Ut("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=Ut("t",e);if("d"in e){const n=e.d;if("h"===t){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())}),Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):$t((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(yt.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class gn{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class vn{constructor(e){this.allowedEvents_=e,this.listeners_={},n(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;et===e)),"Unknown event: "+e)}}class yn extends vn{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||_()||(window.addEventListener("online",(()=>{this.online_||(this.online_=!0,this.trigger("online",!0))}),!1),window.addEventListener("offline",(()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))}),!1))}static getInstance(){return new yn}getInitialEvent(e){return n("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class wn{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function Cn(e){return e.pieces_.length-e.pieceNum_}function Tn(e){let t=e.pieceNum_;return t=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n0&&n.push(e[t])}return new wn(n,0)}function Rn(e){return e.pieceNum_>=e.pieces_.length}function Nn(e,t){const n=In(e),i=In(t);if(null===n)return t;if(n===i)return Nn(Tn(e),Tn(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function An(e,t){const n=kn(e,0),i=kn(t,0);for(let e=0;eCn(t))return!1;for(;n768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+Mn(e))}function Mn(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Fn extends vn{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}static getInstance(){return new Fn}getInitialEvent(e){return n("visible"===e,"Unknown event type: "+e),[this.visible_]}}const Un=1e3;class qn extends gn{constructor(e,t,n,i,r,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=qn.nextPersistentConnectionId_++,this.log_=Rt("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=Un,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Fn.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&yn.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,i){const r=++this.requestNumber_,s={r,a:e,b:t};this.log_(k(s)),n(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),i&&(this.requestCBHash_[r]=i)}get(e){this.initConnection_();const t=new p,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(i),t.promise}listen(e,t,i,r){this.initConnection_();const s=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+s),this.listens.has(o)||this.listens.set(o,new Map),n(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),n(!this.listens.get(o).has(s),"listen() called twice for same path/queryId.");const a={onComplete:r,hashFn:t,query:e,tag:i};this.listens.get(o).set(s,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const r={p:n};e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest("q",r,(r=>{const s=r.d,o=r.s;qn.warnOnListenWarnings_(s,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",r),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,s))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&P(e,"w")){const n=R(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();Ot(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||function(e){const t=S(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=function(e){const t=S(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const i=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+i+" "+r),n(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(i,r)&&this.connected_&&this.sendUnlisten_(i,r,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const r={p:e};i&&(r.q=n,r.t=i),this.sendRequest("n",r)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){const r={p:t,d:n};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,(e=>{i&&setTimeout((()=>{i(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,r){this.initConnection_();const s={p:t,d:n};void 0!==r&&(s.h=r),this.outstandingPuts_.push({action:e,request:s,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+k(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):Nt("Unrecognized action received from server: "+k(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){n(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout((()=>{this.establishConnectionTimer_=null,this.establishConnection_()}),Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=Un,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Un,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&((new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=Un),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime());const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),i=this.onRealtimeDisconnect_.bind(this),r=this.id+":"+qn.nextConnectionId_++,s=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,i())},l=function(e){n(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:c,sendRequest:l};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[n,c]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?Pt("getToken() completed but was canceled"):(Pt("getToken() completed. Creating connection."),this.authToken_=n&&n.accessToken,this.appCheckToken_=c&&c.token,a=new mn(r,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,i,(e=>{Ot(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),s))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&Ot(e),c())}}}interrupt(e){Pt("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){Pt("Resuming connection for reason: "+e),delete this.interruptReasons_[e],N(this.interruptReasons_)&&(this.reconnectDelay_=Un,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;eqt(e))).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new wn(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){Pt("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){Pt("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class $n{constructor(e,t,n,i,r){this.key=e,this.value=t,this.color=null!=n?n:$n.RED,this.left=null!=i?i:Kn.EMPTY_NODE,this.right=null!=r?r:Kn.EMPTY_NODE}copy(e,t,n,i,r){return new $n(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=r?r:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this;const r=n(e,i.key);return i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Kn.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,i;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return Kn.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.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,$n.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,$n.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.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}$n.RED=!0,$n.BLACK=!1;class Kn{constructor(e,t=Kn.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Kn(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,$n.BLACK,null,null))}remove(e){return new Kn(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,$n.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Hn(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Hn(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Hn(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Hn(this.root_,null,this.comparator_,!0,e)}}function Gn(e,t){return Mt(e.name,t.name)}function Yn(e,t){return Mt(e,t)}let Jn;Kn.EMPTY_NODE=new class{copy(e,t,n,i,r){return this}insert(e,t,n){return new $n(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};const Qn=function(e){return"number"==typeof e?"number:"+Vt(e):"string:"+e},Xn=function(e){if(e.isLeafNode()){const t=e.val();n("string"==typeof t||"number"==typeof t||"object"==typeof t&&P(t,".sv"),"Priority must be a string or number.")}else n(e===Jn||e.isEmpty(),"priority of unexpected type.");n(e===Jn||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Zn,ei,ti;class ni{constructor(e,t=ni.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,n(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Xn(this.priorityNode_)}static set __childrenNodeConstructor(e){Zn=e}static get __childrenNodeConstructor(){return Zn}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new ni(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:ni.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return Rn(e)?this:".priority"===In(e)?this.priorityNode_:ni.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:ni.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const i=In(e);return null===i?t:t.isEmpty()&&".priority"!==i?this:(n(".priority"!==i||1===Cn(e),".priority must be the last token in a path"),this.updateImmediateChild(i,ni.__childrenNodeConstructor.EMPTY_NODE.updateChild(Tn(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+Qn(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?Vt(this.value_):this.value_,this.lazyHash_=Ct(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===ni.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof ni.__childrenNodeConstructor?-1:(n(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,i=typeof this.value_,r=ni.VALUE_TYPE_ORDER.indexOf(t),s=ni.VALUE_TYPE_ORDER.indexOf(i);return n(r>=0,"Unknown leaf type: "+t),n(s>=0,"Unknown leaf type: "+i),r===s?"object"===i?0:this.value_{const s=R(this.indexSet_,r);if(n(s,"Missing index implementation for "+r),i===ci){if(s.isDefinedOn(e.node)){const n=[],i=t.getIterator(jn.Wrap);let r=i.getNext();for(;r;)r.name!==e.name&&n.push(r),r=i.getNext();return n.push(e),oi(n,s.getCompare())}return ci}{const n=t.get(e.name);let r=i;return n&&(r=r.remove(new jn(e.name,n))),r.insert(e,e.node)}}));return new li(i,this.indexSet_)}removeFromIndexes(e,t){const n=A(this.indexes_,(n=>{if(n===ci)return n;{const i=t.get(e.name);return i?n.remove(new jn(e.name,i)):n}}));return new li(n,this.indexSet_)}}let hi;class ui{constructor(e,t,i){this.children_=e,this.priorityNode_=t,this.indexMap_=i,this.lazyHash_=null,this.priorityNode_&&Xn(this.priorityNode_),this.children_.isEmpty()&&n(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return hi||(hi=new ui(new Kn(Yn),null,li.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||hi}updatePriority(e){return this.children_.isEmpty()?this:new ui(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?hi:t}}getChild(e){const t=In(e);return null===t?this:this.getImmediateChild(t).getChild(Tn(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(n(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new jn(e,t);let i,r;t.isEmpty()?(i=this.children_.remove(e),r=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),r=this.indexMap_.addToIndexes(n,this.children_));const s=i.isEmpty()?hi:this.priorityNode_;return new ui(i,s,r)}}updateChild(e,t){const i=In(e);if(null===i)return t;{n(".priority"!==In(e)||1===Cn(e),".priority must be the last token in a path");const r=this.getImmediateChild(i).updateChild(Tn(e),t);return this.updateImmediateChild(i,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,r=!0;if(this.forEachChild(ii,((s,o)=>{t[s]=o.val(e),n++,r&&ui.INTEGER_REGEXP_.test(s)?i=Math.max(i,Number(s)):r=!1})),!e&&r&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Qn(this.getPriority().val())+":"),this.forEachChild(ii,((t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)})),this.lazyHash_=""===e?"":Ct(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new jn(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new jn(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new jn(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal((e=>t(e.name,e.node))):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,jn.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,jn.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===di?-1:0}withIndex(e){if(e===zn||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new ui(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===zn||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(ii),n=t.getIterator(ii);let i=e.getNext(),r=n.getNext();for(;i&&r;){if(i.name!==r.name||!i.node.equals(r.node))return!1;i=e.getNext(),r=n.getNext()}return null===i&&null===r}return!1}return!1}}resolveIndex_(e){return e===zn?null:this.indexMap_.get(e.toString())}}ui.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const di=new class extends ui{constructor(){super(new Kn(Yn),ui.EMPTY_NODE,li.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ui.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(jn,{MIN:{value:new jn(xt,ui.EMPTY_NODE)},MAX:{value:new jn(Lt,di)}}),Bn.__EMPTY_NODE=ui.EMPTY_NODE,ni.__childrenNodeConstructor=ui,Jn=di,ti=di;const pi=!0;function fi(e,t=null){if(null===e)return ui.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),n(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new ni(e,fi(t));if(e instanceof Array||!pi){let n=ui.EMPTY_NODE;return Wt(e,((t,i)=>{if(P(e,t)&&"."!==t.substring(0,1)){const e=fi(i);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(fi(t))}{const n=[];let i=!1;if(Wt(e,((e,t)=>{if("."!==e.substring(0,1)){const r=fi(t);r.isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new jn(e,r)))}})),0===n.length)return ui.EMPTY_NODE;const r=oi(n,Gn,(e=>e.name),Yn);if(i){const e=oi(n,ii.getCompare());return new ui(r,fi(t),new li({".priority":e},{".priority":ii}))}return new ui(r,fi(t),li.Default)}}!function(e){ei=e}(fi);class _i extends Wn{constructor(e){super(),this.indexPath_=e,n(!Rn(e)&&".priority"!==In(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),i=this.extractChild(t.node),r=n.compareTo(i);return 0===r?Mt(e.name,t.name):r}makePost(e,t){const n=fi(e),i=ui.EMPTY_NODE.updateChild(this.indexPath_,n);return new jn(t,i)}maxPost(){const e=ui.EMPTY_NODE.updateChild(this.indexPath_,di);return new jn(Lt,e)}toString(){return kn(this.indexPath_,0).join("/")}}const mi=new class extends Wn{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?Mt(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return jn.MIN}maxPost(){return jn.MAX}makePost(e,t){const n=fi(e);return new jn(t,n)}toString(){return".value"}};function gi(e){return{type:"value",snapshotNode:e}}function vi(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function yi(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function wi(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class bi{constructor(e){this.index_=e}updateChild(e,t,i,r,s,o){n(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(r).equals(i.getChild(r))&&a.isEmpty()===i.isEmpty()?e:(null!=o&&(i.isEmpty()?e.hasChild(t)?o.trackChildChange(yi(t,a)):n(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(vi(t,i)):o.trackChildChange(wi(t,i,a))),e.isLeafNode()&&i.isEmpty()?e:e.updateImmediateChild(t,i).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(ii,((e,i)=>{t.hasChild(e)||n.trackChildChange(yi(e,i))})),t.isLeafNode()||t.forEachChild(ii,((t,i)=>{if(e.hasChild(t)){const r=e.getImmediateChild(t);r.equals(i)||n.trackChildChange(wi(t,i,r))}else n.trackChildChange(vi(t,i))}))),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ui.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Ii{constructor(e){this.indexedFilter_=new bi(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Ii.getStartPost_(e),this.endPost_=Ii.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,i,r,s){return this.matches(new jn(t,n))||(n=ui.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,r,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=ui.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(ui.EMPTY_NODE);const r=this;return t.forEachChild(ii,((e,t)=>{r.matches(new jn(e,t))||(i=i.updateImmediateChild(e,ui.EMPTY_NODE))})),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class Ci{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new Ii(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,i,r,s){return this.rangedFilter_.matches(new jn(t,n))||(n=ui.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()e(n,t)}else o=this.index_.getCompare();const a=e;n(a.numChildren()===this.limit_,"");const c=new jn(t,i),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(c);if(a.hasChild(t)){const e=a.getImmediateChild(t);let n=r.getChildAfterChild(this.index_,l,this.reverse_);for(;null!=n&&(n.name===t||a.hasChild(n.name));)n=r.getChildAfterChild(this.index_,n,this.reverse_);const u=null==n?1:o(n,c);if(h&&!i.isEmpty()&&u>=0)return null!=s&&s.trackChildChange(wi(t,i,e)),a.updateImmediateChild(t,i);{null!=s&&s.trackChildChange(yi(t,e));const i=a.updateImmediateChild(t,ui.EMPTY_NODE);return null!=n&&this.rangedFilter_.matches(n)?(null!=s&&s.trackChildChange(vi(n.name,n.node)),i.updateImmediateChild(n.name,n.node)):i}}return i.isEmpty()?e:h&&o(l,c)>=0?(null!=s&&(s.trackChildChange(yi(l.name,l.node)),s.trackChildChange(vi(t,i))),a.updateImmediateChild(t,i).updateImmediateChild(l.name,ui.EMPTY_NODE)):e}}class Ti{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=ii}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return n(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return n(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:xt}hasEnd(){return this.endSet_}getIndexEndValue(){return n(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return n(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Lt}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return n(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===ii}copy(){const e=new Ti;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function Ei(e,t,n){const i=e.copy();return i.startSet_=!0,void 0===t&&(t=null),i.indexStartValue_=t,null!=n?(i.startNameSet_=!0,i.indexStartName_=n):(i.startNameSet_=!1,i.indexStartName_=""),i}function ki(e,t,n){const i=e.copy();return i.endSet_=!0,void 0===t&&(t=null),i.indexEndValue_=t,void 0!==n?(i.endNameSet_=!0,i.indexEndName_=n):(i.endNameSet_=!1,i.indexEndName_=""),i}function Si(e,t){const n=e.copy();return n.index_=t,n}function Pi(e){const t={};if(e.isDefault())return t;let i;if(e.index_===ii?i="$priority":e.index_===mi?i="$value":e.index_===zn?i="$key":(n(e.index_ instanceof _i,"Unrecognized index type!"),i=e.index_.toString()),t.orderBy=k(i),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=k(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+k(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=k(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+k(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Ri(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==ii&&(t.i=e.index_.toString()),t}class Ni extends gn{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=Rt("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(n(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const s=Ni.getListenId_(e,n),o={};this.listens_[s]=o;const a=Pi(e._queryParams);this.restRequest_(r+".json",a,((e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(r,a,!1,n),R(this.listens_,s)===o){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",i(t,null)}}))}unlisten(e,t){const n=Ni.getListenId_(e,t);delete this.listens_[n]}get(e){const t=Pi(e._queryParams),n=e._path.toString(),i=new p;return this.restRequest_(n+".json",t,((e,t)=>{let r=t;404===e&&(r=null,e=null),null===e?(this.onDataUpdate_(n,r,!1,null),i.resolve(r)):i.reject(new Error(r))})),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([i,r])=>{i&&i.accessToken&&(t.auth=i.accessToken),r&&r.token&&(t.ac=r.token);const s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+x(t);this.log_("Sending REST request for "+s);const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+s+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=E(o.responseText)}catch(e){Ot("Failed to parse JSON response for "+s+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&Ot("Got unsuccessful REST response for "+s+" Status: "+o.status),n(o.status);n=null}},o.open("GET",s,!0),o.send()}))}}class Ai{constructor(){this.rootNode_=ui.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function Oi(){return{value:null,children:new Map}}function Di(e,t,n){if(Rn(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=In(t);e.children.has(i)||e.children.set(i,Oi()),Di(e.children.get(i),t=Tn(t),n)}}function xi(e,t){if(Rn(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(ii,((t,n)=>{Di(e,new wn(t),n)})),xi(e,t)}}if(e.children.size>0){const n=In(t);return t=Tn(t),e.children.has(n)&&xi(e.children.get(n),t)&&e.children.delete(n),0===e.children.size}return!0}function Li(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}(e,((e,i)=>{Li(i,new wn(t.toString()+"/"+e),n)}))}class Mi{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&Wt(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}class Fi{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Mi(e);const n=1e4+2e4*Math.random();$t(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;Wt(e,((e,i)=>{i>0&&P(this.statsToReport_,e)&&(t[e]=i,n=!0)})),n&&this.server_.reportStats(t),$t(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var Ui;function qi(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(Ui||(Ui={}));class ji{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Ui.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(Rn(this.path)){if(null!=this.affectedTree.value)return n(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new wn(e));return new ji(bn(),t,this.revert)}}return n(In(this.path)===e,"operationForChild called for unrelated child."),new ji(Tn(this.path),this.affectedTree,this.revert)}}class Wi{constructor(e,t){this.source=e,this.path=t,this.type=Ui.LISTEN_COMPLETE}operationForChild(e){return Rn(this.path)?new Wi(this.source,bn()):new Wi(this.source,Tn(this.path))}}class Vi{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Ui.OVERWRITE}operationForChild(e){return Rn(this.path)?new Vi(this.source,bn(),this.snap.getImmediateChild(e)):new Vi(this.source,Tn(this.path),this.snap)}}class Bi{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Ui.MERGE}operationForChild(e){if(Rn(this.path)){const t=this.children.subtree(new wn(e));return t.isEmpty()?null:t.value?new Vi(this.source,bn(),t.value):new Bi(this.source,bn(),t)}return n(In(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Bi(this.source,Tn(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class zi{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Rn(e))return this.isFullyInitialized()&&!this.filtered_;const t=In(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Hi{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function $i(e,t,n,r,s,o){const a=r.filter((e=>e.type===n));a.sort(((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw i("Should only compare child_ events.");const r=new jn(t.childName,t.snapshotNode),s=new jn(n.childName,n.snapshotNode);return e.index_.compare(r,s)}(e,t,n))),a.forEach((n=>{const i=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);s.forEach((r=>{r.respondsTo(n.type)&&t.push(r.createEvent(i,e.query_))}))}))}function Ki(e,t){return{eventCache:e,serverCache:t}}function Gi(e,t,n,i){return Ki(new zi(t,n,i),e.serverCache)}function Yi(e,t,n,i){return Ki(e.eventCache,new zi(t,n,i))}function Ji(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Qi(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Xi;class Zi{constructor(e,t=(()=>(Xi||(Xi=new Kn(Ft)),Xi))()){this.value=e,this.children=t}static fromObject(e){let t=new Zi(null);return Wt(e,((e,n)=>{t=t.set(new wn(e),n)})),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:bn(),value:this.value};if(Rn(e))return null;{const n=In(e),i=this.children.get(n);if(null!==i){const r=i.findRootMostMatchingPathAndValue(Tn(e),t);return null!=r?{path:Pn(new wn(n),r.path),value:r.value}:null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(Rn(e))return this;{const t=In(e),n=this.children.get(t);return null!==n?n.subtree(Tn(e)):new Zi(null)}}set(e,t){if(Rn(e))return new Zi(t,this.children);{const n=In(e),i=(this.children.get(n)||new Zi(null)).set(Tn(e),t),r=this.children.insert(n,i);return new Zi(this.value,r)}}remove(e){if(Rn(e))return this.children.isEmpty()?new Zi(null):new Zi(null,this.children);{const t=In(e),n=this.children.get(t);if(n){const i=n.remove(Tn(e));let r;return r=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&r.isEmpty()?new Zi(null):new Zi(this.value,r)}return this}}get(e){if(Rn(e))return this.value;{const t=In(e),n=this.children.get(t);return n?n.get(Tn(e)):null}}setTree(e,t){if(Rn(e))return t;{const n=In(e),i=(this.children.get(n)||new Zi(null)).setTree(Tn(e),t);let r;return r=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new Zi(this.value,r)}}fold(e){return this.fold_(bn(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((i,r)=>{n[i]=r.fold_(Pn(e,i),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,bn(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(Rn(e))return null;{const i=In(e),r=this.children.get(i);return r?r.findOnPath_(Tn(e),Pn(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,bn(),t)}foreachOnPath_(e,t,n){if(Rn(e))return this;{this.value&&n(t,this.value);const i=In(e),r=this.children.get(i);return r?r.foreachOnPath_(Tn(e),Pn(t,i),n):new Zi(null)}}foreach(e){this.foreach_(bn(),e)}foreach_(e,t){this.children.inorderTraversal(((n,i)=>{i.foreach_(Pn(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}class er{constructor(e){this.writeTree_=e}static empty(){return new er(new Zi(null))}}function tr(e,t,n){if(Rn(t))return new er(new Zi(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const r=i.path;let s=i.value;const o=Nn(r,t);return s=s.updateChild(o,n),new er(e.writeTree_.set(r,s))}{const i=new Zi(n),r=e.writeTree_.setTree(t,i);return new er(r)}}}function nr(e,t,n){let i=e;return Wt(n,((e,n)=>{i=tr(i,Pn(t,e),n)})),i}function ir(e,t){if(Rn(t))return er.empty();{const n=e.writeTree_.setTree(t,new Zi(null));return new er(n)}}function rr(e,t){return null!=sr(e,t)}function sr(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(Nn(n.path,t)):null}function or(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(ii,((e,n)=>{t.push(new jn(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new jn(e,n.value))})),t}function ar(e,t){if(Rn(t))return e;{const n=sr(e,t);return new er(null!=n?new Zi(n):e.writeTree_.subtree(t))}}function cr(e){return e.writeTree_.isEmpty()}function lr(e,t){return hr(bn(),e.writeTree_,t)}function hr(e,t,i){if(null!=t.value)return i.updateChild(e,t.value);{let r=null;return t.children.inorderTraversal(((t,s)=>{".priority"===t?(n(null!==s.value,"Priority writes must always be leaf nodes"),r=s.value):i=hr(Pn(e,t),s,i)})),i.getChild(e).isEmpty()||null===r||(i=i.updateChild(Pn(e,".priority"),r)),i}}function ur(e,t){return Ir(t,e)}function dr(e,t){if(e.snap)return Dn(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&Dn(Pn(e.path,n),t))return!0;return!1}function pr(e){return e.visible}function fr(e,t,n){let r=er.empty();for(let s=0;s{i=i.updateImmediateChild(e,t)})),i;if(n){const r=ar(e.visibleWrites,t);return n.forEachChild(ii,((e,t)=>{const n=lr(ar(r,new wn(e)),t);i=i.updateImmediateChild(e,n)})),or(r).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}return or(ar(e.visibleWrites,t)).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}(e.writeTree,e.treePath,t)}function vr(e,t,i,r){return function(e,t,i,r,s){n(r||s,"Either existingEventSnap or existingServerSnap must exist");const o=Pn(t,i);if(rr(e.visibleWrites,o))return null;{const t=ar(e.visibleWrites,o);return cr(t)?s.getChild(i):lr(t,s.getChild(i))}}(e.writeTree,e.treePath,t,i,r)}function yr(e,t){return function(e,t){return sr(e.visibleWrites,t)}(e.writeTree,Pn(e.treePath,t))}function wr(e,t,n){return function(e,t,n,i){const r=Pn(t,n),s=sr(e.visibleWrites,r);return null!=s?s:i.isCompleteForChild(n)?lr(ar(e.visibleWrites,r),i.getNode().getImmediateChild(n)):null}(e.writeTree,e.treePath,t,n)}function br(e,t){return Ir(Pn(e.treePath,t),e.writeTree)}function Ir(e,t){return{treePath:e,writeTree:t}}class Cr{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,r=e.childName;n("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),n(".priority"!==r,"Only non-priority child changes can be tracked.");const s=this.changeMap.get(r);if(s){const n=s.type;if("child_added"===t&&"child_removed"===n)this.changeMap.set(r,wi(r,e.snapshotNode,s.snapshotNode));else if("child_removed"===t&&"child_added"===n)this.changeMap.delete(r);else if("child_removed"===t&&"child_changed"===n)this.changeMap.set(r,yi(r,s.oldSnap));else if("child_changed"===t&&"child_added"===n)this.changeMap.set(r,vi(r,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==n)throw i("Illegal combination of changes: "+e+" occurred after "+s);this.changeMap.set(r,wi(r,e.snapshotNode,s.oldSnap))}}else this.changeMap.set(r,e)}getChanges(){return Array.from(this.changeMap.values())}}const Tr=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class Er{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new zi(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return wr(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Qi(this.viewCache_),r=function(e,t,n,i,r,s){return function(e,t,n,i,r,s,o){let a;const c=ar(e.visibleWrites,t),l=sr(c,bn());if(null!=l)a=l;else{if(null==n)return[];a=lr(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=s?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let c=n.getNext();for(;c&&e.length1)return t;const r=Tn(n),s=c.getNode().getImmediateChild(e).updateChild(r,i);l=".priority"===e?h.updatePriority(c.getNode(),s):h.updateChild(c.getNode(),e,s,r,Tr,null)}const u=Yi(t,l,c.isFullyInitialized()||Rn(n),h.filtersNodes());return kr(e,u,n,r,new Er(r,u,s),a)}function Pr(e,t,n,i,r,s,o){const a=t.eventCache;let c,l;const h=new Er(r,t,s);if(Rn(n))l=e.filter.updateFullNode(t.eventCache.getNode(),i,o),c=Gi(t,l,!0,e.filter.filtersNodes());else{const r=In(n);if(".priority"===r)l=e.filter.updatePriority(t.eventCache.getNode(),i),c=Gi(t,l,a.isFullyInitialized(),a.isFiltered());else{const s=Tn(n),l=a.getNode().getImmediateChild(r);let u;if(Rn(s))u=i;else{const e=h.getCompleteChild(r);u=null!=e?".priority"===En(s)&&e.getChild(Sn(s)).isEmpty()?e:e.updateChild(s,i):ui.EMPTY_NODE}c=l.equals(u)?t:Gi(t,e.filter.updateChild(a.getNode(),r,u,s,h,o),a.isFullyInitialized(),e.filter.filtersNodes())}}return c}function Rr(e,t){return e.eventCache.isCompleteForChild(t)}function Nr(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function Ar(e,t,n,i,r,s,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c,l=t;c=Rn(n)?i:new Zi(null).setTree(n,i);const h=t.serverCache.getNode();return c.children.inorderTraversal(((n,i)=>{if(h.hasChild(n)){const c=Nr(0,t.serverCache.getNode().getImmediateChild(n),i);l=Sr(e,l,new wn(n),c,r,s,o,a)}})),c.children.inorderTraversal(((n,i)=>{const c=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!h.hasChild(n)&&!c){const c=Nr(0,t.serverCache.getNode().getImmediateChild(n),i);l=Sr(e,l,new wn(n),c,r,s,o,a)}})),l}class Or{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,i=new bi(n.getIndex()),r=(s=n).loadsAllData()?new bi(s.getIndex()):s.hasLimit()?new Ci(s):new Ii(s);var s;this.processor_=function(e){return{filter:e}}(r);const o=t.serverCache,a=t.eventCache,c=i.updateFullNode(ui.EMPTY_NODE,o.getNode(),null),l=r.updateFullNode(ui.EMPTY_NODE,a.getNode(),null),h=new zi(c,o.isFullyInitialized(),i.filtersNodes()),u=new zi(l,a.isFullyInitialized(),r.filtersNodes());this.viewCache_=Ki(u,h),this.eventGenerator_=new Hi(this.query_)}get query(){return this.query_}}function Dr(e,t){const n=Qi(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!Rn(t)&&!n.getImmediateChild(In(t)).isEmpty())?n.getChild(t):null}function xr(e){return 0===e.eventRegistrations_.length}function Lr(e,t,i){const r=[];if(i){n(null==t,"A cancel should cancel all event registrations.");const s=e.query._path;e.eventRegistrations_.forEach((e=>{const t=e.createCancelEvent(i,s);t&&r.push(t)}))}if(t){let n=[];for(let i=0;i{const l=Pn(n,i);Rr(t,In(l))&&(a=Pr(e,a,l,c,r,s,o))})),i.foreach(((i,c)=>{const l=Pn(n,i);Rr(t,In(l))||(a=Pr(e,a,l,c,r,s,o))})),a}(e,t,i.path,i.children,s,o,a):(n(i.source.fromServer,"Unknown source."),l=i.source.tagged||t.serverCache.isFiltered(),c=Ar(e,t,i.path,i.children,s,o,l,a))}else if(r.type===Ui.ACK_USER_WRITE){const i=r;c=i.revert?function(e,t,i,r,s,o){let a;if(null!=yr(r,i))return t;{const c=new Er(r,t,s),l=t.eventCache.getNode();let h;if(Rn(i)||".priority"===In(i)){let i;if(t.serverCache.isFullyInitialized())i=mr(r,Qi(t));else{const e=t.serverCache.getNode();n(e instanceof ui,"serverChildren would be complete if leaf node"),i=gr(r,e)}h=e.filter.updateFullNode(l,i,o)}else{const n=In(i);let s=wr(r,n,t.serverCache);null==s&&t.serverCache.isCompleteForChild(n)&&(s=l.getImmediateChild(n)),h=null!=s?e.filter.updateChild(l,n,s,Tn(i),c,o):t.eventCache.getNode().hasChild(n)?e.filter.updateChild(l,n,ui.EMPTY_NODE,Tn(i),c,o):l,h.isEmpty()&&t.serverCache.isFullyInitialized()&&(a=mr(r,Qi(t)),a.isLeafNode()&&(h=e.filter.updateFullNode(h,a,o)))}return a=t.serverCache.isFullyInitialized()||null!=yr(r,bn()),Gi(t,h,a,e.filter.filtersNodes())}}(e,t,i.path,s,o,a):function(e,t,n,i,r,s,o){if(null!=yr(r,n))return t;const a=t.serverCache.isFiltered(),c=t.serverCache;if(null!=i.value){if(Rn(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return Sr(e,t,n,c.getNode().getChild(n),r,s,a,o);if(Rn(n)){let i=new Zi(null);return c.getNode().forEachChild(zn,((e,t)=>{i=i.set(new wn(e),t)})),Ar(e,t,n,i,r,s,a,o)}return t}{let l=new Zi(null);return i.foreach(((e,t)=>{const i=Pn(n,e);c.isCompleteForPath(i)&&(l=l.set(e,c.getNode().getChild(i)))})),Ar(e,t,n,l,r,s,a,o)}}(e,t,i.path,i.affectedTree,s,o,a)}else{if(r.type!==Ui.LISTEN_COMPLETE)throw i("Unknown operation type: "+r.type);c=function(e,t,n,i,r){const s=t.serverCache;return kr(e,Yi(t,s.getNode(),s.isFullyInitialized()||Rn(n),s.isFiltered()),n,i,Tr,r)}(e,t,r.path,s,a)}const h=a.getChanges();return function(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const r=i.getNode().isLeafNode()||i.getNode().isEmpty(),s=Ji(e);(n.length>0||!e.eventCache.isFullyInitialized()||r&&!i.getNode().equals(s)||!i.getNode().getPriority().equals(s.getPriority()))&&n.push(gi(Ji(t)))}}(t,c,h),{viewCache:c,changes:h}}(e.processor_,o,t,r,s);var c,l;return c=e.processor_,l=a.viewCache,n(l.eventCache.getNode().isIndexed(c.filter.getIndex()),"Event snap not indexed"),n(l.serverCache.getNode().isIndexed(c.filter.getIndex()),"Server snap not indexed"),n(a.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=a.viewCache,Fr(e,a.changes,a.viewCache.eventCache.getNode(),null)}function Fr(e,t,n,i){const r=i?[i]:e.eventRegistrations_;return function(e,t,n,i){const r=[],s=[];return t.forEach((t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&s.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))})),$i(e,r,"child_removed",t,i,n),$i(e,r,"child_added",t,i,n),$i(e,r,"child_moved",s,i,n),$i(e,r,"child_changed",t,i,n),$i(e,r,"value",t,i,n),r}(e.eventGenerator_,t,n,r)}let Ur,qr;class jr{constructor(){this.views=new Map}}function Wr(e,t,i,r){const s=t.source.queryId;if(null!==s){const o=e.views.get(s);return n(null!=o,"SyncTree gave us an op for an invalid query."),Mr(o,t,i,r)}{let n=[];for(const s of e.views.values())n=n.concat(Mr(s,t,i,r));return n}}function Vr(e,t,n,i,r){const s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=mr(n,r?i:null),s=!1;e?s=!0:i instanceof ui?(e=gr(n,i),s=!1):(e=ui.EMPTY_NODE,s=!1);const o=Ki(new zi(e,s,!1),new zi(i,r,!1));return new Or(t,o)}return o}function Br(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function zr(e,t){let n=null;for(const i of e.views.values())n=n||Dr(i,t);return n}function Hr(e,t){if(t._queryParams.loadsAllData())return Gr(e);{const n=t._queryIdentifier;return e.views.get(n)}}function $r(e,t){return null!=Hr(e,t)}function Kr(e){return null!=Gr(e)}function Gr(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Yr=1;class Jr{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Zi(null),this.pendingWriteTree_={visibleWrites:er.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Qr(e,t,i,r,s){return function(e,t,i,r,s){n(r>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===s&&(s=!0),e.allWrites.push({path:t,snap:i,writeId:r,visible:s}),s&&(e.visibleWrites=tr(e.visibleWrites,t,i)),e.lastWriteId=r}(e.pendingWriteTree_,t,i,r,s),s?rs(e,new Vi({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,i)):[]}function Xr(e,t,i=!1){const r=function(e,t){for(let n=0;ne.writeId===t));n(i>=0,"removeWrite called with nonexistent writeId.");const r=e.allWrites[i];e.allWrites.splice(i,1);let s=r.visible,o=!1,a=e.allWrites.length-1;for(;s&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=i&&dr(t,r.path)?s=!1:Dn(r.path,t.path)&&(o=!0)),a--}return!!s&&(o?(function(e){e.visibleWrites=fr(e.allWrites,pr,bn()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0):(r.snap?e.visibleWrites=ir(e.visibleWrites,r.path):Wt(r.children,(t=>{e.visibleWrites=ir(e.visibleWrites,Pn(r.path,t))})),!0))}(e.pendingWriteTree_,t)){let t=new Zi(null);return null!=r.snap?t=t.set(bn(),!0):Wt(r.children,(e=>{t=t.set(new wn(e),!0)})),rs(e,new ji(r.path,t,i))}return[]}function Zr(e,t,n){return rs(e,new Vi({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function es(e,t,i,r,s=!1){const o=t._path,a=e.syncPointTree_.get(o);let c=[];if(a&&("default"===t._queryIdentifier||$r(a,t))){const l=function(e,t,i,r){const s=t._queryIdentifier,o=[];let a=[];const c=Kr(e);if("default"===s)for(const[t,n]of e.views.entries())a=a.concat(Lr(n,i,r)),xr(n)&&(e.views.delete(t),n.query._queryParams.loadsAllData()||o.push(n.query));else{const t=e.views.get(s);t&&(a=a.concat(Lr(t,i,r)),xr(t)&&(e.views.delete(s),t.query._queryParams.loadsAllData()||o.push(t.query)))}return c&&!Kr(e)&&o.push(new(n(Ur,"Reference.ts has not been loaded"),Ur)(t._repo,t._path)),{removed:o,events:a}}(a,t,i,r);0===a.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(o));const h=l.removed;if(c=l.events,!s){const n=-1!==h.findIndex((e=>e._queryParams.loadsAllData())),i=e.syncPointTree_.findOnPath(o,((e,t)=>Kr(t)));if(n&&!i){const t=e.syncPointTree_.subtree(o);if(!t.isEmpty()){const n=function(e){return e.fold(((e,t,n)=>{if(t&&Kr(t))return[Gr(t)];{let e=[];return t&&(e=Br(t)),Wt(n,((t,n)=>{e=e.concat(n)})),e}}))}(t);for(let t=0;t0&&!r)if(n){const n=null;e.listenProvider_.stopListening(ps(t),n)}else h.forEach((t=>{const n=e.queryToTagMap.get(ls(t));e.listenProvider_.stopListening(ps(t),n)}))}!function(e,t){for(let n=0;n{const n=Nn(e,s);o=o||zr(t,n),a=a||Kr(t)}));let c,l=e.syncPointTree_.get(s);l?(a=a||Kr(l),o=o||zr(l,bn())):(l=new jr,e.syncPointTree_=e.syncPointTree_.set(s,l)),null!=o?c=!0:(c=!1,o=ui.EMPTY_NODE,e.syncPointTree_.subtree(s).foreachChild(((e,t)=>{const n=zr(t,bn());n&&(o=o.updateImmediateChild(e,n))})));const h=$r(l,t);if(!h&&!t._queryParams.loadsAllData()){const i=ls(t);n(!e.queryToTagMap.has(i),"View does not exist, but we have a tag");const r=Yr++;e.queryToTagMap.set(i,r),e.tagToQueryMap.set(r,i)}let u=function(e,t,n,i,r,s){const o=Vr(e,t,i,r,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),function(e,t){e.eventRegistrations_.push(t)}(o,n),function(e,t){const n=e.viewCache_.eventCache,i=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(ii,((e,t)=>{i.push(vi(e,t))})),n.isFullyInitialized()&&i.push(gi(n.getNode())),Fr(e,i,n.getNode(),t)}(o,n)}(l,t,i,ur(e.pendingWriteTree_,s),o,c);if(!h&&!a&&!r){const i=Hr(l,t);u=u.concat(function(e,t,i){const r=t._path,s=cs(e,t),o=as(e,i),a=e.listenProvider_.startListening(ps(t),s,o.hashFn,o.onComplete),c=e.syncPointTree_.subtree(r);if(s)n(!Kr(c.value),"If we're adding a query, it shouldn't be shadowed");else{const t=c.fold(((e,t,n)=>{if(!Rn(e)&&t&&Kr(t))return[Gr(t).query];{let e=[];return t&&(e=e.concat(Br(t).map((e=>e.query)))),Wt(n,((t,n)=>{e=e.concat(n)})),e}}));for(let n=0;n{const i=zr(n,Nn(e,t));if(i)return i}));return _r(i,t,r,n,!0)}function rs(e,t){return ss(t,e.syncPointTree_,null,ur(e.pendingWriteTree_,bn()))}function ss(e,t,n,i){if(Rn(e.path))return os(e,t,n,i);{const r=t.get(bn());null==n&&null!=r&&(n=zr(r,bn()));let s=[];const o=In(e.path),a=e.operationForChild(o),c=t.children.get(o);if(c&&a){const e=n?n.getImmediateChild(o):null,t=br(i,o);s=s.concat(ss(a,c,e,t))}return r&&(s=s.concat(Wr(r,e,i,n))),s}}function os(e,t,n,i){const r=t.get(bn());null==n&&null!=r&&(n=zr(r,bn()));let s=[];return t.children.inorderTraversal(((t,r)=>{const o=n?n.getImmediateChild(t):null,a=br(i,t),c=e.operationForChild(t);c&&(s=s.concat(os(c,r,o,a)))})),r&&(s=s.concat(Wr(r,e,i,n))),s}function as(e,t){const n=t.query,i=cs(e,n);return{hashFn:()=>{const e=function(e){return e.viewCache_.serverCache.getNode()}(t)||ui.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return i?function(e,t,n){const i=hs(e,n);if(i){const n=us(i),r=n.path,s=n.queryId,o=Nn(r,t);return ds(e,r,new Wi(qi(s),o))}return[]}(e,n._path,i):function(e,t){return rs(e,new Wi({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const i=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const i=new Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}(t,n);return es(e,n,null,i)}}}}function cs(e,t){const n=ls(t);return e.queryToTagMap.get(n)}function ls(e){return e._path.toString()+"$"+e._queryIdentifier}function hs(e,t){return e.tagToQueryMap.get(t)}function us(e){const t=e.indexOf("$");return n(-1!==t&&t{const r=Is(i,t.getImmediateChild(e),n);r!==i&&(s=s.updateImmediateChild(e,r))})),s}}class Cs{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function Ts(e,t){let n=t instanceof wn?t:new wn(t),i=e,r=In(n);for(;null!==r;){const e=R(i.node.children,r)||{children:{},childCount:0};i=new Cs(r,i,e),n=Tn(n),r=In(n)}return i}function Es(e){return e.node.value}function ks(e,t){e.node.value=t,As(e)}function Ss(e){return e.node.childCount>0}function Ps(e,t){Wt(e.node.children,((n,i)=>{t(new Cs(n,e,i))}))}function Rs(e,t,n,i){n&&!i&&t(e),Ps(e,(e=>{Rs(e,t,!0,i)})),n&&i&&t(e)}function Ns(e){return new wn(null===e.parent?e.name:Ns(e.parent)+"/"+e.name)}function As(e){null!==e.parent&&function(e,t,n){const i=function(e){return void 0===Es(e)&&!Ss(e)}(n),r=P(e.node.children,t);i&&r?(delete e.node.children[t],e.node.childCount--,As(e)):i||r||(e.node.children[t]=n.node,e.node.childCount++,As(e))}(e.parent,e.name,e)}const Os=/[\[\].#$\/\u0000-\u001F\u007F]/,Ds=/[\[\].#$\u0000-\u001F\u007F]/,xs=10485760,Ls=function(e){return"string"==typeof e&&0!==e.length&&!Os.test(e)},Ms=function(e){return"string"==typeof e&&0!==e.length&&!Ds.test(e)},Fs=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Dt(e)||e&&"object"==typeof e&&P(e,".sv")},Us=function(e,t,n,i){i&&void 0===t||qs(V(e,"value"),t,n)},qs=function(e,t,n){const i=n instanceof wn?new xn(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+Mn(i));if("function"==typeof t)throw new Error(e+"contains a function "+Mn(i)+" with contents = "+t.toString());if(Dt(t))throw new Error(e+"contains "+t.toString()+" "+Mn(i));if("string"==typeof t&&t.length>xs/3&&H(t)>xs)throw new Error(e+"contains a string greater than "+xs+" utf8 bytes "+Mn(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,r=!1;if(Wt(t,((t,s)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(r=!0,!Ls(t)))throw new Error(e+" contains an invalid key ("+t+") "+Mn(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=H(t),Ln(e)}(i,t),qs(e,s,i),function(e){const t=e.parts_.pop();e.byteLength_-=H(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)})),n&&r)throw new Error(e+' contains ".value" child '+Mn(i)+" in addition to actual children.")}},js=function(e,t,n,i){if(i&&void 0===t)return;const r=V(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(r+" must be an object containing the children to replace.");const s=[];Wt(t,((e,t)=>{const i=new wn(e);if(qs(r,t,Pn(n,i)),".priority"===En(i)&&!Fs(t))throw new Error(r+"contains an invalid value for '"+i.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(i)})),function(e,t){let n,i;for(n=0;nOn(e,t)))}function Js(e,t,n){Gs(e,n),Qs(e,(e=>Dn(e,t)||Dn(t,e)))}function Qs(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i=0)e.server_=new Ni(e.repoInfo_,((t,n,i,r)=>{so(e,t,n,i,r)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>oo(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{k(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new qn(e.repoInfo_,t,((t,n,i,r)=>{so(e,t,n,i,r)}),(t=>{oo(e,t)}),(t=>{!function(e,t){Wt(t,((t,n)=>{ao(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function(t,n){const i=t.toString();return on[i]||(on[i]=new Fi(e.stats_,e.server_)),on[i]}(e.repoInfo_),e.infoData_=new Ai,e.infoSyncTree_=new Jr({startListening:(t,n,i,r)=>{let s=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=Zr(e.infoSyncTree_,t._path,o),setTimeout((()=>{r("ok")}),0)),s},stopListening:()=>{}}),ao(e,"connected",!1),e.serverSyncTree_=new Jr({startListening:(t,n,i,r)=>(e.server_.listen(t,i,n,((n,i)=>{const s=r(n,i);Js(e.eventQueue_,t._path,s)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function io(e){const t=e.infoData_.getNode(new wn(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function ro(e){return ms({timestamp:io(e)})}function so(e,t,n,i,r){e.dataUpdateCount++;const s=new wn(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(r)if(i){const t=A(n,(e=>fi(e)));o=function(e,t,n,i){const r=hs(e,i);if(r){const i=us(r),s=i.path,o=i.queryId,a=Nn(s,t),c=Zi.fromObject(n);return ds(e,s,new Bi(qi(o),a,c))}return[]}(e.serverSyncTree_,s,t,r)}else{const t=fi(n);o=ts(e.serverSyncTree_,s,t,r)}else if(i){const t=A(n,(e=>fi(e)));o=function(e,t,n){const i=Zi.fromObject(n);return rs(e,new Bi({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,i))}(e.serverSyncTree_,s,t)}else{const t=fi(n);o=Zr(e.serverSyncTree_,s,t)}let a=s;o.length>0&&(a=yo(e,s)),Js(e.eventQueue_,a,o)}function oo(e,t){ao(e,"connected",t),!1===t&&function(e){_o(e,"onDisconnectEvents");const t=ro(e),n=Oi();Li(e.onDisconnect_,bn(),((i,r)=>{const s=ws(i,r,e.serverSyncTree_,t);Di(n,i,s)}));let i=[];Li(n,bn(),((t,n)=>{i=i.concat(Zr(e.serverSyncTree_,t,n));const r=To(e,t);yo(e,r)})),e.onDisconnect_=Oi(),Js(e.eventQueue_,bn(),i)}(e)}function ao(e,t,n){const i=new wn("/.info/"+t),r=fi(n);e.infoData_.updateSnapshot(i,r);const s=Zr(e.infoSyncTree_,i,r);Js(e.eventQueue_,i,s)}function co(e){return e.nextWriteId_++}function lo(e,t,n,i,r){_o(e,"set",{path:t.toString(),value:n,priority:i});const s=ro(e),o=fi(n,i),a=is(e.serverSyncTree_,t),c=bs(o,a,s),l=co(e),h=Qr(e.serverSyncTree_,t,c,l,!0);Gs(e.eventQueue_,h),e.server_.put(t.toString(),o.val(!0),((n,i)=>{const s="ok"===n;s||Ot("set at "+t+" failed: "+n);const o=Xr(e.serverSyncTree_,l,!s);Js(e.eventQueue_,t,o),mo(0,r,n,i)}));const u=To(e,t);yo(e,u),Js(e.eventQueue_,u,[])}function ho(e,t,n){e.server_.onDisconnectCancel(t.toString(),((i,r)=>{"ok"===i&&xi(e.onDisconnect_,t),mo(0,n,i,r)}))}function uo(e,t,n,i){const r=fi(n);e.server_.onDisconnectPut(t.toString(),r.val(!0),((n,s)=>{"ok"===n&&Di(e.onDisconnect_,t,r),mo(0,i,n,s)}))}function po(e,t,n){let i;i=".info"===In(t._path)?es(e.infoSyncTree_,t,n):es(e.serverSyncTree_,t,n),Ys(e.eventQueue_,t._path,i)}function fo(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Zs)}function _o(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),Pt(n,...t)}function mo(e,t,n,i){t&&Ht((()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let r=e;i&&(r+=": "+i);const s=new Error(r);s.code=e,t(s)}}))}function go(e,t,n){return is(e.serverSyncTree_,t,n)||ui.EMPTY_NODE}function vo(e,t=e.transactionQueueTree_){if(t||Co(e,t),Es(t)){const i=bo(e,t);n(i.length>0,"Sending zero length transaction queue"),i.every((e=>0===e.status))&&function(e,t,i){const r=i.map((e=>e.currentWriteId)),s=go(e,t,r);let o=s;const a=s.hash();for(let e=0;e{_o(e,"transaction put response",{path:l.toString(),status:n});let r=[];if("ok"===n){const n=[];for(let t=0;ti[t].onComplete(null,!0,i[t].currentOutputSnapshotResolved))),i[t].unwatcher();Co(e,Ts(e.transactionQueueTree_,t)),vo(e,e.transactionQueueTree_),Js(e.eventQueue_,t,r);for(let e=0;e{vo(e,t)}))}function yo(e,t){const i=wo(e,t),r=Ns(i);return function(e,t,i){if(0===t.length)return;const r=[];let s=[];const o=t.filter((e=>0===e.status)).map((e=>e.currentWriteId));for(let c=0;c=eo)d=!0,u="maxretry",s=s.concat(Xr(e.serverSyncTree_,l.currentWriteId,!0));else{const n=go(e,l.path,o);l.currentInputSnapshot=n;const i=t[c].update(n.val());if(void 0!==i){qs("transaction failed: Data returned ",i,l.path);let t=fi(i);"object"==typeof i&&null!=i&&P(i,".priority")||(t=t.updatePriority(n.getPriority()));const r=l.currentWriteId,a=ro(e),c=bs(t,n,a);l.currentOutputSnapshotRaw=t,l.currentOutputSnapshotResolved=c,l.currentWriteId=co(e),o.splice(o.indexOf(r),1),s=s.concat(Qr(e.serverSyncTree_,l.path,c,l.currentWriteId,l.applyLocally)),s=s.concat(Xr(e.serverSyncTree_,r,!0))}else d=!0,u="nodata",s=s.concat(Xr(e.serverSyncTree_,l.currentWriteId,!0))}Js(e.eventQueue_,i,s),s=[],d&&(t[c].status=2,a=t[c].unwatcher,setTimeout(a,Math.floor(0)),t[c].onComplete&&("nodata"===u?r.push((()=>t[c].onComplete(null,!1,t[c].currentInputSnapshot))):r.push((()=>t[c].onComplete(new Error(u),!1,null)))))}var a;Co(e,e.transactionQueueTree_);for(let e=0;ee.order-t.order)),n}function Io(e,t,n){const i=Es(t);if(i)for(let e=0;e{Io(e,t,n)}))}function Co(e,t){const n=Es(t);if(n){let e=0;for(let t=0;t0?n:void 0)}Ps(t,(t=>{Co(e,t)}))}function To(e,t){const n=Ns(wo(e,t)),i=Ts(e.transactionQueueTree_,t);return function(e,t,n){let i=e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}}(i,(t=>{Eo(e,t)})),Eo(e,i),Rs(i,(t=>{Eo(e,t)})),n}function Eo(e,t){const i=Es(t);if(i){const r=[];let s=[],o=-1;for(let t=0;t.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||At("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Ot("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const r="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new tn(n.host,n.secure,i,r,t,"",i!==n.subdomain),path:new wn(n.pathString)}},So=function(e){let t="",n="",i="",r="",s="",o=!0,a="https",c=443;if("string"==typeof e){let l=e.indexOf("//");l>=0&&(a=e.substring(0,l-1),e=e.substring(l+2));let h=e.indexOf("/");-1===h&&(h=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(h,u)),h0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}(e.substring(h,u)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):Ot(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,u)));l=t.indexOf(":"),l>=0?(o="https"===a||"wss"===a,c=parseInt(t.substring(l+1),10)):l=t.length;const p=t.slice(0,l);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{const e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),s=i}"ns"in d&&(s=d.ns)}return{host:t,port:c,domain:n,subdomain:i,secure:o,scheme:a,pathString:r,namespace:s}},Po="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Ro=function(){let e=0;const t=[];return function(i){const r=i===e;let s;e=i;const o=new Array(8);for(s=7;s>=0;s--)o[s]=Po.charAt(i%64),i=Math.floor(i/64);n(0===i,"Cannot push at time == 0");let a=o.join("");if(r){for(s=11;s>=0&&63===t[s];s--)t[s]=0;t[s]++}else for(s=0;s<12;s++)t[s]=Math.floor(64*Math.random());for(s=0;s<12;s++)a+=Po.charAt(t[s]);return n(20===a.length,"nextPushId: Length should be 20."),a}}();class No{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+k(this.snapshot.exportVal())}}class Ao{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class Oo{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return n(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class Do{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new p;return ho(this._repo,this._path,e.wrapCallback((()=>{}))),e.promise}remove(){Hs("OnDisconnect.remove",this._path);const e=new p;return uo(this._repo,this._path,null,e.wrapCallback((()=>{}))),e.promise}set(e){Hs("OnDisconnect.set",this._path),Us("OnDisconnect.set",e,this._path,!1);const t=new p;return uo(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}setWithPriority(e,t){Hs("OnDisconnect.setWithPriority",this._path),Us("OnDisconnect.setWithPriority",e,this._path,!1),Ws("OnDisconnect.setWithPriority",t,!1);const n=new p;return function(e,t,n,i,r){const s=fi(n,i);e.server_.onDisconnectPut(t.toString(),s.val(!0),((n,i)=>{"ok"===n&&Di(e.onDisconnect_,t,s),mo(0,r,n,i)}))}(this._repo,this._path,e,t,n.wrapCallback((()=>{}))),n.promise}update(e){Hs("OnDisconnect.update",this._path),js("OnDisconnect.update",e,this._path,!1);const t=new p;return function(e,t,n,i){if(N(n))return Pt("onDisconnect().update() called with empty data. Don't do anything."),void mo(0,i,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,((r,s)=>{"ok"===r&&Wt(n,((n,i)=>{const r=fi(i);Di(e.onDisconnect_,Pn(t,n),r)})),mo(0,i,r,s)}))}(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}}class xo{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return Rn(this._path)?null:En(this._path)}get ref(){return new Uo(this._repo,this._path)}get _queryIdentifier(){const e=Ri(this._queryParams),t=qt(e);return"{}"===t?"default":t}get _queryObject(){return Ri(this._queryParams)}isEqual(e){if(!((e=$(e))instanceof xo))return!1;const t=this._repo===e._repo,n=On(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;ne(new qo(n,Vo(this.ref,t),ii))))}hasChild(e){const t=new wn(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function jo(e,t){return(e=$(e))._checkNotDeleted("ref"),void 0!==t?Vo(e._root,t):e._root}function Wo(e,t){(e=$(e))._checkNotDeleted("refFromURL");const n=ko(t,e._repo.repoInfo_.nodeAdmin);$s("refFromURL",n);const i=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||i.host===e._repo.repoInfo_.host||At("refFromURL: Host name does not match the current database: (found "+i.host+" but expected "+e._repo.repoInfo_.host+")"),jo(e,n.path.toString())}function Vo(e,t){return null===In((e=$(e))._path)?zs("child","path",t,!1):Bs("child","path",t,!1),new Uo(e._repo,Pn(e._path,t))}function Bo(e,t){e=$(e),Hs("set",e._path),Us("set",t,e._path,!1);const n=new p;return lo(e._repo,e._path,t,null,n.wrapCallback((()=>{}))),n.promise}function zo(e,t){js("update",t,e._path,!1);const i=new p;return function(e,t,i,r){_o(e,"update",{path:t.toString(),value:i});let s=!0;const o=ro(e),a={};if(Wt(i,((n,i)=>{s=!1,a[n]=ws(Pn(t,n),fi(i),e.serverSyncTree_,o)})),s)Pt("update() called with empty data. Don't do anything."),mo(0,r,"ok",void 0);else{const s=co(e),o=function(e,t,i,r){!function(e,t,i,r){n(r>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:i,writeId:r,visible:!0}),e.visibleWrites=nr(e.visibleWrites,t,i),e.lastWriteId=r}(e.pendingWriteTree_,t,i,r);const s=Zi.fromObject(i);return rs(e,new Bi({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,s))}(e.serverSyncTree_,t,a,s);Gs(e.eventQueue_,o),e.server_.merge(t.toString(),i,((n,i)=>{const o="ok"===n;o||Ot("update at "+t+" failed: "+n);const a=Xr(e.serverSyncTree_,s,!o),c=a.length>0?yo(e,t):t;Js(e.eventQueue_,c,a),mo(0,r,n,i)})),Wt(i,(n=>{const i=To(e,Pn(t,n));yo(e,i)})),Js(e.eventQueue_,t,[])}}(e._repo,e._path,t,i.wrapCallback((()=>{}))),i.promise}function Ho(e){e=$(e);const t=new Oo((()=>{})),n=new $o(t);return function(e,t,n){const i=function(e,t){const n=t._path;let i=null;e.syncPointTree_.foreachOnPath(n,((e,t)=>{const r=Nn(e,n);i=i||zr(t,r)}));let r=e.syncPointTree_.get(n);r?i=i||zr(r,bn()):(r=new jr,e.syncPointTree_=e.syncPointTree_.set(n,r));const s=null!=i,o=s?new zi(i,!0,!1):null;return Ji(Vr(r,t,ur(e.pendingWriteTree_,t._path),s?o.getNode():ui.EMPTY_NODE,s).viewCache_)}(e.serverSyncTree_,t);return null!=i?Promise.resolve(i):e.server_.get(t).then((i=>{const r=fi(i).withIndex(t._queryParams.getIndex());let s;if(ns(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())s=Zr(e.serverSyncTree_,t._path,r);else{const n=cs(e.serverSyncTree_,t);s=ts(e.serverSyncTree_,t._path,r,n)}return Js(e.eventQueue_,t._path,s),es(e.serverSyncTree_,t,n,null,!0),r}),(n=>(_o(e,"get for query "+k(t)+" failed: "+n),Promise.reject(new Error(n)))))}(e._repo,e,n).then((t=>new qo(t,new Uo(e._repo,e._path),e._queryParams.getIndex())))}class $o{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new No("value",this,new qo(e.snapshotNode,new Uo(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new Ao(this,e,t):null}matches(e){return e instanceof $o&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Ko{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new Ao(this,e,t):null}createEvent(e,t){n(null!=e.childName,"Child events should have a childName.");const i=Vo(new Uo(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new No(e.type,this,new qo(e.snapshotNode,i,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Ko&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function Go(e,t,n,i,r){let s;if("object"==typeof i&&(s=void 0,r=i),"function"==typeof i&&(s=i),r&&r.onlyOnce){const t=n,i=(n,i)=>{po(e._repo,e,a),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}const o=new Oo(n,s||void 0),a="value"===t?new $o(o):new Ko(t,o);return function(e,t,n){let i;i=".info"===In(t._path)?ns(e.infoSyncTree_,t,n):ns(e.serverSyncTree_,t,n),Ys(e.eventQueue_,t._path,i)}(e._repo,e,a),()=>po(e._repo,e,a)}function Yo(e,t,n,i){return Go(e,"value",t,n,i)}function Jo(e,t,n,i){return Go(e,"child_added",t,n,i)}function Qo(e,t,n,i){return Go(e,"child_changed",t,n,i)}function Xo(e,t,n,i){return Go(e,"child_moved",t,n,i)}function Zo(e,t,n,i){return Go(e,"child_removed",t,n,i)}function ea(e,t,n){let i=null;const r=n?new Oo(n):null;"value"===t?i=new $o(r):t&&(i=new Ko(t,r)),po(e._repo,e,i)}class ta{}class na extends ta{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){Us("endAt",this._value,e._path,!0);const t=ki(e._queryParams,this._value,this._key);if(Fo(t),Mo(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new xo(e._repo,e._path,t,e._orderByCalled)}}class ia extends ta{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){Us("endBefore",this._value,e._path,!1);const t=function(e,t,n){let i;return i=e.index_===zn||n?ki(e,t,n):ki(e,t,xt),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(Fo(t),Mo(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new xo(e._repo,e._path,t,e._orderByCalled)}}class ra extends ta{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){Us("startAt",this._value,e._path,!0);const t=Ei(e._queryParams,this._value,this._key);if(Fo(t),Mo(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new xo(e._repo,e._path,t,e._orderByCalled)}}class sa extends ta{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){Us("startAfter",this._value,e._path,!1);const t=function(e,t,n){let i;return i=e.index_===zn||n?Ei(e,t,n):Ei(e,t,Lt),i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(Fo(t),Mo(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new xo(e._repo,e._path,t,e._orderByCalled)}}class oa extends ta{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new xo(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class aa extends ta{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new xo(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class ca extends ta{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){Lo(e,"orderByChild");const t=new wn(this._path);if(Rn(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new _i(t),i=Si(e._queryParams,n);return Mo(i),new xo(e._repo,e._path,i,!0)}}class la extends ta{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){Lo(e,"orderByKey");const t=Si(e._queryParams,zn);return Mo(t),new xo(e._repo,e._path,t,!0)}}class ha extends ta{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){Lo(e,"orderByPriority");const t=Si(e._queryParams,ii);return Mo(t),new xo(e._repo,e._path,t,!0)}}class ua extends ta{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){Lo(e,"orderByValue");const t=Si(e._queryParams,mi);return Mo(t),new xo(e._repo,e._path,t,!0)}}class da extends ta{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(Us("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new na(this._value,this._key)._apply(new ra(this._value,this._key)._apply(e))}}function pa(e,...t){let n=$(e);for(const e of t)n=e._apply(n);return n}!function(e){n(!Ur,"__referenceConstructor has already been defined"),Ur=e}(Uo),function(e){n(!qr,"__referenceConstructor has already been defined"),qr=e}(Uo);const fa={};function _a(e,t,n,i,r){let s=i||e.options.databaseURL;void 0===s&&(e.options.projectId||At("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Pt("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o,a,c=ko(s,r),l=c.repoInfo;"undefined"!=typeof process&&process.env&&(a=process.env.FIREBASE_DATABASE_EMULATOR_HOST),a?(o=!0,s=`http://${a}?ns=${l.namespace}`,c=ko(s,r),l=c.repoInfo):o=!c.repoInfo.secure;const h=r&&o?new Yt(Yt.OWNER):new Gt(e.name,e.options,t);$s("Invalid Firebase Database URL",c),Rn(c.path)||At("Database URL must point to the root of a Firebase Database (not including a child path).");const u=function(e,t,n,i){let r=fa[t.name];r||(r={},fa[t.name]=r);let s=r[e.toURLString()];return s&&At("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),s=new to(e,false,n,i),r[e.toURLString()]=s,s}(l,e,h,new Kt(e.name,n));return new ma(u,e)}class ma{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(no(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Uo(this._repo,bn())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=fa[t];n&&n[e.key]===e||At(`Database ${t}(${e.repoInfo_}) has already been deleted.`),fo(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&At("Cannot call "+e+" on a deleted database.")}}function ga(){fn.IS_TRANSPORT_INITIALIZED&&Ot("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function va(){ga(),hn.forceDisallow()}function ya(){ga(),pn.forceDisallow(),hn.forceAllow()}class wa{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function ba(e,t,i){var r;if(e=$(e),Hs("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const s=null===(r=null==i?void 0:i.applyLocally)||void 0===r||r,o=new p,a=Yo(e,(()=>{}));return function(t,i,r,s,a,c){_o(t,"transaction on "+i);const l={path:i,update:r,onComplete:(t,n,i)=>{let r=null;t?o.reject(t):(r=new qo(i,new Uo(e._repo,e._path),ii),o.resolve(new wa(n,r)))},status:null,order:It(),applyLocally:c,retryCount:0,unwatcher:a,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},h=go(t,i,void 0);l.currentInputSnapshot=h;const u=l.update(h.val());if(void 0===u)l.unwatcher(),l.currentOutputSnapshotRaw=null,l.currentOutputSnapshotResolved=null,l.onComplete&&l.onComplete(null,!1,l.currentInputSnapshot);else{qs("transaction failed: Data returned ",u,l.path),l.status=0;const e=Ts(t.transactionQueueTree_,i),r=Es(e)||[];let s;r.push(l),ks(e,r),"object"==typeof u&&null!==u&&P(u,".priority")?(s=R(u,".priority"),n(Fs(s),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):s=(is(t.serverSyncTree_,i)||ui.EMPTY_NODE).getPriority().val();const o=ro(t),a=fi(u,s),c=bs(a,h,o);l.currentOutputSnapshotRaw=a,l.currentOutputSnapshotResolved=c,l.currentWriteId=co(t);const d=Qr(t.serverSyncTree_,i,c,l.currentWriteId,l.applyLocally);Js(t.eventQueue_,i,d),vo(t,t.transactionQueueTree_)}}(e._repo,e._path,t,0,a,s),o.promise}qn.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},qn.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},_t(We),Oe(new K("database",((e,{instanceIdentifier:t})=>_a(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),Ke(dt,pt,void 0),Ke(dt,pt,"esm2017");const Ia=new ie("@firebase/database-compat"),Ca=function(e){const t="FIREBASE WARNING: "+e;Ia.warn(t)};class Ta{constructor(e){this._delegate=e}cancel(e){W("OnDisconnect.cancel",0,1,arguments.length),B("OnDisconnect.cancel","onComplete",e,!0);const t=this._delegate.cancel();return e&&t.then((()=>e(null)),(t=>e(t))),t}remove(e){W("OnDisconnect.remove",0,1,arguments.length),B("OnDisconnect.remove","onComplete",e,!0);const t=this._delegate.remove();return e&&t.then((()=>e(null)),(t=>e(t))),t}set(e,t){W("OnDisconnect.set",1,2,arguments.length),B("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then((()=>t(null)),(e=>t(e))),n}setWithPriority(e,t,n){W("OnDisconnect.setWithPriority",2,3,arguments.length),B("OnDisconnect.setWithPriority","onComplete",n,!0);const i=this._delegate.setWithPriority(e,t);return n&&i.then((()=>n(null)),(e=>n(e))),i}update(e,t){if(W("OnDisconnect.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let n=0;nt(null)),(e=>t(e))),n}}class Ea{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return W("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class ka{constructor(e,t){this._database=e,this._delegate=t}val(){return W("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return W("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return W("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return W("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return W("DataSnapshot.child",0,1,arguments.length),e=String(e),Bs("DataSnapshot.child","path",e,!1),new ka(this._database,this._delegate.child(e))}hasChild(e){return W("DataSnapshot.hasChild",1,1,arguments.length),Bs("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return W("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(e){return W("DataSnapshot.forEach",1,1,arguments.length),B("DataSnapshot.forEach","action",e,!1),this._delegate.forEach((t=>e(new ka(this._database,t))))}hasChildren(){return W("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return W("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return W("DataSnapshot.ref",0,0,arguments.length),new Pa(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class Sa{constructor(e,t){this.database=e,this._delegate=t}on(e,t,n,i){var r;W("Query.on",2,4,arguments.length),B("Query.on","callback",t,!1);const s=Sa.getCancelAndContextArgs_("Query.on",n,i),o=(e,n)=>{t.call(s.context,new ka(this.database,e),n)};o.userCallback=t,o.context=s.context;const a=null===(r=s.cancel)||void 0===r?void 0:r.bind(s.context);switch(e){case"value":return Yo(this._delegate,o,a),t;case"child_added":return Jo(this._delegate,o,a),t;case"child_removed":return Zo(this._delegate,o,a),t;case"child_changed":return Qo(this._delegate,o,a),t;case"child_moved":return Xo(this._delegate,o,a),t;default:throw new Error(V("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){if(W("Query.off",0,3,arguments.length),function(e,t,n){if(void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(V("Query.off","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}(0,e),B("Query.off","callback",t,!0),z("Query.off","context",n,!0),t){const i=()=>{};i.userCallback=t,i.context=n,ea(this._delegate,e,i)}else ea(this._delegate,e)}get(){return Ho(this._delegate).then((e=>new ka(this.database,e)))}once(e,t,n,i){W("Query.once",1,4,arguments.length),B("Query.once","callback",t,!0);const r=Sa.getCancelAndContextArgs_("Query.once",n,i),s=new p,o=(e,n)=>{const i=new ka(this.database,e);t&&t.call(r.context,i,n),s.resolve(i)};o.userCallback=t,o.context=r.context;const a=e=>{r.cancel&&r.cancel.call(r.context,e),s.reject(e)};switch(e){case"value":Yo(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":Jo(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":Zo(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":Qo(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":Xo(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(V("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return W("Query.limitToFirst",1,1,arguments.length),new Sa(this.database,pa(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new oa(e)}(e)))}limitToLast(e){return W("Query.limitToLast",1,1,arguments.length),new Sa(this.database,pa(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new aa(e)}(e)))}orderByChild(e){return W("Query.orderByChild",1,1,arguments.length),new Sa(this.database,pa(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Bs("orderByChild","path",e,!1),new ca(e)}(e)))}orderByKey(){return W("Query.orderByKey",0,0,arguments.length),new Sa(this.database,pa(this._delegate,new la))}orderByPriority(){return W("Query.orderByPriority",0,0,arguments.length),new Sa(this.database,pa(this._delegate,new ha))}orderByValue(){return W("Query.orderByValue",0,0,arguments.length),new Sa(this.database,pa(this._delegate,new ua))}startAt(e=null,t){return W("Query.startAt",0,2,arguments.length),new Sa(this.database,pa(this._delegate,function(e=null,t){return Vs("startAt","key",t,!0),new ra(e,t)}(e,t)))}startAfter(e=null,t){return W("Query.startAfter",0,2,arguments.length),new Sa(this.database,pa(this._delegate,function(e,t){return Vs("startAfter","key",t,!0),new sa(e,t)}(e,t)))}endAt(e=null,t){return W("Query.endAt",0,2,arguments.length),new Sa(this.database,pa(this._delegate,function(e,t){return Vs("endAt","key",t,!0),new na(e,t)}(e,t)))}endBefore(e=null,t){return W("Query.endBefore",0,2,arguments.length),new Sa(this.database,pa(this._delegate,function(e,t){return Vs("endBefore","key",t,!0),new ia(e,t)}(e,t)))}equalTo(e,t){return W("Query.equalTo",1,2,arguments.length),new Sa(this.database,pa(this._delegate,function(e,t){return Vs("equalTo","key",t,!0),new da(e,t)}(e,t)))}toString(){return W("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return W("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(W("Query.isEqual",1,1,arguments.length),!(e instanceof Sa))throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.");return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,n){const i={cancel:void 0,context:void 0};if(t&&n)i.cancel=t,B(e,"cancel",i.cancel,!0),i.context=n,z(e,"context",i.context,!0);else if(t)if("object"==typeof t&&null!==t)i.context=t;else{if("function"!=typeof t)throw new Error(V(e,"cancelOrContext")+" must either be a cancel callback or a context object.");i.cancel=t}return i}get ref(){return new Pa(this.database,new Uo(this._delegate._repo,this._delegate._path))}}class Pa extends Sa{constructor(e,t){super(e,new xo(t._repo,t._path,new Ti,!1)),this.database=e,this._delegate=t}getKey(){return W("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return W("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new Pa(this.database,Vo(this._delegate,e))}getParent(){W("Reference.parent",0,0,arguments.length);const e=this._delegate.parent;return e?new Pa(this.database,e):null}getRoot(){return W("Reference.root",0,0,arguments.length),new Pa(this.database,this._delegate.root)}set(e,t){W("Reference.set",1,2,arguments.length),B("Reference.set","onComplete",t,!0);const n=Bo(this._delegate,e);return t&&n.then((()=>t(null)),(e=>t(e))),n}update(e,t){if(W("Reference.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let n=0;nt(null)),(e=>t(e))),n}setWithPriority(e,t,n){W("Reference.setWithPriority",2,3,arguments.length),B("Reference.setWithPriority","onComplete",n,!0);const i=function(e,t,n){if(Hs("setWithPriority",e._path),Us("setWithPriority",t,e._path,!1),Ws("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const i=new p;return lo(e._repo,e._path,t,n,i.wrapCallback((()=>{}))),i.promise}(this._delegate,e,t);return n&&i.then((()=>n(null)),(e=>n(e))),i}remove(e){W("Reference.remove",0,1,arguments.length),B("Reference.remove","onComplete",e,!0);const t=function(e){return Hs("remove",e._path),Bo(e,null)}(this._delegate);return e&&t.then((()=>e(null)),(t=>e(t))),t}transaction(e,t,n){W("Reference.transaction",1,3,arguments.length),B("Reference.transaction","transactionUpdate",e,!1),B("Reference.transaction","onComplete",t,!0),function(e,t,n,i){if(void 0!==n&&"boolean"!=typeof n)throw new Error(V("Reference.transaction","applyLocally")+"must be a boolean.")}(0,0,n);const i=ba(this._delegate,e,{applyLocally:n}).then((e=>new Ea(e.committed,new ka(this.database,e.snapshot))));return t&&i.then((e=>t(null,e.committed,e.snapshot)),(e=>t(e,!1,null))),i}setPriority(e,t){W("Reference.setPriority",1,2,arguments.length),B("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=$(e),Hs("setPriority",e._path),Ws("setPriority",t,!1);const n=new p;return lo(e._repo,Pn(e._path,".priority"),t,null,n.wrapCallback((()=>{}))),n.promise}(this._delegate,e);return t&&n.then((()=>t(null)),(e=>t(e))),n}push(e,t){W("Reference.push",0,2,arguments.length),B("Reference.push","onComplete",t,!0);const n=function(e,t){e=$(e),Hs("push",e._path),Us("push",t,e._path,!0);const n=io(e._repo),i=Ro(n),r=Vo(e,i),s=Vo(e,i);let o;return o=null!=t?Bo(s,t).then((()=>s)):Promise.resolve(s),r.then=o.then.bind(o),r.catch=o.then.bind(o,void 0),r}(this._delegate,e),i=n.then((e=>new Pa(this.database,e)));t&&i.then((()=>t(null)),(e=>t(e)));const r=new Pa(this.database,n);return r.then=i.then.bind(i),r.catch=i.catch.bind(i,void 0),r}onDisconnect(){return Hs("Reference.onDisconnect",this._delegate._path),new Ta(new Do(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class Ra{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:va,forceLongPolling:ya}}useEmulator(e,t,n={}){!function(e,t,n,i={}){(e=$(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&At("Cannot call useEmulator() after instance has already been initialized.");const r=e._repoInternal;let s;if(r.repoInfo_.nodeAdmin)i.mockUserToken&&At('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new Yt(Yt.OWNER);else if(i.mockUserToken){const t="string"==typeof i.mockUserToken?i.mockUserToken:function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",i=e.iat||0,r=e.sub||e.user_id;if(!r)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:i,exp:i+3600,auth_time:i,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}}},e);return[c(JSON.stringify({alg:"none",type:"JWT"})),c(JSON.stringify(s)),""].join(".")}(i.mockUserToken,e.app.options.projectId);s=new Yt(t)}!function(e,t,n,i){e.repoInfo_=new tn(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),i&&(e.authTokenProvider_=i)}(r,t,n,s)}(this._delegate,e,t,n)}ref(e){if(W("database.ref",0,1,arguments.length),e instanceof Pa){const t=Wo(this._delegate,e.toString());return new Pa(this,t)}{const t=jo(this._delegate,e);return new Pa(this,t)}}refFromURL(e){W("database.refFromURL",1,1,arguments.length);const t=Wo(this._delegate,e);return new Pa(this,t)}goOffline(){return W("database.goOffline",0,0,arguments.length),(e=$(e=this._delegate))._checkNotDeleted("goOffline"),void fo(e._repo);var e}goOnline(){return W("database.goOnline",0,0,arguments.length),(e=$(e=this._delegate))._checkNotDeleted("goOnline"),void((t=e._repo).persistentConnection_&&t.persistentConnection_.resume(Zs));var e,t}}Ra.ServerValue={TIMESTAMP:{".sv":"timestamp"},increment:e=>function(e){return{".sv":{increment:e}}}(e)};var Na=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:i,customAppCheckImpl:r,namespace:s,nodeAdmin:o=!1}){_t(n);const a=new J("database-standalone"),c=new Y("auth-internal",a);let l;return c.setComponent(new K("auth-internal",(()=>i),"PRIVATE")),r&&(l=new Y("app-check-internal",a),l.setComponent(new K("app-check-internal",(()=>r),"PRIVATE"))),{instance:new Ra(_a(e,c,l,t,o),e),namespace:s}}});const Aa=Ra.ServerValue;var Oa;function Da(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r{const n=e.getProvider("app-compat").getImmediate(),i=e.getProvider("database").getImmediate({identifier:t});return new Ra(i,n)}),"PUBLIC").setServiceProps({Reference:Pa,Query:Sa,Database:Ra,DataSnapshot:ka,enableLogging:function(e,t){St(e,t)},INTERNAL:Na,ServerValue:Aa}).setMultipleInstances(!0)),Oa.registerVersion("@firebase/database-compat","1.0.5"),Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const xa={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"};const La=function(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements."}},Ma=function(){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."}},Fa=new C("auth","Firebase",{"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."}),Ua=new ie("@firebase/auth");function qa(e,...t){Ua.logLevel<=X.ERROR&&Ua.error(`Auth (${We}): ${e}`,...t)}function ja(e,...t){throw Ha(e,...t)}function Wa(e,...t){return Ha(e,...t)}function Va(e,t,n){const i=Object.assign(Object.assign({},Ma()),{[t]:n});return new C("auth","Firebase",i).create(t,{appName:e.name})}function Ba(e){return Va(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function za(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&ja(e,"argument-error"),Va(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function Ha(e,...t){if("string"!=typeof e){const n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return Fa.create(e,...t)}function $a(e,t,...n){if(!e)throw Ha(t,...n)}function Ka(e){const t="INTERNAL ASSERTION FAILED: "+e;throw qa(t),new Error(t)}function Ga(e,t){e||Ka(t)}function Ya(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Ja(){return"http:"===Qa()||"https:"===Qa()}function Qa(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Xa{constructor(e,t){this.shortDelay=e,this.longDelay=t,Ga(t>e,"Short delay should be less than long delay!"),this.isMobile=_()||y()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(Ja()||v()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Za(e,t){Ga(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class ec{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void Ka("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void Ka("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void Ka("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const tc={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"},nc=new Xa(3e4,6e4);function ic(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function rc(e,t,n,i,r={}){return sc(e,r,(async()=>{let r={},s={};i&&("GET"===t?s=i:r={body:JSON.stringify(i)});const o=x(Object.assign({key:e.config.apiKey},s)).slice(1),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode),ec.fetch()(ac(e,e.config.apiHost,n,o),Object.assign({method:t,headers:a,referrerPolicy:"no-referrer"},r))}))}async function sc(e,t,n){e._canInitEmulator=!1;const i=Object.assign(Object.assign({},tc),t);try{const t=new lc(e),r=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await r.json();if("needConfirmation"in s)throw hc(e,"account-exists-with-different-credential",s);if(r.ok&&!("errorMessage"in s))return s;{const t=r.ok?s.errorMessage:s.error.message,[n,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw hc(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===n)throw hc(e,"email-already-in-use",s);if("USER_DISABLED"===n)throw hc(e,"user-disabled",s);const a=i[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw Va(e,a,o);ja(e,a)}}catch(t){if(t instanceof I)throw t;ja(e,"network-request-failed",{message:String(t)})}}async function oc(e,t,n,i,r={}){const s=await rc(e,t,n,i,r);return"mfaPendingCredential"in s&&ja(e,"multi-factor-auth-required",{_serverResponse:s}),s}function ac(e,t,n,i){const r=`${t}${n}?${i}`;return e.config.emulator?Za(e.config,r):`${e.config.apiScheme}://${r}`}function cc(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class lc{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(Wa(this.auth,"network-request-failed"))),nc.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function hc(e,t,n){const i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);const r=Wa(e,t,i);return r.customData._tokenResponse=n,r}function uc(e){return void 0!==e&&void 0!==e.getResponse}function dc(e){return void 0!==e&&void 0!==e.enterprise}class pc{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return cc(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function fc(e,t){return rc(e,"POST","/v1/accounts:lookup",t)}function _c(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function mc(e){return 1e3*Number(e)}function gc(e){const[t,n,i]=e.split(".");if(void 0===t||void 0===n||void 0===i)return qa("JWT malformed, contained fewer than 3 sections"),null;try{const e=l(n);return e?JSON.parse(e):(qa("Failed to decode base64 JWT payload"),null)}catch(e){return qa("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function vc(e){const t=gc(e);return $a(t,"internal-error"),$a(void 0!==t.exp,"internal-error"),$a(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function yc(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof I&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class wc{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}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){return void("auth/network-request-failed"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class bc{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=_c(this.lastLoginAt),this.creationTime=_c(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Ic(e){var t;const n=e.auth,i=await e.getIdToken(),r=await yc(e,fc(n,{idToken:i}));$a(null==r?void 0:r.users.length,n,"internal-error");const s=r.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?Cc(s.providerUserInfo):[],a=(c=e.providerData,l=o,[...c.filter((e=>!l.some((t=>t.providerId===e.providerId)))),...l]);var c,l;const h=e.isAnonymous,u=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!h&&u,p={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 bc(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,p)}function Cc(e){return e.map((e=>{var{providerId:t}=e,n=Da(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}))}class Tc{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){$a(e.idToken,"internal-error"),$a(void 0!==e.idToken,"internal-error"),$a(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):vc(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){$a(0!==e.length,"internal-error");const t=vc(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?($a(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:i,expiresIn:r}=await async function(e,t){const n=await sc(e,{},(async()=>{const n=x({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:i,apiKey:r}=e.config,s=ac(e,i,"/v1/token",`key=${r}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",ec.fetch()(s,{method:"POST",headers:o,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(e,t);this.updateTokensAndExpiration(n,i,Number(r))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:i,expirationTime:r}=t,s=new Tc;return n&&($a("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),i&&($a("string"==typeof i,"internal-error",{appName:e}),s.accessToken=i),r&&($a("number"==typeof r,"internal-error",{appName:e}),s.expirationTime=r),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new Tc,this.toJSON())}_performRefresh(){return Ka("not implemented")}}function Ec(e,t){$a("string"==typeof e||void 0===e,"internal-error",{appName:t})}class kc{constructor(e){var{uid:t,auth:n,stsTokenManager:i}=e,r=Da(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new wc(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=r.displayName||null,this.email=r.email||null,this.emailVerified=r.emailVerified||!1,this.phoneNumber=r.phoneNumber||null,this.photoURL=r.photoURL||null,this.isAnonymous=r.isAnonymous||!1,this.tenantId=r.tenantId||null,this.providerData=r.providerData?[...r.providerData]:[],this.metadata=new bc(r.createdAt||void 0,r.lastLoginAt||void 0)}async getIdToken(e){const t=await yc(this,this.stsTokenManager.getToken(this.auth,e));return $a(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=$(e),i=await n.getIdToken(t),r=gc(i);$a(r&&r.exp&&r.auth_time&&r.iat,n.auth,"internal-error");const s="object"==typeof r.firebase?r.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:r,token:i,authTime:_c(mc(r.auth_time)),issuedAtTime:_c(mc(r.iat)),expirationTime:_c(mc(r.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=$(e);await Ic(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&($a(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new kc(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){$a(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await Ic(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Me(this.auth.app))return Promise.reject(Ba(this.auth));const e=await this.getIdToken();return await yc(this,async function(e,t){return rc(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>Object.assign({},e))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,i,r,s,o,a,c,l;const h=null!==(n=t.displayName)&&void 0!==n?n:void 0,u=null!==(i=t.email)&&void 0!==i?i:void 0,d=null!==(r=t.phoneNumber)&&void 0!==r?r:void 0,p=null!==(s=t.photoURL)&&void 0!==s?s:void 0,f=null!==(o=t.tenantId)&&void 0!==o?o:void 0,_=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,m=null!==(c=t.createdAt)&&void 0!==c?c:void 0,g=null!==(l=t.lastLoginAt)&&void 0!==l?l:void 0,{uid:v,emailVerified:y,isAnonymous:w,providerData:b,stsTokenManager:I}=t;$a(v&&I,e,"internal-error");const C=Tc.fromJSON(this.name,I);$a("string"==typeof v,e,"internal-error"),Ec(h,e.name),Ec(u,e.name),$a("boolean"==typeof y,e,"internal-error"),$a("boolean"==typeof w,e,"internal-error"),Ec(d,e.name),Ec(p,e.name),Ec(f,e.name),Ec(_,e.name),Ec(m,e.name),Ec(g,e.name);const T=new kc({uid:v,auth:e,email:u,emailVerified:y,displayName:h,isAnonymous:w,photoURL:p,phoneNumber:d,tenantId:f,stsTokenManager:C,createdAt:m,lastLoginAt:g});return b&&Array.isArray(b)&&(T.providerData=b.map((e=>Object.assign({},e)))),_&&(T._redirectEventId=_),T}static async _fromIdTokenResponse(e,t,n=!1){const i=new Tc;i.updateFromServerResponse(t);const r=new kc({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await Ic(r),r}static async _fromGetAccountInfoResponse(e,t,n){const i=t.users[0];$a(void 0!==i.localId,"internal-error");const r=void 0!==i.providerUserInfo?Cc(i.providerUserInfo):[],s=!(i.email&&i.passwordHash||(null==r?void 0:r.length)),o=new Tc;o.updateFromIdToken(n);const a=new kc({uid:i.localId,auth:e,stsTokenManager:o,isAnonymous:s}),c={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new bc(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash||(null==r?void 0:r.length))};return Object.assign(a,c),a}}const Sc=new Map;function Pc(e){Ga(e instanceof Function,"Expected a class definition");let t=Sc.get(e);return t?(Ga(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,Sc.set(e,t),t)}class Rc{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 void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Rc.type="NONE";const Nc=Rc;function Ac(e,t,n){return`firebase:${e}:${t}:${n}`}class Oc{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:i,name:r}=this.auth;this.fullUserKey=Ac(this.userKey,i.apiKey,r),this.fullPersistenceKey=Ac("persistence",i.apiKey,r),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?kc._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new Oc(Pc(Nc),e,n);const i=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let r=i[0]||Pc(Nc);const s=Ac(n,e.config.apiKey,e.name);let o=null;for(const n of t)try{const t=await n._get(s);if(t){const i=kc._fromJSON(e,t);n!==r&&(o=i),r=n;break}}catch(e){}const a=i.filter((e=>e._shouldAllowMigration));return r._shouldAllowMigration&&a.length?(r=a[0],o&&await r._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==r)try{await e._remove(s)}catch(e){}}))),new Oc(r,e,n)):new Oc(r,e,n)}}function Dc(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Fc(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(xc(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(qc(t))return"Blackberry";if(jc(t))return"Webos";if(Lc(t))return"Safari";if((t.includes("chrome/")||Mc(t))&&!t.includes("edge/"))return"Chrome";if(Uc(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=e.match(t);if(2===(null==n?void 0:n.length))return n[1]}return"Other"}function xc(e=f()){return/firefox\//i.test(e)}function Lc(e=f()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function Mc(e=f()){return/crios\//i.test(e)}function Fc(e=f()){return/iemobile/i.test(e)}function Uc(e=f()){return/android/i.test(e)}function qc(e=f()){return/blackberry/i.test(e)}function jc(e=f()){return/webos/i.test(e)}function Wc(e=f()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Vc(e=f()){return Wc(e)||Uc(e)||jc(e)||qc(e)||/windows phone/i.test(e)||Fc(e)}function Bc(e,t=[]){let n;switch(e){case"Browser":n=Dc(f());break;case"Worker":n=`${Dc(f())}-${e}`;break;default:n=e}const i=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${We}/${i}`}class zc{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise(((n,i)=>{try{n(e(t))}catch(e){i(e)}}));n.onAbort=t,this.queue.push(n);const i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}class Hc{constructor(e){var t,n,i,r;const s=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=s.minPasswordLength)&&void 0!==t?t:6,s.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=s.maxPasswordLength),void 0!==s.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=s.containsLowercaseCharacter),void 0!==s.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=s.containsUppercaseCharacter),void 0!==s.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=s.containsNumericCharacter),void 0!==s.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=s.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(i=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==i?i:"",this.forceUpgradeOnSignin=null!==(r=e.forceUpgradeOnSignin)&&void 0!==r&&r,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,i,r,s,o;const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&(a.isValid=null===(t=a.meetsMinPasswordLength)||void 0===t||t),a.isValid&&(a.isValid=null===(n=a.meetsMaxPasswordLength)||void 0===n||n),a.isValid&&(a.isValid=null===(i=a.containsLowercaseLetter)||void 0===i||i),a.isValid&&(a.isValid=null===(r=a.containsUppercaseLetter)||void 0===r||r),a.isValid&&(a.isValid=null===(s=a.containsNumericCharacter)||void 0===s||s),a.isValid&&(a.isValid=null===(o=a.containsNonAlphanumericCharacter)||void 0===o||o),a}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),i&&(t.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let i=0;i="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,i,r){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=r))}}class $c{constructor(e,t,n,i){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Gc(this),this.idTokenSubscription=new Gc(this),this.beforeStateQueue=new zc(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=Fa,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=Pc(t)),this._initializationPromise=this.queue((async()=>{var n,i;if(!this._deleted&&(this.persistenceManager=await Oc.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await fc(this,{idToken:e}),n=await kc._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var t;if(Me(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const n=await this.assertedPersistence.getCurrentUser();let i=n,r=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(e);n&&n!==s||!(null==o?void 0:o.user)||(i=o.user,r=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(r)try{await this.beforeStateQueue.runMiddleware(i)}catch(e){i=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return $a(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Ic(e)}catch(e){if("auth/network-request-failed"!==(null==e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Me(this.app))return Promise.reject(Ba(this));const t=e?$(e):null;return t&&$a(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&&$a(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 Me(this.app)?Promise.reject(Ba(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Me(this.app)?Promise.reject(Ba(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(Pc(e))}))}_getRecaptchaConfig(){return null==this.tenantId?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 null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function(e,t={}){return rc(e,"GET","/v2/passwordPolicy",ic(e,t))}(this),t=new Hc(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new C("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged((()=>{n(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function(e,t){return rc(e,"POST","/v2/accounts:revokeToken",ic(e,t))}(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&Pc(e)||this._popupRedirectResolver;$a(t,this,"argument-error"),this.redirectPersistenceManager=await Oc.create(this,[Pc(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};const r="function"==typeof t?t:t.next.bind(t);let s=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if($a(o,this,"internal-error"),o.then((()=>{s||r(this.currentUser)})),"function"==typeof t){const r=e.addObserver(t,n,i);return()=>{s=!0,r()}}{const n=e.addObserver(t);return()=>{s=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return $a(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Bc(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);const i=await this._getAppCheckToken();return i&&(t["X-Firebase-AppCheck"]=i),t}async _getAppCheckToken(){var e;const t=await(null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null==t?void 0:t.error)&&function(e,...t){Ua.logLevel<=X.WARN&&Ua.warn(`Auth (${We}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),null==t?void 0:t.token}}function Kc(e){return $(e)}class Gc{constructor(e){this.auth=e,this.observer=null,this.addObserver=U((e=>this.observer=e))}get next(){return $a(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let Yc={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function Jc(e){return Yc.loadJS(e)}function Qc(e){return`__${e}${Math.floor(1e6*Math.random())}`}class Xc{constructor(e){this.type="recaptcha-enterprise",this.auth=Kc(e)}async verify(e="verify",t=!1){function n(t,n,i){const r=window.grecaptcha;dc(r)?r.enterprise.ready((()=>{r.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n("NO_RECAPTCHA")}))})):i(Error("No reCAPTCHA enterprise script loaded."))}return new Promise(((e,i)=>{(async function(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,n)=>{(async function(e,t){return rc(e,"GET","/v2/recaptchaConfig",ic(e,t))})(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((i=>{if(void 0!==i.recaptchaKey){const n=new pc(i);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}n(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{n(e)}))}))})(this.auth).then((r=>{if(!t&&dc(window.grecaptcha))n(r,e,i);else{if("undefined"==typeof window)return void i(new Error("RecaptchaVerifier is only supported in browser"));let t=Yc.recaptchaEnterpriseScript;0!==t.length&&(t+=r),Jc(t).then((()=>{n(r,e,i)})).catch((e=>{i(e)}))}})).catch((e=>{i(e)}))}))}}async function Zc(e,t,n,i=!1){const r=new Xc(e);let s;try{s=await r.verify(n)}catch(e){s=await r.verify(n,!0)}const o=Object.assign({},t);return i?Object.assign(o,{captchaResp:s}):Object.assign(o,{captchaResponse:s}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}async function el(e,t,n,i){var r;if(null===(r=e._getRecaptchaConfig())||void 0===r?void 0:r.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const r=await Zc(e,t,n,"getOobCode"===n);return i(e,r)}return i(e,t).catch((async r=>{if("auth/missing-recaptcha-token"===r.code){console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const r=await Zc(e,t,n,"getOobCode"===n);return i(e,r)}return Promise.reject(r)}))}function tl(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function nl(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class il{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Ka("not implemented")}_getIdTokenResponse(e){return Ka("not implemented")}_linkToIdToken(e,t){return Ka("not implemented")}_getReauthenticationResolver(e){return Ka("not implemented")}}async function rl(e,t){return rc(e,"POST","/v1/accounts:resetPassword",ic(e,t))}async function sl(e,t){return rc(e,"POST","/v1/accounts:signUp",t)}async function ol(e,t){return oc(e,"POST","/v1/accounts:signInWithPassword",ic(e,t))}async function al(e,t){return rc(e,"POST","/v1/accounts:sendOobCode",ic(e,t))}async function cl(e,t){return al(e,t)}async function ll(e,t){return al(e,t)}class hl extends il{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new hl(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new hl(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if((null==t?void 0:t.email)&&(null==t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return el(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",ol);case"emailLink":return async function(e,t){return oc(e,"POST","/v1/accounts:signInWithEmailLink",ic(e,t))}(e,{email:this._email,oobCode:this._password});default:ja(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return el(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",sl);case"emailLink":return async function(e,t){return oc(e,"POST","/v1/accounts:signInWithEmailLink",ic(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:ja(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ul(e,t){return oc(e,"POST","/v1/accounts:signInWithIdp",ic(e,t))}class dl extends il{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new dl(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):ja("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="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i}=t,r=Da(t,["providerId","signInMethod"]);if(!n||!i)return null;const s=new dl(n,i);return s.idToken=r.idToken||void 0,s.accessToken=r.accessToken||void 0,s.secret=r.secret,s.nonce=r.nonce,s.pendingToken=r.pendingToken||null,s}_getIdTokenResponse(e){return ul(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,ul(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,ul(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=x(t)}return e}}const pl={USER_NOT_FOUND:"user-not-found"};class fl extends il{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new fl({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new fl({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return oc(e,"POST","/v1/accounts:signInWithPhoneNumber",ic(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await oc(e,"POST","/v1/accounts:signInWithPhoneNumber",ic(e,t));if(n.temporaryProof)throw hc(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return oc(e,"POST","/v1/accounts:signInWithPhoneNumber",ic(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),pl)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:i}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}=e;return n||t||i||r?new fl({verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}):null}}class _l{constructor(e){var t,n,i,r,s,o;const a=L(M(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,l=null!==(n=a.oobCode)&&void 0!==n?n:null,h=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=a.mode)&&void 0!==i?i:null);$a(c&&l&&h,"argument-error"),this.apiKey=c,this.operation=h,this.code=l,this.continueUrl=null!==(r=a.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(s=a.languageCode)&&void 0!==s?s:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(e){const t=function(e){const t=L(M(e)).link,n=t?L(M(t)).deep_link_id:null,i=L(M(e)).deep_link_id;return(i?L(M(i)).link:null)||i||n||t||e}(e);try{return new _l(t)}catch(e){return null}}}class ml{constructor(){this.providerId=ml.PROVIDER_ID}static credential(e,t){return hl._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=_l.parseLink(t);return $a(n,"argument-error"),hl._fromEmailAndCode(e,n.code,n.tenantId)}}ml.PROVIDER_ID="password",ml.EMAIL_PASSWORD_SIGN_IN_METHOD="password",ml.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class gl{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 vl extends gl{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class yl extends vl{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return $a("providerId"in t&&"signInMethod"in t,"argument-error"),dl._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return $a(e.idToken||e.accessToken,"argument-error"),dl._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return yl.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return yl.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:i,pendingToken:r,nonce:s,providerId:o}=e;if(!(n||i||t||r))return null;if(!o)return null;try{return new yl(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:r})}catch(e){return null}}}class wl extends vl{constructor(){super("facebook.com")}static credential(e){return dl._fromParams({providerId:wl.PROVIDER_ID,signInMethod:wl.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return wl.credentialFromTaggedObject(e)}static credentialFromError(e){return wl.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return wl.credential(e.oauthAccessToken)}catch(e){return null}}}wl.FACEBOOK_SIGN_IN_METHOD="facebook.com",wl.PROVIDER_ID="facebook.com";class bl extends vl{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return dl._fromParams({providerId:bl.PROVIDER_ID,signInMethod:bl.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return bl.credentialFromTaggedObject(e)}static credentialFromError(e){return bl.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return bl.credential(t,n)}catch(e){return null}}}bl.GOOGLE_SIGN_IN_METHOD="google.com",bl.PROVIDER_ID="google.com";class Il extends vl{constructor(){super("github.com")}static credential(e){return dl._fromParams({providerId:Il.PROVIDER_ID,signInMethod:Il.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Il.credentialFromTaggedObject(e)}static credentialFromError(e){return Il.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Il.credential(e.oauthAccessToken)}catch(e){return null}}}Il.GITHUB_SIGN_IN_METHOD="github.com",Il.PROVIDER_ID="github.com";class Cl extends il{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return ul(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,ul(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,ul(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i,pendingToken:r}=t;return n&&i&&r&&n===i?new Cl(n,r):null}static _create(e,t){return new Cl(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Tl extends gl{constructor(e){$a(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Tl.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Tl.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=Cl.fromJSON(e);return $a(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return Cl._create(n,t)}catch(e){return null}}}class El extends vl{constructor(){super("twitter.com")}static credential(e,t){return dl._fromParams({providerId:El.PROVIDER_ID,signInMethod:El.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return El.credentialFromTaggedObject(e)}static credentialFromError(e){return El.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return El.credential(t,n)}catch(e){return null}}}async function kl(e,t){return oc(e,"POST","/v1/accounts:signUp",ic(e,t))}El.TWITTER_SIGN_IN_METHOD="twitter.com",El.PROVIDER_ID="twitter.com";class Sl{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){const r=await kc._fromIdTokenResponse(e,n,i),s=Pl(n);return new Sl({user:r,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const i=Pl(n);return new Sl({user:e,providerId:i,_tokenResponse:n,operationType:t})}}function Pl(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class Rl extends I{constructor(e,t,n,i){var r;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,Rl.prototype),this.customData={appName:e.name,tenantId:null!==(r=e.tenantId)&&void 0!==r?r:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new Rl(e,t,n,i)}}function Nl(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw Rl._fromErrorAndOperation(e,n,t,i);throw n}))}function Al(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function Ol(e,t,n=!1){const i=await yc(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Sl._forOperation(e,"link",i)}async function Dl(e,t,n){await Ic(t);const i=!1===e?"provider-already-linked":"no-such-provider";$a(Al(t.providerData).has(n)===e,t.auth,i)}async function xl(e,t,n=!1){const{auth:i}=e;if(Me(i.app))return Promise.reject(Ba(i));const r="reauthenticate";try{const s=await yc(e,Nl(i,r,t,e),n);$a(s.idToken,i,"internal-error");const o=gc(s.idToken);$a(o,i,"internal-error");const{sub:a}=o;return $a(e.uid===a,i,"user-mismatch"),Sl._forOperation(e,r,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&ja(i,"user-mismatch"),e}}async function Ll(e,t,n=!1){if(Me(e.app))return Promise.reject(Ba(e));const i="signIn",r=await Nl(e,i,t),s=await Sl._fromIdTokenResponse(e,i,r);return n||await e._updateCurrentUser(s.user),s}async function Ml(e,t){return Ll(Kc(e),t)}async function Fl(e,t){const n=$(e);return await Dl(!1,n,t.providerId),Ol(n,t)}async function Ul(e,t){return xl($(e),t)}class ql{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?jl._fromServerResponse(e,t):"totpInfo"in t?Wl._fromServerResponse(e,t):ja(e,"internal-error")}}class jl extends ql{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new jl(t)}}class Wl extends ql{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new Wl(t)}}function Vl(e,t,n){var i;$a((null===(i=n.url)||void 0===i?void 0:i.length)>0,e,"invalid-continue-uri"),$a(void 0===n.dynamicLinkDomain||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&($a(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&($a(n.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function Bl(e){const t=Kc(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function zl(e,t){const n=$(e),i=await rl(n,{oobCode:t}),r=i.requestType;switch($a(r,n,"internal-error"),r){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":$a(i.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":$a(i.mfaInfo,n,"internal-error");default:$a(i.email,n,"internal-error")}let s=null;return i.mfaInfo&&(s=ql._fromServerResponse(Kc(n),i.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===i.requestType?i.newEmail:i.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===i.requestType?i.email:i.newEmail)||null,multiFactorInfo:s},operation:r}}async function Hl(e,t,n){const{auth:i}=e,r={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(r.email=t),n&&(r.password=n);const s=await yc(e,async function(e,t){return rc(e,"POST","/v1/accounts:update",t)}(i,r));await e._updateTokensIfNecessary(s,!0)}class $l{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class Kl extends $l{constructor(e,t,n,i){super(e,t,n),this.username=i}}class Gl extends $l{constructor(e,t){super(e,"facebook.com",t)}}class Yl extends Kl{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class Jl extends $l{constructor(e,t){super(e,"google.com",t)}}class Ql extends Kl{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Xl(e){const{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){var t,n;if(!e)return null;const{providerId:i}=e,r=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},s=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!i&&(null==e?void 0:e.idToken)){const i=null===(n=null===(t=gc(e.idToken))||void 0===t?void 0:t.firebase)||void 0===n?void 0:n.sign_in_provider;if(i)return new $l(s,"anonymous"!==i&&"custom"!==i?i:null)}if(!i)return null;switch(i){case"facebook.com":return new Gl(s,r);case"github.com":return new Yl(s,r);case"google.com":return new Jl(s,r);case"twitter.com":return new Ql(s,r,e.screenName||null);case"custom":case"anonymous":return new $l(s,null);default:return new $l(s,i,r)}}(n)}class Zl{constructor(e,t,n){this.type=e,this.credential=t,this.user=n}static _fromIdtoken(e,t){return new Zl("enroll",e,t)}static _fromMfaPendingCredential(e){return new Zl("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t,n;if(null==e?void 0:e.multiFactorSession){if(null===(t=e.multiFactorSession)||void 0===t?void 0:t.pendingCredential)return Zl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null===(n=e.multiFactorSession)||void 0===n?void 0:n.idToken)return Zl._fromIdtoken(e.multiFactorSession.idToken)}return null}}class eh{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,t){const n=Kc(e),i=t.customData._serverResponse,r=(i.mfaInfo||[]).map((e=>ql._fromServerResponse(n,e)));$a(i.mfaPendingCredential,n,"internal-error");const s=Zl._fromMfaPendingCredential(i.mfaPendingCredential);return new eh(s,r,(async e=>{const r=await e._process(n,s);delete i.mfaInfo,delete i.mfaPendingCredential;const o=Object.assign(Object.assign({},i),{idToken:r.idToken,refreshToken:r.refreshToken});switch(t.operationType){case"signIn":const e=await Sl._fromIdTokenResponse(n,t.operationType,o);return await n._updateCurrentUser(e.user),e;case"reauthenticate":return $a(t.user,n,"internal-error"),Sl._forOperation(t.user,t.operationType,o);default:ja(n,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}class th{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload((t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map((t=>ql._fromServerResponse(e.auth,t))))}))}static _fromUser(e){return new th(e)}async getSession(){return Zl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const n=e,i=await this.getSession(),r=await yc(this.user,n._process(this.user.auth,i,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,n=await this.user.getIdToken();try{const e=await yc(this.user,(i=this.user.auth,r={idToken:n,mfaEnrollmentId:t},rc(i,"POST","/v2/accounts/mfaEnrollment:withdraw",ic(i,r))));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t)),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(e){throw e}var i,r}}const nh=new WeakMap,ih="__sak";class rh{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(ih,"1"),this.storage.removeItem(ih),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){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()}}class sh extends rh{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const e=f();return Lc(e)||Wc(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Vc(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(n);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const i=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},r=this.storage.getItem(n);w()&&10===document.documentMode&&r!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,10):i()}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){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]}}sh.type="LOCAL";const oh=sh;class ah extends rh{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}ah.type="SESSION";const ch=ah;class lh{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const n=new lh(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:i,data:r}=t.data,s=this.handlersMap[i];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:i});const o=Array.from(s).map((async e=>e(t.origin,r))),a=await function(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:i,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function hh(e="",t=10){let n="";for(let e=0;e{const c=hh("",20);i.port1.start();const l=setTimeout((()=>{a(new Error("unsupported_event"))}),n);s={messageChannel:i,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(l),r=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(r),o(t.data.response);break;default:clearTimeout(l),clearTimeout(r),a(new Error("invalid_response"))}}},this.handlers.add(s),i.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[i.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function dh(){return window}function ph(){return void 0!==dh().WorkerGlobalScope&&"function"==typeof dh().importScripts}const fh="firebaseLocalStorageDb",_h="firebaseLocalStorage",mh="fbase_key";class gh{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 vh(e,t){return e.transaction([_h],t?"readwrite":"readonly").objectStore(_h)}function yh(){const e=indexedDB.open(fh,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(_h,{keyPath:mh})}catch(e){n(e)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(_h)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(fh);return new gh(e).toPromise()}(),t(await yh()))}))}))}async function wh(e,t,n){const i=vh(e,!0).put({[mh]:t,value:n});return new gh(i).toPromise()}function bh(e,t){const n=vh(e,!0).delete(t);return new gh(n).toPromise()}class Ih{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.db||(this.db=await yh()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return ph()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=lh._getInstance(ph()?self:null),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new uh(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(e=n[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=n[0])||void 0===t?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await yh();return await wh(e,ih,"1"),await bh(e,ih),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((n=>wh(n,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function(e,t){const n=vh(e,!1).get(t),i=await new gh(n).toPromise();return void 0===i?null:i.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>bh(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=vh(e,!1).getAll();return new gh(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;if(0!==e.length)for(const{fbase_key:i,value:r}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(r)&&(this.notifyListeners(i,r),t.push(i));for(const e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}Ih.type="LOCAL";const Ch=Ih,Th=1e12;class Eh{constructor(e){this.auth=e,this.counter=Th,this._widgets=new Map}render(e,t){const n=this.counter;return this._widgets.set(n,new kh(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t;const n=e||Th;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;const n=e||Th;return(null===(t=this._widgets.get(n))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;const n=e||Th;return null===(t=this._widgets.get(n))||void 0===t||t.execute(),""}}class kh{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};const i="string"==typeof e?document.getElementById(e):e;$a(i,"argument-error",{appName:t}),this.container=i,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout((()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let e=0;e<50;e++)t.push(n.charAt(Math.floor(62*Math.random())));return t.join("")}();const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout((()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()}),6e4)}),500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const Sh=Qc("rcb"),Ph=new Xa(3e4,6e4);class Rh{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!(null===(e=dh().grecaptcha)||void 0===e?void 0:e.render)}load(e,t=""){return $a(function(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}(t),e,"argument-error"),this.shouldResolveImmediately(t)&&uc(dh().grecaptcha)?Promise.resolve(dh().grecaptcha):new Promise(((n,i)=>{const r=dh().setTimeout((()=>{i(Wa(e,"network-request-failed"))}),Ph.get());dh()[Sh]=()=>{dh().clearTimeout(r),delete dh()[Sh];const s=dh().grecaptcha;if(!s||!uc(s))return void i(Wa(e,"internal-error"));const o=s.render;s.render=(e,t)=>{const n=o(e,t);return this.counter++,n},this.hostLanguage=t,n(s)},Jc(`${Yc.recaptchaV2Script}?${x({onload:Sh,render:"explicit",hl:t})}`).catch((()=>{clearTimeout(r),i(Wa(e,"internal-error"))}))}))}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!!(null===(t=dh().grecaptcha)||void 0===t?void 0:t.render)&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}class Nh{async load(e){return new Eh(e)}clearedOneInstance(){}}const Ah="recaptcha",Oh={theme:"light",type:"image"};class Dh{constructor(e,t,n=Object.assign({},Oh)){this.parameters=n,this.type=Ah,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Kc(e),this.isInvisible="invisible"===this.parameters.size,$a("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");const i="string"==typeof t?document.getElementById(t):t;$a(i,this.auth,"argument-error"),this.container=i,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new Nh:new Rh,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha();return t.getResponse(e)||new Promise((n=>{const i=e=>{e&&(this.tokenChangeListeners.delete(i),n(e))};this.tokenChangeListeners.add(i),this.isInvisible&&t.execute(e)}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch((e=>{throw this.renderPromise=null,e}))),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}validateStartingState(){$a(!this.parameters.sitekey,this.auth,"argument-error"),$a(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),$a("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach((e=>e(t))),"function"==typeof e)e(t);else if("string"==typeof e){const n=dh()[e];"function"==typeof n&&n(t)}}}assertNotDestroyed(){$a(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){$a(Ja()&&!ph(),this.auth,"internal-error"),await function(){let e=null;return new Promise((t=>{"complete"!==document.readyState?(e=()=>t(),window.addEventListener("load",e)):t()})).catch((t=>{throw e&&window.removeEventListener("load",e),t}))}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await async function(e){return(await rc(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}(this.auth);$a(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return $a(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class xh{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=fl._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function Lh(e,t,n){var i;const r=await n.verify();try{let s;if($a("string"==typeof r,e,"argument-error"),$a(n.type===Ah,e,"argument-error"),s="string"==typeof t?{phoneNumber:t}:t,"session"in s){const t=s.session;if("phoneNumber"in s){$a("enroll"===t.type,e,"internal-error");const n=await function(e,t){return rc(e,"POST","/v2/accounts/mfaEnrollment:start",ic(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:r}});return n.phoneSessionInfo.sessionInfo}{$a("signin"===t.type,e,"internal-error");const n=(null===(i=s.multiFactorHint)||void 0===i?void 0:i.uid)||s.multiFactorUid;$a(n,e,"missing-multi-factor-info");const o=await function(e,t){return rc(e,"POST","/v2/accounts/mfaSignIn:start",ic(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:r}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return rc(e,"POST","/v1/accounts:sendVerificationCode",ic(e,t))}(e,{phoneNumber:s.phoneNumber,recaptchaToken:r});return t}}finally{n._reset()}}class Mh{constructor(e){this.providerId=Mh.PROVIDER_ID,this.auth=Kc(e)}verifyPhoneNumber(e,t){return Lh(this.auth,e,$(t))}static credential(e,t){return fl._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Mh.credentialFromTaggedObject(t)}static credentialFromError(e){return Mh.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?fl._fromTokenResponse(t,n):null}}function Fh(e,t){return t?Pc(t):($a(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}Mh.PROVIDER_ID="phone",Mh.PHONE_SIGN_IN_METHOD="phone";class Uh extends il{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ul(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ul(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ul(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 qh(e){return Ll(e.auth,new Uh(e),e.bypassAuthState)}function jh(e){const{auth:t,user:n}=e;return $a(n,t,"internal-error"),xl(n,new Uh(e),e.bypassAuthState)}async function Wh(e){const{auth:t,user:n}=e;return $a(n,t,"internal-error"),Ol(n,new Uh(e),e.bypassAuthState)}class Vh{constructor(e,t,n,i,r=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:i,tenantId:r,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:r||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return qh;case"linkViaPopup":case"linkViaRedirect":return Wh;case"reauthViaPopup":case"reauthViaRedirect":return jh;default:ja(this.auth,"internal-error")}}resolve(e){Ga(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Ga(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 Bh=new Xa(2e3,1e4);class zh extends Vh{constructor(e,t,n,i,r){super(e,t,i,r),this.provider=n,this.authWindow=null,this.pollId=null,zh.currentPopupAction&&zh.currentPopupAction.cancel(),zh.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return $a(e,this.auth,"internal-error"),e}async onExecution(){Ga(1===this.filter.length,"Popup operations only handle one event");const e=hh();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(Wa(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(Wa(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,zh.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(Wa(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(e,Bh.get())};e()}}zh.currentPopupAction=null;const Hh="pendingRedirect",$h=new Map;class Kh extends Vh{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=$h.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=Qh(t),i=Jh(e);if(!await i._isAvailable())return!1;const r="true"===await i._get(n);return await i._remove(n),r}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}$h.set(this.auth._key(),e)}return this.bypassAuthState||$h.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function Gh(e,t){return Jh(e)._set(Qh(t),"true")}function Yh(e,t){$h.set(e._key(),t)}function Jh(e){return Pc(e._redirectPersistence)}function Qh(e){return Ac(Hh,e.config.apiKey,e.name)}async function Xh(e,t,n=!1){if(Me(e.app))return Promise.reject(Ba(e));const i=Kc(e),r=Fh(i,t),s=new Kh(i,r,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await i._persistUserIfCurrent(o.user),await i._setRedirectUser(null,t)),o}async function Zh(e){const t=hh(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class eu{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return nu(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!nu(e)){const i=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(Wa(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(tu(e))}saveEventToCache(e){this.cachedEventUids.add(tu(e)),this.lastProcessedEventTime=Date.now()}}function tu(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function nu({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function iu(e,t={}){return rc(e,"GET","/v1/projects",t)}const ru=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,su=/^https?/;function ou(e){const t=Ya(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){const r=new URL(e);return""===r.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===i}if(!su.test(n))return!1;if(ru.test(e))return i===e;const r=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+r+"|"+r+")$","i").test(i)}const au=new Xa(3e4,6e4);function cu(){const e=dh().___jsl;if(null==e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t{var i,r,s;function o(){cu(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{cu(),n(Wa(e,"network-request-failed"))},timeout:au.get()})}if(null===(r=null===(i=dh().gapi)||void 0===i?void 0:i.iframes)||void 0===r?void 0:r.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=dh().gapi)||void 0===s?void 0:s.load)){const t=Qc("iframefcb");return dh()[t]=()=>{gapi.load?o():n(Wa(e,"network-request-failed"))},Jc(`${Yc.gapiScript}?onload=${t}`).catch((e=>n(e)))}o()}})).catch((e=>{throw hu=null,e}))}let hu=null;const uu=new Xa(5e3,15e3),du="__/auth/iframe",pu="emulator/auth/iframe",fu={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},_u=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function mu(e){const t=e.config;$a(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?Za(t,pu):`https://${e.config.authDomain}/${du}`,i={apiKey:t.apiKey,appName:e.name,v:We},r=_u.get(e.config.apiHost);r&&(i.eid=r);const s=e._getFrameworks();return s.length&&(i.fw=s.join(",")),`${n}?${x(i).slice(1)}`}const gu={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class vu{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}const yu="__/auth/handler",wu="emulator/auth/handler",bu=encodeURIComponent("fac");async function Iu(e,t,n,i,r,s){$a(e.config.authDomain,e,"auth-domain-config-required"),$a(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:i,v:We,eventId:r};if(t instanceof gl){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",N(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(s||{}))o[e]=t}if(t instanceof vl){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(o.scopes=e.join(","))}e.tenantId&&(o.tid=e.tenantId);const a=o;for(const e of Object.keys(a))void 0===a[e]&&delete a[e];const c=await e._getAppCheckToken(),l=c?`#${bu}=${encodeURIComponent(c)}`:"";return`${function({config:e}){return e.emulator?Za(e,wu):`https://${e.authDomain}/${yu}`}(e)}?${x(a).slice(1)}${l}`}const Cu="webStorageSupport",Tu=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=ch,this._completeRedirectFn=Xh,this._overrideRedirectResult=Yh}async _openPopup(e,t,n,i){var r;return Ga(null===(r=this.eventManagers[e._key()])||void 0===r?void 0:r.manager,"_initialize() not called before _openPopup()"),function(e,t,n,i=500,r=600){const s=Math.max((window.screen.availHeight-r)/2,0).toString(),o=Math.max((window.screen.availWidth-i)/2,0).toString();let a="";const c=Object.assign(Object.assign({},gu),{width:i.toString(),height:r.toString(),top:s,left:o}),l=f().toLowerCase();n&&(a=Mc(l)?"_blank":n),xc(l)&&(t=t||"http://localhost",c.scrollbars="yes");const h=Object.entries(c).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(function(e=f()){var t;return Wc(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(l)&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(i)}(t||"",a),new vu(null);const u=window.open(t||"",a,h);$a(u,e,"popup-blocked");try{u.focus()}catch(e){}return new vu(u)}(e,await Iu(e,t,n,Ya(),i),hh())}async _openRedirect(e,t,n,i){return await this._originValidation(e),r=await Iu(e,t,n,Ya(),i),dh().location.href=r,new Promise((()=>{}));var r}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(Ga(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch((()=>{delete this.eventManagers[t]})),n}async initAndGetManager(e){const t=await async function(e){const t=await function(e){return hu=hu||lu(e),hu}(e),n=dh().gapi;return $a(n,e,"internal-error"),t.open({where:document.body,url:mu(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:fu,dontclear:!0},(t=>new Promise((async(n,i)=>{await t.restyle({setHideOnLeave:!1});const r=Wa(e,"network-request-failed"),s=dh().setTimeout((()=>{i(r)}),uu.get());function o(){dh().clearTimeout(s),n(t)}t.ping(o).then(o,(()=>{i(r)}))}))))}(e),n=new eu(e);return t.register("authEvent",(t=>($a(null==t?void 0:t.authEvent,e,"invalid-auth-event"),{status:n.onEvent(t.authEvent)?"ACK":"ERROR"})),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(Cu,{type:Cu},(n=>{var i;const r=null===(i=null==n?void 0:n[0])||void 0===i?void 0:i[Cu];void 0!==r&&t(!!r),ja(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){if(e.config.emulator)return;const{authorizedDomains:t}=await iu(e);for(const e of t)try{if(ou(e))return}catch(e){}ja(e,"unauthorized-domain")}(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Vc()||Lc()||Wc()}};class Eu{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return Ka("unexpected MultiFactorSessionType")}}}class ku extends Eu{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ku(e)}_finalizeEnroll(e,t,n){return function(e,t){return rc(e,"POST","/v2/accounts/mfaEnrollment:finalize",ic(e,t))}(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return function(e,t){return rc(e,"POST","/v2/accounts/mfaSignIn:finalize",ic(e,t))}(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class Su{constructor(){}static assertion(e){return ku._fromCredential(e)}}Su.FACTOR_ID="phone";var Pu,Ru,Nu,Au="@firebase/auth",Ou="1.7.4";class Du{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){$a(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function xu(){return window}null===(Pu=u())||void 0===Pu||Pu._authIdTokenMaxAge,Ru={loadJS:e=>new Promise(((t,n)=>{const i=document.createElement("script");i.setAttribute("src",e),i.onload=t,i.onerror=e=>{const t=Wa("internal-error");t.customData=e,n(t)},i.type="text/javascript",i.charset="UTF-8",function(){var e,t;return null!==(t=null===(e=document.getElementsByTagName("head"))||void 0===e?void 0:e[0])&&void 0!==t?t:document}().appendChild(i)})),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="},Yc=Ru,Nu="Browser",Oe(new K("auth",((e,{options:t})=>{const n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),r=e.getProvider("app-check-internal"),{apiKey:s,authDomain:o}=n.options;$a(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});const a={apiKey:s,authDomain:o,clientPlatform:Nu,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Bc(Nu)},c=new $c(n,i,r,a);return function(e,t){const n=(null==t?void 0:t.persistence)||[],i=(Array.isArray(n)?n:[n]).map(Pc);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(i,null==t?void 0:t.popupRedirectResolver)}(c,t),c}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),Oe(new K("auth-internal",(e=>{return t=Kc(e.getProvider("auth").getImmediate()),new Du(t);var t}),"PRIVATE").setInstantiationMode("EXPLICIT")),Ke(Au,Ou,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(Nu)),Ke(Au,Ou,"esm2017");class Lu extends eu{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise((e=>{this.resolveInialized=e}))}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(e){return this.resolveInialized(),this.passiveListeners.forEach((t=>t(e))),super.onEvent(e)}async initialized(){await this.initPromise}}async function Mu(e){const t=await Uu()._get(qu(e));return t&&await Uu()._remove(qu(e)),t}function Fu(){const e=[];for(let t=0;t<20;t++){const t=Math.floor(62*Math.random());e.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(t))}return e.join("")}function Uu(){return Pc(oh)}function qu(e){return Ac("authEvent",e.config.apiKey,e.name)}function ju(e){if(!(null==e?void 0:e.includes("?")))return{};const[t,...n]=e.split("?");return L(n.join("?"))}const Wu=class{constructor(){this._redirectPersistence=ch,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=Xh,this._overrideRedirectResult=Yh}async _initialize(e){const t=e._key();let n=this.eventManagers.get(t);return n||(n=new Lu(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){ja(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,i){!function(e){var t,n,i,r,s,o,a,c,l,h;const u=xu();$a("function"==typeof(null===(t=null==u?void 0:u.universalLinks)||void 0===t?void 0:t.subscribe),e,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),$a(void 0!==(null===(n=null==u?void 0:u.BuildInfo)||void 0===n?void 0:n.packageName),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),$a("function"==typeof(null===(s=null===(r=null===(i=null==u?void 0:u.cordova)||void 0===i?void 0:i.plugins)||void 0===r?void 0:r.browsertab)||void 0===s?void 0:s.openUrl),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),$a("function"==typeof(null===(c=null===(a=null===(o=null==u?void 0:u.cordova)||void 0===o?void 0:o.plugins)||void 0===a?void 0:a.browsertab)||void 0===c?void 0:c.isAvailable),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),$a("function"==typeof(null===(h=null===(l=null==u?void 0:u.cordova)||void 0===l?void 0:l.InAppBrowser)||void 0===h?void 0:h.open),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"})}(e);const r=await this._initialize(e);await r.initialized(),r.resetRedirect(),$h.clear(),await this._originValidation(e);const s=function(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:Fu(),postBody:null,tenantId:e.tenantId,error:Wa(e,"no-auth-event")}}(e,n,i);await function(e,t){return Uu()._set(qu(e),t)}(e,s);const o=await async function(e,t,n){var i;const{BuildInfo:r}=xu();Ga(t.sessionId,"AuthEvent did not contain a session ID");const s=await async function(e){const t=function(e){if(Ga(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;te.toString(16).padStart(2,"0"))).join("")}(t.sessionId),o={};return Wc()?o.ibi=r.packageName:Uc()?o.apn=r.packageName:ja(e,"operation-not-supported-in-this-environment"),r.displayName&&(o.appDisplayName=r.displayName),o.sessionId=s,Iu(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,o)}(e,s,t);return async function(e,t,n){const{cordova:i}=xu();let r=()=>{};try{await new Promise(((s,o)=>{let a=null;function c(){var e;s();const t=null===(e=i.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==n?void 0:n.close)&&n.close()}function l(){a||(a=window.setTimeout((()=>{o(Wa(e,"redirect-cancelled-by-user"))}),2e3))}function h(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&l()}t.addPassiveListener(c),document.addEventListener("resume",l,!1),Uc()&&document.addEventListener("visibilitychange",h,!1),r=()=>{t.removePassiveListener(c),document.removeEventListener("resume",l,!1),document.removeEventListener("visibilitychange",h,!1),a&&window.clearTimeout(a)}}))}finally{r()}}(e,r,await function(e){const{cordova:t}=xu();return new Promise((n=>{t.plugins.browsertab.isAvailable((i=>{let r=null;i?t.plugins.browsertab.openUrl(e):r=t.InAppBrowser.open(e,function(e=f()){return/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)}()?"_blank":"_system","location=yes"),n(r)}))}))}(o))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){const{BuildInfo:t}=xu(),n={};Wc()?n.iosBundleId=t.packageName:Uc()?n.androidPackageName=t.packageName:ja(e,"operation-not-supported-in-this-environment"),await iu(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(e,t){const{universalLinks:n,handleOpenURL:i,BuildInfo:r}=xu(),s=setTimeout((async()=>{await Mu(e),t.onEvent(Vu())}),500),o=async n=>{clearTimeout(s);const i=await Mu(e);let r=null;i&&(null==n?void 0:n.url)&&(r=function(e,t){var n,i;const r=function(e){const t=ju(e),n=t.link?decodeURIComponent(t.link):void 0,i=ju(n).link,r=t.deep_link_id?decodeURIComponent(t.deep_link_id):void 0;return ju(r).link||r||i||n||e}(t);if(r.includes("/__/auth/callback")){const t=ju(r),s=t.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(t.firebaseError)):null,o=null===(i=null===(n=null==s?void 0:s.code)||void 0===n?void 0:n.split("auth/"))||void 0===i?void 0:i[1],a=o?Wa(o):null;return a?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:a,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:r,postBody:null}}return null}(i,n.url)),t.onEvent(r||Vu())};void 0!==n&&"function"==typeof n.subscribe&&n.subscribe(null,o);const a=i,c=`${r.packageName.toLowerCase()}://`;xu().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&o({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}}}};function Vu(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Wa("no-auth-event")}}function Bu(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function zu(e=f()){return!("file:"!==Bu()&&"ionic:"!==Bu()&&"capacitor:"!==Bu()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Hu(){try{const e=self.localStorage,t=hh();if(e)return e.setItem(t,"1"),e.removeItem(t),!function(e=f()){return w()&&11===(null===document||void 0===document?void 0:document.documentMode)||function(e=f()){return/Edge\/\d+/.test(e)}(e)}()||b()}catch(e){return $u()&&b()}return!1}function $u(){return void 0!==e.g&&"WorkerGlobalScope"in e.g&&"importScripts"in e.g}function Ku(){return("http:"===Bu()||"https:"===Bu()||v()||zu())&&!(y()||m())&&Hu()&&!$u()}function Gu(){return zu()&&"undefined"!=typeof document}const Yu={LOCAL:"local",NONE:"none",SESSION:"session"},Ju=$a,Qu="persistence";async function Xu(e){await e._initializationPromise;const t=Zu(),n=Ac(Qu,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function Zu(){var e;try{return(null===(e="undefined"!=typeof window?window:null)||void 0===e?void 0:e.sessionStorage)||null}catch(e){return null}}const ed=$a;class td{constructor(){this.browserResolver=Pc(Tu),this.cordovaResolver=Pc(Wu),this.underlyingResolver=null,this._redirectPersistence=ch,this._completeRedirectFn=Xh,this._overrideRedirectResult=Yh}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,i){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,i)}async _openRedirect(e,t,n,i){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,i)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Gu()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return ed(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){if(this.underlyingResolver)return;const e=await async function(){return!!Gu()&&new Promise((e=>{const t=setTimeout((()=>{e(!1)}),1e3);document.addEventListener("deviceready",(()=>{clearTimeout(t),e(!0)}))}))}();this.underlyingResolver=e?this.cordovaResolver:this.browserResolver}}function nd(e){return e.unwrap()}function id(e){const{_tokenResponse:t}=e instanceof I?e.customData:e;if(!t)return null;if(!(e instanceof I)&&"temporaryProof"in t&&"phoneNumber"in t)return Mh.credentialFromResult(e);const n=t.providerId;if(!n||n===xa.PASSWORD)return null;let i;switch(n){case xa.GOOGLE:i=bl;break;case xa.FACEBOOK:i=wl;break;case xa.GITHUB:i=Il;break;case xa.TWITTER:i=El;break;default:const{oauthIdToken:e,oauthAccessToken:r,oauthTokenSecret:s,pendingToken:o,nonce:a}=t;return r||s||e||o?o?n.startsWith("saml.")?Cl._create(n,o):dl._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:e,accessToken:r}):new yl(n).credential({idToken:e,accessToken:r,rawNonce:a}):null}return e instanceof I?i.credentialFromError(e):i.credentialFromResult(e)}function rd(e,t){return t.catch((t=>{throw t instanceof I&&function(e,t){var n;const i=null===(n=t.customData)||void 0===n?void 0:n._tokenResponse;if("auth/multi-factor-auth-required"===(null==t?void 0:t.code))t.resolver=new od(e,function(e,t){var n;const i=$(e),r=t;return $a(t.customData.operationType,i,"argument-error"),$a(null===(n=r.customData._serverResponse)||void 0===n?void 0:n.mfaPendingCredential,i,"argument-error"),eh._fromError(i,r)}(e,t));else if(i){const e=id(t),n=t;e&&(n.credential=e,n.tenantId=i.tenantId||void 0,n.email=i.email||void 0,n.phoneNumber=i.phoneNumber||void 0)}}(e,t),t})).then((e=>{const t=e.operationType,n=e.user;return{operationType:t,credential:(i=e,id(i)),additionalUserInfo:Xl(e),user:ad.getOrCreate(n)};var i}))}async function sd(e,t){const n=await t;return{verificationId:n.verificationId,confirm:t=>rd(e,n.confirm(t))}}class od{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return rd(nd(this.auth),this.resolver.resolveSignIn(e))}}class ad{constructor(e){this._delegate=e,this.multiFactor=function(e){const t=$(e);return nh.has(t)||nh.set(t,th._fromUser(t)),nh.get(t)}(e)}static getOrCreate(e){return ad.USER_MAP.has(e)||ad.USER_MAP.set(e,new ad(e)),ad.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return rd(this.auth,Fl(this._delegate,e))}async linkWithPhoneNumber(e,t){return sd(this.auth,async function(e,t,n){const i=$(e);await Dl(!1,i,"phone");const r=await Lh(i.auth,t,$(n));return new xh(r,(e=>Fl(i,e)))}(this._delegate,e,t))}async linkWithPopup(e){return rd(this.auth,async function(e,t,n){const i=$(e);za(i.auth,t,gl);const r=Fh(i.auth,n);return new zh(i.auth,"linkViaPopup",t,r,i).executeNotNull()}(this._delegate,e,td))}async linkWithRedirect(e){return await Xu(Kc(this.auth)),function(e,t,n){return async function(e,t,n){const i=$(e);za(i.auth,t,gl),await i.auth._initializationPromise;const r=Fh(i.auth,n);await Dl(!1,i,t.providerId),await Gh(r,i.auth);const s=await Zh(i);return r._openRedirect(i.auth,t,"linkViaRedirect",s)}(e,t,n)}(this._delegate,e,td)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return rd(this.auth,Ul(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return sd(this.auth,async function(e,t,n){const i=$(e);if(Me(i.auth.app))return Promise.reject(Ba(i.auth));const r=await Lh(i.auth,t,$(n));return new xh(r,(e=>Ul(i,e)))}(this._delegate,e,t))}reauthenticateWithPopup(e){return rd(this.auth,async function(e,t,n){const i=$(e);if(Me(i.auth.app))return Promise.reject(Wa(i.auth,"operation-not-supported-in-this-environment"));za(i.auth,t,gl);const r=Fh(i.auth,n);return new zh(i.auth,"reauthViaPopup",t,r,i).executeNotNull()}(this._delegate,e,td))}async reauthenticateWithRedirect(e){return await Xu(Kc(this.auth)),function(e,t,n){return async function(e,t,n){const i=$(e);if(za(i.auth,t,gl),Me(i.auth.app))return Promise.reject(Ba(i.auth));await i.auth._initializationPromise;const r=Fh(i.auth,n);await Gh(r,i.auth);const s=await Zh(i);return r._openRedirect(i.auth,t,"reauthViaRedirect",s)}(e,t,n)}(this._delegate,e,td)}sendEmailVerification(e){return async function(e,t){const n=$(e),i={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&Vl(n.auth,i,t);const{email:r}=await async function(e,t){return al(e,t)}(n.auth,i);r!==e.email&&await e.reload()}(this._delegate,e)}async unlink(e){return await async function(e,t){const n=$(e);await Dl(!0,n,t);const{providerUserInfo:i}=await async function(e,t){return rc(e,"POST","/v1/accounts:update",t)}(n.auth,{idToken:await n.getIdToken(),deleteProvider:[t]}),r=Al(i||[]);return n.providerData=n.providerData.filter((e=>r.has(e.providerId))),r.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}(this._delegate,e),this}updateEmail(e){return function(e,t){const n=$(e);return Me(n.auth.app)?Promise.reject(Ba(n.auth)):Hl(n,t,null)}(this._delegate,e)}updatePassword(e){return function(e,t){return Hl($(e),null,t)}(this._delegate,e)}updatePhoneNumber(e){return async function(e,t){const n=$(e);if(Me(n.auth.app))return Promise.reject(Ba(n.auth));await Ol(n,t)}(this._delegate,e)}updateProfile(e){return async function(e,{displayName:t,photoURL:n}){if(void 0===t&&void 0===n)return;const i=$(e),r={idToken:await i.getIdToken(),displayName:t,photoUrl:n,returnSecureToken:!0},s=await yc(i,async function(e,t){return rc(e,"POST","/v1/accounts:update",t)}(i.auth,r));i.displayName=s.displayName||null,i.photoURL=s.photoUrl||null;const o=i.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=i.displayName,o.photoURL=i.photoURL),await i._updateTokensIfNecessary(s)}(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return async function(e,t,n){const i=$(e),r={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&Vl(i.auth,r,n);const{email:s}=await async function(e,t){return al(e,t)}(i.auth,r);s!==e.email&&await e.reload()}(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}ad.USER_MAP=new WeakMap;const cd=$a;class ld{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();const{apiKey:n}=e.options;cd(n,"invalid-api-key",{appName:e.name}),cd(n,"invalid-api-key",{appName:e.name});const i="undefined"!=typeof window?td:void 0;this._delegate=t.initialize({options:{persistence:ud(n,e.name),popupRedirectResolver:i}}),this._delegate._updateErrorMap(La),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?ad.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){!function(e,t,n){const i=Kc(e);$a(i._canInitEmulator,i,"emulator-config-failed"),$a(/^https?:\/\//.test(t),i,"invalid-emulator-scheme");const r=!!(null==n?void 0:n.disableWarnings),s=tl(t),{host:o,port:a}=function(e){const t=tl(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const i=n[2].split("@").pop()||"",r=/^(\[[^\]]+\])(:|$)/.exec(i);if(r){const e=r[1];return{host:e,port:nl(i.substr(e.length+1))}}{const[e,t]=i.split(":");return{host:e,port:nl(t)}}}(t),c=null===a?"":`:${a}`;i.config.emulator={url:`${s}//${o}${c}/`},i.settings.appVerificationDisabledForTesting=!0,i.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:r})}),r||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}(this._delegate,e,t)}applyActionCode(e){return async function(e,t){await async function(e,t){return rc(e,"POST","/v1/accounts:update",ic(e,t))}($(e),{oobCode:t})}(this._delegate,e)}checkActionCode(e){return zl(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await rl($(e),{oobCode:t,newPassword:n}).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&Bl(e),t}))}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return rd(this._delegate,async function(e,t,n){if(Me(e.app))return Promise.reject(Ba(e));const i=Kc(e),r=el(i,{returnSecureToken:!0,email:t,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",kl),s=await r.catch((t=>{throw"auth/password-does-not-meet-requirements"===t.code&&Bl(e),t})),o=await Sl._fromIdTokenResponse(i,"signIn",s);return await i._updateCurrentUser(o.user),o}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return async function(e,t){const n={identifier:t,continueUri:Ja()?Ya():"http://localhost"},{signinMethods:i}=await async function(e,t){return rc(e,"POST","/v1/accounts:createAuthUri",ic(e,t))}($(e),n);return i||[]}(this._delegate,e)}isSignInWithEmailLink(e){return function(e,t){const n=_l.parseLink(t);return"EMAIL_SIGNIN"===(null==n?void 0:n.operation)}(this._delegate,e)}async getRedirectResult(){cd(Ku(),this._delegate,"operation-not-supported-in-this-environment");const e=await async function(e,t){return await Kc(e)._initializationPromise,Xh(e,t,!1)}(this._delegate,td);return e?rd(this._delegate,Promise.resolve(e)):{credential:null,user:null}}addFrameworkForLogging(e){!function(e,t){Kc(e)._logFramework(t)}(this._delegate,e)}onAuthStateChanged(e,t,n){const{next:i,error:r,complete:s}=hd(e,t,n);return this._delegate.onAuthStateChanged(i,r,s)}onIdTokenChanged(e,t,n){const{next:i,error:r,complete:s}=hd(e,t,n);return this._delegate.onIdTokenChanged(i,r,s)}sendSignInLinkToEmail(e,t){return async function(e,t,n){const i=Kc(e),r={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};!function(e,t){$a(t.handleCodeInApp,i,"argument-error"),t&&Vl(i,e,t)}(r,n),await el(i,r,"getOobCode",ll)}(this._delegate,e,t)}sendPasswordResetEmail(e,t){return async function(e,t,n){const i=Kc(e),r={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};n&&Vl(i,r,n),await el(i,r,"getOobCode",cl)}(this._delegate,e,t||void 0)}async setPersistence(e){let t;switch(function(e,t){Ju(Object.values(Yu).includes(t),e,"invalid-persistence-type"),y()?Ju(t!==Yu.SESSION,e,"unsupported-persistence-type"):m()?Ju(t===Yu.NONE,e,"unsupported-persistence-type"):$u()?Ju(t===Yu.NONE||t===Yu.LOCAL&&b(),e,"unsupported-persistence-type"):Ju(t===Yu.NONE||Hu(),e,"unsupported-persistence-type")}(this._delegate,e),e){case Yu.SESSION:t=ch;break;case Yu.LOCAL:t=await Pc(Ch)._isAvailable()?Ch:oh;break;case Yu.NONE:t=Nc;break;default:return ja("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(t)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return rd(this._delegate,async function(e){var t;if(Me(e.app))return Promise.reject(Ba(e));const n=Kc(e);if(await n._initializationPromise,null===(t=n.currentUser)||void 0===t?void 0:t.isAnonymous)return new Sl({user:n.currentUser,providerId:null,operationType:"signIn"});const i=await kl(n,{returnSecureToken:!0}),r=await Sl._fromIdTokenResponse(n,"signIn",i,!0);return await n._updateCurrentUser(r.user),r}(this._delegate))}signInWithCredential(e){return rd(this._delegate,Ml(this._delegate,e))}signInWithCustomToken(e){return rd(this._delegate,async function(e,t){if(Me(e.app))return Promise.reject(Ba(e));const n=Kc(e),i=await async function(e,t){return oc(e,"POST","/v1/accounts:signInWithCustomToken",ic(e,t))}(n,{token:t,returnSecureToken:!0}),r=await Sl._fromIdTokenResponse(n,"signIn",i);return await n._updateCurrentUser(r.user),r}(this._delegate,e))}signInWithEmailAndPassword(e,t){return rd(this._delegate,function(e,t,n){return Me(e.app)?Promise.reject(Ba(e)):Ml($(e),ml.credential(t,n)).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&Bl(e),t}))}(this._delegate,e,t))}signInWithEmailLink(e,t){return rd(this._delegate,async function(e,t,n){if(Me(e.app))return Promise.reject(Ba(e));const i=$(e),r=ml.credentialWithLink(t,n||Ya());return $a(r._tenantId===(i.tenantId||null),i,"tenant-id-mismatch"),Ml(i,r)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return sd(this._delegate,async function(e,t,n){if(Me(e.app))return Promise.reject(Ba(e));const i=Kc(e),r=await Lh(i,t,$(n));return new xh(r,(e=>Ml(i,e)))}(this._delegate,e,t))}async signInWithPopup(e){return cd(Ku(),this._delegate,"operation-not-supported-in-this-environment"),rd(this._delegate,async function(e,t,n){if(Me(e.app))return Promise.reject(Wa(e,"operation-not-supported-in-this-environment"));const i=Kc(e);za(e,t,gl);const r=Fh(i,n);return new zh(i,"signInViaPopup",t,r).executeNotNull()}(this._delegate,e,td))}async signInWithRedirect(e){return cd(Ku(),this._delegate,"operation-not-supported-in-this-environment"),await Xu(this._delegate),function(e,t,n){return async function(e,t,n){if(Me(e.app))return Promise.reject(Ba(e));const i=Kc(e);za(e,t,gl),await i._initializationPromise;const r=Fh(i,n);return await Gh(r,i),r._openRedirect(i,t,"signInViaRedirect")}(e,t,n)}(this._delegate,e,td)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){const{data:n}=await zl($(e),t);return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function hd(e,t,n){let i=e;"function"!=typeof e&&({next:i,error:t,complete:n}=e);const r=i;return{next:e=>r(e&&ad.getOrCreate(e)),error:t,complete:n}}function ud(e,t){const n=function(e,t){const n=Zu();if(!n)return[];const i=Ac(Qu,e,t);switch(n.getItem(i)){case Yu.NONE:return[Nc];case Yu.LOCAL:return[Ch,ch];case Yu.SESSION:return[ch];default:return[]}}(e,t);if("undefined"==typeof self||n.includes(Ch)||n.push(Ch),"undefined"!=typeof window)for(const e of[oh,ch])n.includes(e)||n.push(e);return n.includes(Nc)||n.push(Nc),n}ld.Persistence=Yu;class dd{constructor(){this.providerId="phone",this._delegate=new Mh(nd(ut.auth()))}static credential(e,t){return Mh.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}dd.PHONE_SIGN_IN_METHOD=Mh.PHONE_SIGN_IN_METHOD,dd.PROVIDER_ID=Mh.PROVIDER_ID;const pd=$a;class fd{constructor(e,t,n=ut.app()){var i;pd(null===(i=n.options)||void 0===i?void 0:i.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new Dh(n.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}function _d(e,t){window[e]||(window[e]=t)}!function(e){e.INTERNAL.registerComponent(new K("auth-compat",(e=>{const t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new ld(t,n)}),"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"}},EmailAuthProvider:ml,FacebookAuthProvider:wl,GithubAuthProvider:Il,GoogleAuthProvider:bl,OAuthProvider:yl,SAMLAuthProvider:Tl,PhoneAuthProvider:dd,PhoneMultiFactorGenerator:Su,RecaptchaVerifier:fd,TwitterAuthProvider:El,Auth:ld,AuthCredential:il,Error:I}).setInstantiationMode("LAZY").setMultipleInstances(!1)),e.registerVersion("@firebase/auth-compat","0.5.9")}(ut);const{prcFirebaseConfig:md,prcFirebaseInteractivesConfig:gd}=window;_d("firebase",ut.initializeApp(md)),_d("firebaseDb",ut.database()),_d("firebaseAuth",ut.auth()),_d("interactivesDB",ut.initializeApp(gd,"interactivesDB"))})();; (()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{escapeAmpersand:()=>n,escapeAttribute:()=>u,escapeEditableHTML:()=>i,escapeHTML:()=>c,escapeLessThan:()=>o,escapeQuotationMark:()=>a,isValidAttributeName:()=>p});const r=/[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;function n(e){return e.replace(/&(?!([a-z0-9]+|#[0-9]+|#x[a-f0-9]+);)/gi,"&")}function a(e){return e.replace(/"/g,""")}function o(e){return e.replace(//g,">")}(a(n(e)))}function c(e){return o(n(e))}function i(e){return o(e.replace(/&/g,"&"))}function p(e){return!r.test(e)}(window.wp=window.wp||{}).escapeHtml=t})(); //# sourceMappingURL=index.min.js.map; (()=>{"use strict";var e={4470:(e,t,n)=>{var r=n(1850);t.s=r.createRoot,t.a=r.hydrateRoot},1850:e=>{e.exports=window.ReactDOM}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};(()=>{n.r(r),n.d(r,{Children:()=>e.Children,Component:()=>e.Component,Fragment:()=>e.Fragment,Platform:()=>v,PureComponent:()=>e.PureComponent,RawHTML:()=>R,StrictMode:()=>e.StrictMode,Suspense:()=>e.Suspense,cloneElement:()=>e.cloneElement,concatChildren:()=>f,createContext:()=>e.createContext,createElement:()=>e.createElement,createInterpolateElement:()=>p,createPortal:()=>m.createPortal,createRef:()=>e.createRef,createRoot:()=>g.s,findDOMNode:()=>m.findDOMNode,flushSync:()=>m.flushSync,forwardRef:()=>e.forwardRef,hydrate:()=>m.hydrate,hydrateRoot:()=>g.a,isEmptyElement:()=>y,isValidElement:()=>e.isValidElement,lazy:()=>e.lazy,memo:()=>e.memo,render:()=>m.render,renderToString:()=>Y,startTransition:()=>e.startTransition,switchChildrenNodeName:()=>h,unmountComponentAtNode:()=>m.unmountComponentAtNode,useCallback:()=>e.useCallback,useContext:()=>e.useContext,useDebugValue:()=>e.useDebugValue,useDeferredValue:()=>e.useDeferredValue,useEffect:()=>e.useEffect,useId:()=>e.useId,useImperativeHandle:()=>e.useImperativeHandle,useInsertionEffect:()=>e.useInsertionEffect,useLayoutEffect:()=>e.useLayoutEffect,useMemo:()=>e.useMemo,useReducer:()=>e.useReducer,useRef:()=>e.useRef,useState:()=>e.useState,useSyncExternalStore:()=>e.useSyncExternalStore,useTransition:()=>e.useTransition});const e=window.React;let t,o,i,a;const s=/<(\/)?(\w+)\s*(\/)?>/g;function l(e,t,n,r,o){return{element:e,tokenStart:t,tokenLength:n,prevOffset:r,leadingTextStart:o,children:[]}}function c(n){const r=function(){const e=s.exec(t);if(null===e)return["no-more-tokens"];const n=e.index,[r,o,i,a]=e,l=r.length;return a?["self-closed",i,n,l]:o?["closer",i,n,l]:["opener",i,n,l]}(),[c,p,f,h]=r,m=a.length,g=f>o?o:null;if(!n[p])return u(),!1;switch(c){case"no-more-tokens":if(0!==m){const{leadingTextStart:e,tokenStart:n}=a.pop();i.push(t.substr(e,n))}return u(),!1;case"self-closed":return 0===m?(null!==g&&i.push(t.substr(g,f-g)),i.push(n[p]),o=f+h,!0):(d(l(n[p],f,h)),o=f+h,!0);case"opener":return a.push(l(n[p],f,h,f+h,g)),o=f+h,!0;case"closer":if(1===m)return function(n){const{element:r,leadingTextStart:o,prevOffset:s,tokenStart:l,children:c}=a.pop(),u=n?t.substr(s,n-s):t.substr(s);u&&c.push(u),null!==o&&i.push(t.substr(o,l-o)),i.push((0,e.cloneElement)(r,null,...c))}(f),o=f+h,!0;const r=a.pop(),s=t.substr(r.prevOffset,f-r.prevOffset);r.children.push(s),r.prevOffset=f+h;const c=l(r.element,r.tokenStart,r.tokenLength,f+h);return c.children=r.children,d(c),o=f+h,!0;default:return u(),!1}}function u(){const e=t.length-o;0!==e&&i.push(t.substr(o,e))}function d(n){const{element:r,tokenStart:o,tokenLength:i,prevOffset:s,children:l}=n,c=a[a.length-1],u=t.substr(c.prevOffset,o-c.prevOffset);u&&c.children.push(u),c.children.push((0,e.cloneElement)(r,null,...l)),c.prevOffset=s||o+i}const p=(n,r)=>{if(t=n,o=0,i=[],a=[],s.lastIndex=0,!(t=>{const n="object"==typeof t,r=n&&Object.values(t);return n&&r.length&&r.every((t=>(0,e.isValidElement)(t)))})(r))throw new TypeError("The conversionMap provided is not valid. It must be an object with values that are React Elements");do{}while(c(r));return(0,e.createElement)(e.Fragment,null,...i)};function f(...t){return t.reduce(((t,n,r)=>(e.Children.forEach(n,((n,o)=>{n&&"string"!=typeof n&&(n=(0,e.cloneElement)(n,{key:[r,o].join()})),t.push(n)})),t)),[])}function h(t,n){return t&&e.Children.map(t,((t,r)=>{if("string"==typeof t?.valueOf())return(0,e.createElement)(n,{key:r},t);const{children:o,...i}=t.props;return(0,e.createElement)(n,{key:r,...i},o)}))}var m=n(1850),g=n(4470);const y=e=>"number"!=typeof e&&("string"==typeof e?.valueOf()||Array.isArray(e)?!e.length:!e),v={OS:"web",select:e=>"web"in e?e.web:e.default,isWeb:!0};function b(e){return"[object Object]"===Object.prototype.toString.call(e)}var k=function(){return k=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{"string"==typeof e&&""!==e.trim()&&(r+=e)})),(0,e.createElement)("div",{dangerouslySetInnerHTML:{__html:r},...n})}const{Provider:T,Consumer:A}=(0,e.createContext)(void 0),M=(0,e.forwardRef)((()=>null)),I=new Set(["string","boolean","number"]),L=new Set(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),P=new Set(["allowfullscreen","allowpaymentrequest","allowusermedia","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","typemustmatch"]),j=new Set(["autocapitalize","autocomplete","charset","contenteditable","crossorigin","decoding","dir","draggable","enctype","formenctype","formmethod","http-equiv","inputmode","kind","method","preload","scope","shape","spellcheck","translate","type","wrap"]),H=new Set(["animation","animationIterationCount","baselineShift","borderImageOutset","borderImageSlice","borderImageWidth","columnCount","cx","cy","fillOpacity","flexGrow","flexShrink","floodOpacity","fontWeight","gridColumnEnd","gridColumnStart","gridRowEnd","gridRowStart","lineHeight","opacity","order","orphans","r","rx","ry","shapeImageThreshold","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","tabSize","widows","x","y","zIndex","zoom"]);function z(e,t){return t.some((t=>0===e.indexOf(t)))}function D(e){return"key"===e||"children"===e}function V(e,t){return"style"===e?function(e){if(!1===b(t=e)||void 0!==(n=t.constructor)&&(!1===b(r=n.prototype)||!1===r.hasOwnProperty("isPrototypeOf")))return e;var t,n,r;let o;for(const t in e){const n=e[t];null!=n&&(o?o+=";":o="",o+=U(t)+":"+$(t,n))}return o}(t):t}const W=["accentHeight","alignmentBaseline","arabicForm","baselineShift","capHeight","clipPath","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","dominantBaseline","enableBackground","fillOpacity","fillRule","floodColor","floodOpacity","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","horizAdvX","horizOriginX","imageRendering","letterSpacing","lightingColor","markerEnd","markerMid","markerStart","overlinePosition","overlineThickness","paintOrder","panose1","pointerEvents","renderingIntent","shapeRendering","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","textAnchor","textDecoration","textRendering","underlinePosition","underlineThickness","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","vHanging","vIdeographic","vMathematical","vectorEffect","vertAdvY","vertOriginX","vertOriginY","wordSpacing","writingMode","xmlnsXlink","xHeight"].reduce(((e,t)=>(e[t.toLowerCase()]=t,e)),{}),_=["allowReorder","attributeName","attributeType","autoReverse","baseFrequency","baseProfile","calcMode","clipPathUnits","contentScriptType","contentStyleType","diffuseConstant","edgeMode","externalResourcesRequired","filterRes","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","suppressContentEditableWarning","suppressHydrationWarning","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector"].reduce(((e,t)=>(e[t.toLowerCase()]=t,e)),{}),F=["xlink:actuate","xlink:arcrole","xlink:href","xlink:role","xlink:show","xlink:title","xlink:type","xml:base","xml:lang","xml:space","xmlns:xlink"].reduce(((e,t)=>(e[t.replace(":","").toLowerCase()]=t,e)),{});function N(e){switch(e){case"htmlFor":return"for";case"className":return"class"}const t=e.toLowerCase();return _[t]?_[t]:W[t]?C(W[t]):F[t]?F[t]:t}function U(e){return e.startsWith("--")?e:z(e,["ms","O","Moz","Webkit"])?"-"+C(e):C(e)}function $(e,t){return"number"!=typeof t||0===t||H.has(e)?t:t+"px"}function q(t,n,r={}){if(null==t||!1===t)return"";if(Array.isArray(t))return B(t,n,r);switch(typeof t){case"string":return(0,E.escapeHTML)(t);case"number":return t.toString()}const{type:o,props:i}=t;switch(o){case e.StrictMode:case e.Fragment:return B(i.children,n,r);case R:const{children:t,...o}=i;return X(Object.keys(o).length?"div":null,{...o,dangerouslySetInnerHTML:{__html:t}},n,r)}switch(typeof o){case"string":return X(o,i,n,r);case"function":return o.prototype&&"function"==typeof o.prototype.render?function(e,t,n,r={}){const o=new e(t,r);"function"==typeof o.getChildContext&&Object.assign(r,o.getChildContext());return q(o.render(),n,r)}(o,i,n,r):q(o(i,r),n,r)}switch(o&&o.$$typeof){case T.$$typeof:return B(i.children,i.value,r);case A.$$typeof:return q(i.children(n||o._currentValue),n,r);case M.$$typeof:return q(o.render(i),n,r)}return""}function X(e,t,n,r={}){let o="";if("textarea"===e&&t.hasOwnProperty("value")){o=B(t.value,n,r);const{value:e,...i}=t;t=i}else t.dangerouslySetInnerHTML&&"string"==typeof t.dangerouslySetInnerHTML.__html?o=t.dangerouslySetInnerHTML.__html:void 0!==t.children&&(o=B(t.children,n,r));if(!e)return o;const i=function(e){let t="";for(const n in e){const r=N(n);if(!(0,E.isValidAttributeName)(r))continue;let o=V(n,e[n]);if(!I.has(typeof o))continue;if(D(n))continue;const i=P.has(r);if(i&&!1===o)continue;const a=i||z(n,["data-","aria-"])||j.has(r);("boolean"!=typeof o||a)&&(t+=" "+r,i||("string"==typeof o&&(o=(0,E.escapeAttribute)(o)),t+='="'+o+'"'))}return t}(t);return L.has(e)?"<"+e+i+"/>":"<"+e+i+">"+o+""}function B(e,t,n={}){let r="";e=Array.isArray(e)?e:[e];for(let o=0;o{if(o||"string"==typeof o)return-1===r.indexOf(a)&&(a="solid"),(0,e.createElement)("i",{className:"icon"},(0,e.createElement)("svg",{style:{width:`${l}em`,height:`${l}em`}},(0,e.createElement)("use",{href:`${window.location.origin}/pewresearch-org/wp-content/plugins/prc-icon-library/build/icons/sprites/${a}.svg#${o}`})))},IconLibraryIndex:a})}},a={};function o(e){var l=a[e];if(void 0!==l)return l.exports;var s=a[e]={exports:{}};return r[e](s,s.exports,o),s.exports}o.m=r,e=[],o.O=function(r,a,l,s){if(!a){var i=1/0;for(u=0;u=s)&&Object.keys(o.O).every((function(e){return o.O[e](a[c])}))?a.splice(c--,1):(t=!1,s0&&e[u-1][2]>s;u--)e[u]=e[u-1];e[u]=[a,l,s]},o.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},function(){var e={826:0,431:0};o.O.j=function(r){return 0===e[r]};var r=function(r,a){var l,s,i=a[0],t=a[1],c=a[2],n=0;if(i.some((function(r){return 0!==e[r]}))){for(l in t)o.o(t,l)&&(o.m[l]=t[l]);if(c)var u=c(o)}for(r&&r(a);n