From 1db0e462a96462d4b2788d7163e6b2693c6b6d3b Mon Sep 17 00:00:00 2001 From: light-200 <44830619+light-200@users.noreply.github.com> Date: Tue, 25 Jan 2022 00:20:41 +0530 Subject: [PATCH 1/2] =?UTF-8?q?feat/login=20prompt=20added=20=F0=9F=A5=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/base.css | 2 ++ docs/bundle.js | 2 +- docs/index.html | 1 + docs/style.css | 21 ++++++++++++++++++++- src/functions/getText.js | 17 ++++++++++++----- src/functions/handlePopup.js | 23 +++++++++++++++++++++++ src/ui/uiElements.js | 3 +++ 7 files changed, 62 insertions(+), 7 deletions(-) create mode 100644 src/functions/handlePopup.js diff --git a/docs/base.css b/docs/base.css index 440520b..4d7d6f5 100644 --- a/docs/base.css +++ b/docs/base.css @@ -31,6 +31,7 @@ --lb-list-item-bg-color: var(--lb-header-color); --lb-list-item-color: var(--lb-header-bg-color); --correct-word: rgb(206, 158, 1); + --infoPopup-border-color: rgb(206, 158, 1); } .dark { @@ -45,6 +46,7 @@ --lb-list-item-color: var(--lb-header-bg-color); background-color: var(--background-color); color: var(--font-color); + --infoPopup-border-color: rgb(206, 158, 1); } @media only screen and (max-width: 500px) { diff --git a/docs/bundle.js b/docs/bundle.js index f1a75e9..177ace5 100644 --- a/docs/bundle.js +++ b/docs/bundle.js @@ -1,2 +1,2 @@ /*! For license information please see bundle.js.LICENSE.txt */ -(()=>{var e={306:function(e){!function(t){"use strict";var n=function(){return{escape:function(e){return e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")},parseExtension:t,mimeType:function(e){var n,r;return(n="application/font-woff",r="image/jpeg",{woff:n,woff2:n,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:r,jpeg:r,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml"})[t(e).toLowerCase()]||""},dataAsUrl:function(e,t){return"data:"+t+";base64,"+e},isDataUrl:function(e){return-1!==e.search(/^(data:)/)},canvasToBlob:function(e){return e.toBlob?new Promise((function(t){e.toBlob(t)})):function(e){return new Promise((function(t){for(var n=window.atob(e.toDataURL().split(",")[1]),r=n.length,i=new Uint8Array(r),s=0;s'+e+""})).then((function(e){return''+e+""})).then((function(e){return"data:image/svg+xml;charset=utf-8,"+e}))}(r,t.width||n.width(e),t.height||n.height(e))}))}function l(e,t){return u(e,t).then(n.makeImage).then(n.delay(100)).then((function(r){var i=function(e){var r=document.createElement("canvas");if(r.width=t.width||n.width(e),r.height=t.height||n.height(e),t.bgcolor){var i=r.getContext("2d");i.fillStyle=t.bgcolor,i.fillRect(0,0,r.width,r.height)}return r}(e);return i.getContext("2d").drawImage(r,0,0),i}))}function h(e,t,r){return r||!t||t(e)?Promise.resolve(e).then((function(e){return e instanceof HTMLCanvasElement?n.makeImage(e.toDataURL()):e.cloneNode(!1)})).then((function(r){return function(e,t,r){var i=e.childNodes;return 0===i.length?Promise.resolve(t):function(e,t,n){var r=Promise.resolve();return t.forEach((function(t){r=r.then((function(){return h(t,n)})).then((function(t){t&&e.appendChild(t)}))})),r}(t,n.asArray(i),r).then((function(){return t}))}(e,r,t)})).then((function(t){return function(e,t){return t instanceof Element?Promise.resolve().then((function(){r=window.getComputedStyle(e),i=t.style,r.cssText?i.cssText=r.cssText:function(e,t){n.asArray(e).forEach((function(n){t.setProperty(n,e.getPropertyValue(n),e.getPropertyPriority(n))}))}(r,i);var r,i})).then((function(){[":before",":after"].forEach((function(r){!function(r){var i=window.getComputedStyle(e,r),s=i.getPropertyValue("content");if(""!==s&&"none"!==s){var o=n.uid();t.className=t.className+" "+o;var a=document.createElement("style");a.appendChild(function(e,t,r){var i="."+e+":"+t,s=r.cssText?o(r):a(r);return document.createTextNode(i+"{"+s+"}");function o(e){var t=e.getPropertyValue("content");return e.cssText+" content: "+t+";"}function a(e){return n.asArray(e).map(t).join("; ")+";";function t(t){return t+": "+e.getPropertyValue(t)+(e.getPropertyPriority(t)?" !important":"")}}}(o,r,i)),t.appendChild(a)}}(r)}))})).then((function(){e instanceof HTMLTextAreaElement&&(t.innerHTML=e.value),e instanceof HTMLInputElement&&t.setAttribute("value",e.value)})).then((function(){t instanceof SVGElement&&(t.setAttribute("xmlns","http://www.w3.org/2000/svg"),t instanceof SVGRectElement&&["width","height"].forEach((function(e){var n=t.getAttribute(e);n&&t.style.setProperty(e,n)})))})).then((function(){return t})):t}(e,t)})):Promise.resolve()}function d(e){return i.resolveAll().then((function(t){var n=document.createElement("style");return e.appendChild(n),n.appendChild(document.createTextNode(t)),e}))}function f(e){return s.inlineAll(e).then((function(){return e}))}e.exports=c}()},162:function(e,t,n){var r;void 0===(r=function(){"use strict";function t(e,t,n){var r=new XMLHttpRequest;r.open("GET",e),r.responseType="blob",r.onload=function(){a(r.response,t,n)},r.onerror=function(){console.error("could not download file")},r.send()}function r(e){var t=new XMLHttpRequest;t.open("HEAD",e,!1);try{t.send()}catch(e){}return 200<=t.status&&299>=t.status}function i(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(n){var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(t)}}var s="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof n.g&&n.g.global===n.g?n.g:void 0,o=s.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),a=s.saveAs||("object"!=typeof window||window!==s?function(){}:"download"in HTMLAnchorElement.prototype&&!o?function(e,n,o){var a=s.URL||s.webkitURL,c=document.createElement("a");n=n||e.name||"download",c.download=n,c.rel="noopener","string"==typeof e?(c.href=e,c.origin===location.origin?i(c):r(c.href)?t(e,n,o):i(c,c.target="_blank")):(c.href=a.createObjectURL(e),setTimeout((function(){a.revokeObjectURL(c.href)}),4e4),setTimeout((function(){i(c)}),0))}:"msSaveOrOpenBlob"in navigator?function(e,n,s){if(n=n||e.name||"download","string"!=typeof e)navigator.msSaveOrOpenBlob(function(e,t){return void 0===t?t={autoBom:!1}:"object"!=typeof t&&(console.warn("Deprecated: Expected third argument to be a object"),t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e}(e,s),n);else if(r(e))t(e,n,s);else{var o=document.createElement("a");o.href=e,o.target="_blank",setTimeout((function(){i(o)}))}}:function(e,n,r,i){if((i=i||open("","_blank"))&&(i.document.title=i.document.body.innerText="downloading..."),"string"==typeof e)return t(e,n,r);var a="application/octet-stream"===e.type,c=/constructor/i.test(s.HTMLElement)||s.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||a&&c||o)&&"undefined"!=typeof FileReader){var l=new FileReader;l.onloadend=function(){var e=l.result;e=u?e:e.replace(/^data:[^;]*;/,"data:attachment/file;"),i?i.location.href=e:location=e,i=null},l.readAsDataURL(e)}else{var h=s.URL||s.webkitURL,d=h.createObjectURL(e);i?i.location=d:location.href=d,i=null,setTimeout((function(){h.revokeObjectURL(d)}),4e4)}});s.saveAs=a.saveAs=a,e.exports=a}.apply(t,[]))||(e.exports=r)},676:function(e,t){!function(e){"use strict";function t(e){return Array.prototype.slice.call(e)}function n(e){return new Promise((function(t,n){e.onsuccess=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function r(e,t,r){var i,s=new Promise((function(s,o){n(i=e[t].apply(e,r)).then(s,o)}));return s.request=i,s}function i(e,t,n){var i=r(e,t,n);return i.then((function(e){if(e)return new l(e,i.request)}))}function s(e,t,n){n.forEach((function(n){Object.defineProperty(e.prototype,n,{get:function(){return this[t][n]},set:function(e){this[t][n]=e}})}))}function o(e,t,n,i){i.forEach((function(i){i in n.prototype&&(e.prototype[i]=function(){return r(this[t],i,arguments)})}))}function a(e,t,n,r){r.forEach((function(r){r in n.prototype&&(e.prototype[r]=function(){return this[t][r].apply(this[t],arguments)})}))}function c(e,t,n,r){r.forEach((function(r){r in n.prototype&&(e.prototype[r]=function(){return i(this[t],r,arguments)})}))}function u(e){this._index=e}function l(e,t){this._cursor=e,this._request=t}function h(e){this._store=e}function d(e){this._tx=e,this.complete=new Promise((function(t,n){e.oncomplete=function(){t()},e.onerror=function(){n(e.error)},e.onabort=function(){n(e.error)}}))}function f(e,t,n){this._db=e,this.oldVersion=t,this.transaction=new d(n)}function p(e){this._db=e}s(u,"_index",["name","keyPath","multiEntry","unique"]),o(u,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),c(u,"_index",IDBIndex,["openCursor","openKeyCursor"]),s(l,"_cursor",["direction","key","primaryKey","value"]),o(l,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(e){e in IDBCursor.prototype&&(l.prototype[e]=function(){var t=this,r=arguments;return Promise.resolve().then((function(){return t._cursor[e].apply(t._cursor,r),n(t._request).then((function(e){if(e)return new l(e,t._request)}))}))})})),h.prototype.createIndex=function(){return new u(this._store.createIndex.apply(this._store,arguments))},h.prototype.index=function(){return new u(this._store.index.apply(this._store,arguments))},s(h,"_store",["name","keyPath","indexNames","autoIncrement"]),o(h,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),c(h,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),a(h,"_store",IDBObjectStore,["deleteIndex"]),d.prototype.objectStore=function(){return new h(this._tx.objectStore.apply(this._tx,arguments))},s(d,"_tx",["objectStoreNames","mode"]),a(d,"_tx",IDBTransaction,["abort"]),f.prototype.createObjectStore=function(){return new h(this._db.createObjectStore.apply(this._db,arguments))},s(f,"_db",["name","version","objectStoreNames"]),a(f,"_db",IDBDatabase,["deleteObjectStore","close"]),p.prototype.transaction=function(){return new d(this._db.transaction.apply(this._db,arguments))},s(p,"_db",["name","version","objectStoreNames"]),a(p,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(e){[h,u].forEach((function(n){e in n.prototype&&(n.prototype[e.replace("open","iterate")]=function(){var n=t(arguments),r=n[n.length-1],i=this._store||this._index,s=i[e].apply(i,n.slice(0,-1));s.onsuccess=function(){r(s.result)}})}))})),[u,h].forEach((function(e){e.prototype.getAll||(e.prototype.getAll=function(e,t){var n=this,r=[];return new Promise((function(i){n.iterateCursor(e,(function(e){e?(r.push(e.value),void 0===t||r.length!=t?e.continue():i(r)):i(r)}))}))})})),e.openDb=function(e,t,n){var i=r(indexedDB,"open",[e,t]),s=i.request;return s&&(s.onupgradeneeded=function(e){n&&n(new f(s.result,e.oldVersion,s.transaction))}),i.then((function(e){return new p(e)}))},e.deleteDb=function(e){return r(indexedDB,"deleteDatabase",[e])},Object.defineProperty(e,"__esModule",{value:!0})}(t)}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},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.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e={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_,r=[];for(let t=0;t>2,l=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let n=0;for(let r=0;r>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],o=e[n++];t[r++]=String.fromCharCode((15&i)<<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_,r=[];for(let t=0;t>4;if(r.push(c),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==a){const e=o<<6&192|a;r.push(e)}}}return r},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 t{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 r(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function i(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(r())}function s(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function o(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function a(){const e=r();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}class c extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,c.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,u.prototype.create)}}class u{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],s=i?function(e,t){return e.replace(l,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",o=`${this.serviceName}: ${s} (${r}).`;return new c(r,o,n)}}const l=/\{\$([^}]+)}/g;function h(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],s=t[i];if(d(n)&&d(s)){if(!h(n,s))return!1}else if(n!==s)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function d(e){return null!==e&&"object"==typeof e}function f(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function p(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),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 g{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(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 r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const 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===r.next&&(r.next=y),void 0===r.error&&(r.error=y),void 0===r.complete&&(r.complete=y);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=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 y(){}function v(e,t=1e3,n=2){const r=t*Math.pow(n,e),i=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+i)}function w(e){return e&&e._delegate?e._delegate:e}class I{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 T="[DEFAULT]";class E{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 n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){const e=new t;if(this.instancesDeferred.set(n,e),this.isInitialized(n)||this.shouldAutoInitialize())try{const t=this.getOrInitializeService({instanceIdentifier:n});t&&e.resolve(t)}catch(e){}}return this.instancesDeferred.get(n).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:T})}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="[DEFAULT]"){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="[DEFAULT]"){return this.instances.has(e)}getOptions(e="[DEFAULT]"){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 r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(r);return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===T?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e="[DEFAULT]"){return this.component?this.component.multipleInstances?e:T:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class b{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 E(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const _=[];var S,k;(k=S||(S={}))[k.DEBUG=0]="DEBUG",k[k.VERBOSE=1]="VERBOSE",k[k.INFO=2]="INFO",k[k.WARN=3]="WARN",k[k.ERROR=4]="ERROR",k[k.SILENT=5]="SILENT";const A={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},C=S.INFO,N={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},R=(e,t,...n)=>{if(t{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 O="@firebase/app",P="0.7.11",M=new D("@firebase/app"),x={[O]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},U=new Map,F=new Map;function V(e,t){try{e.container.addComponent(t)}catch(n){M.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function j(e){const t=e.name;if(F.has(t))return M.debug(`There were multiple attempts to register component ${t}.`),!1;F.set(t,e);for(const t of U.values())V(t,e);return!0}function q(e,t){return e.container.getProvider(t)}const B=new u("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","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."});class ${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 I("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 B.create("app-deleted",{appName:this._name})}}const H="9.6.1";function K(e="[DEFAULT]"){const t=U.get(e);if(!t)throw B.create("no-app",{appName:e});return t}function z(e,t,n){var r;let i=null!==(r=x[e])&&void 0!==r?r:e;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${t}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void M.warn(e.join(" "))}j(new I(`${i}-version`,(()=>({library:i,version:t})),"VERSION"))}j(new I("platform-logger",(e=>new L(e)),"PRIVATE")),z(O,P,""),z(O,P,"esm2017"),z("fire-js",""),z("firebase","9.6.1","app");var G=n(676);const W="@firebase/installations",J="0.5.4",X="w:0.5.4",Q=new u("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Y(e){return e instanceof c&&e.code.includes("request-failed")}function Z({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function ee(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function te(e,t){const n=(await t.json()).error;return Q.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function ne({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}async function re(e){const t=await e();return t.status>=500&&t.status<600?e():t}function ie(e){return new Promise((t=>{setTimeout(t,e)}))}const se=/^[cdef][\w-]{21}$/;function oe(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){return(t=e,btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var t}(e);return se.test(t)?t:""}catch(e){return""}}function ae(e){return`${e.appName}!${e.appId}`}const ce=new Map;function ue(e,t){const n=ae(e);le(n,t),function(e,t){const n=(!he&&"BroadcastChannel"in self&&(he=new BroadcastChannel("[Firebase] FID Change"),he.onmessage=e=>{le(e.data.key,e.data.fid)}),he);n&&n.postMessage({key:e,fid:t}),0===ce.size&&he&&(he.close(),he=null)}(n,t)}function le(e,t){const n=ce.get(e);if(n)for(const e of n)e(t)}let he=null;const de="firebase-installations-store";let fe=null;function pe(){return fe||(fe=(0,G.openDb)("firebase-installations-database",1,(e=>{0===e.oldVersion&&e.createObjectStore(de)}))),fe}async function me(e,t){const n=ae(e),r=(await pe()).transaction(de,"readwrite"),i=r.objectStore(de),s=await i.get(n);return await i.put(t,n),await r.complete,s&&s.fid===t.fid||ue(e,t.fid),t}async function ge(e){const t=ae(e),n=(await pe()).transaction(de,"readwrite");await n.objectStore(de).delete(t),await n.complete}async function ye(e,t){const n=ae(e),r=(await pe()).transaction(de,"readwrite"),i=r.objectStore(de),s=await i.get(n),o=t(s);return void 0===o?await i.delete(n):await i.put(o,n),await r.complete,!o||s&&s.fid===o.fid||ue(e,o.fid),o}async function ve(e){let t;const n=await ye(e,(n=>{const r=function(e){return Te(e||{fid:oe(),registrationStatus:0})}(n),i=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine)return{installationEntry:t,registrationPromise:Promise.reject(Q.create("app-offline"))};const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function(e,t){try{const n=await async function(e,{fid:t}){const n=Z(e),r=ne(e),i={fid:t,authVersion:"FIS_v2",appId:e.appId,sdkVersion:X},s={method:"POST",headers:r,body:JSON.stringify(i)},o=await re((()=>fetch(n,s)));if(o.ok){const e=await o.json();return{fid:e.fid||t,registrationStatus:2,refreshToken:e.refreshToken,authToken:ee(e.authToken)}}throw await te("Create Installation",o)}(e,t);return me(e,n)}catch(n){throw Y(n)&&409===n.customData.serverCode?await ge(e):await me(e,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:we(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function we(e){let t=await Ie(e);for(;1===t.registrationStatus;)await ie(100),t=await Ie(e);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await ve(e);return n||t}return t}function Ie(e){return ye(e,(e=>{if(!e)throw Q.create("installation-not-found");return Te(e)}))}function Te(e){return 1===(t=e).registrationStatus&&t.registrationTime+1e4fetch(r,a)));if(c.ok)return ee(await c.json());throw await te("Generate Auth Token",c)}async function be(e,t=!1){let n;const r=await ye(e.appConfig,(r=>{if(!Se(r))throw Q.create("not-registered");const i=r.authToken;if(!t&&(2===(s=i).requestStatus&&!function(e){const t=Date.now();return t{if(!Se(e))throw Q.create("not-registered");return 1===(t=e.authToken).requestStatus&&t.requestTime+1e4{const t=e.getProvider("app").getImmediate(),n=function(e){if(!e||!e.options)throw ke("App Configuration");if(!e.name)throw ke("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw ke(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,platformLoggerProvider:q(t,"platform-logger"),_delete:()=>Promise.resolve()}}),"PUBLIC")),j(new I("installations-internal",(e=>{const t=q(e.getProvider("app").getImmediate(),Ae).getImmediate();return{getId:()=>async function(e){const t=e,{installationEntry:n,registrationPromise:r}=await ve(t.appConfig);return r?r.catch(console.error):be(t).catch(console.error),n.fid}(t),getToken:e=>async function(e,t=!1){const n=e;return await async function(e){const{registrationPromise:t}=await ve(e);t&&await t}(n.appConfig),(await be(n,t)).token}(t,e)}}),"PRIVATE")),z(W,J),z(W,J,"esm2017");const Ce="analytics",Ne="https://www.googletagmanager.com/gtag/js",Re=new D("@firebase/analytics");function De(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}const Le=new u("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Oe=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function Pe(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function Me(e,t=Oe,n){const{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Le.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Le.create("no-api-key")}const o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},a=new Ue;return setTimeout((async()=>{a.abort()}),void 0!==n?n:6e4),xe({appId:r,apiKey:i,measurementId:s},o,a,t)}async function xe(e,{throttleEndTimeMillis:t,backoffCount:n},r,i=Oe){const{appId:s,measurementId:o}=e;try{await function(e,t){return new Promise(((n,r)=>{const i=Math.max(t-Date.now(),0),s=setTimeout(n,i);e.addEventListener((()=>{clearTimeout(s),r(Le.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(r,t)}catch(e){if(o)return Re.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:s,measurementId:o};throw e}try{const t=await async function(e){var t;const{appId:n,apiKey:r}=e,i={method:"GET",headers:Pe(r)},s="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(s,i);if(200!==o.status&&304!==o.status){let e="";try{const n=await o.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(e){}throw Le.create("config-fetch-failed",{httpStatus:o.status,responseMessage:e})}return o.json()}(e);return i.deleteThrottleMetadata(s),t}catch(t){if(!function(e){if(!(e instanceof c&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t)){if(i.deleteThrottleMetadata(s),o)return Re.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${t.message}]`),{appId:s,measurementId:o};throw t}const a=503===Number(t.customData.httpStatus)?v(n,i.intervalMillis,30):v(n,i.intervalMillis),u={throttleEndTimeMillis:Date.now()+a,backoffCount:n+1};return i.setThrottleMetadata(s,u),Re.debug(`Calling attemptFetch again in ${a} millis`),xe(e,u,r,i)}}class Ue{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}async function Fe(e,t,n,r,i,s,o){var a;const c=Me(e);c.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&Re.warn(`The measurement ID in the local Firebase config (${e.options.measurementId}) does not match the measurement ID fetched from the server (${t.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((e=>Re.error(e))),t.push(c);const u=async function(){if("object"!=typeof indexedDB)return Re.warn(Le.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}catch(e){return Re.warn(Le.create("indexeddb-unavailable",{errorInfo:e}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[l,h]=await Promise.all([c,u]);(function(){const e=window.document.getElementsByTagName("script");for(const t of Object.values(e))if(t.src&&t.src.includes(Ne))return t;return null})()||function(e,t){const n=document.createElement("script");n.src=`${Ne}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const d=null!==(a=null==o?void 0:o.config)&&void 0!==a?a:{};return d.origin="firebase",d.update=!0,null!=h&&(d.firebase_id=h),i("config",l.measurementId,d),l.measurementId}class Ve{constructor(e){this.app=e}_delete(){return delete je[this.app.options.appId],Promise.resolve()}}let je={},qe=[];const Be={};let $e,He,Ke="dataLayer",ze=!1;function Ge(e,t,n){!function(){const e=[];if(s()&&e.push("This is a browser extension environment."),"undefined"!=typeof navigator&&navigator.cookieEnabled||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>`(${t+1}) ${e}`)).join(" "),n=Le.create("invalid-analytics-context",{errorInfo:t});Re.warn(n.message)}}();const r=e.options.appId;if(!r)throw Le.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Le.create("no-api-key");Re.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=je[r])throw Le.create("already-exists",{id:r});if(!ze){!function(e){let t=[];Array.isArray(window.dataLayer)?t=window.dataLayer:window.dataLayer=t}();const{wrappedGtag:e,gtagCore:t}=function(e,t,n,r,i){let s=function(...e){window.dataLayer.push(arguments)};return window.gtag&&"function"==typeof window.gtag&&(s=window.gtag),window.gtag=function(e,t,n,r){return async function(i,s,o){try{"event"===i?await async function(e,t,n,r,i){try{let s=[];if(i&&i.send_to){let e=i.send_to;Array.isArray(e)||(e=[e]);const r=await De(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),i=e&&t[e.appId];if(!i){s=[];break}s.push(i)}}0===s.length&&(s=Object.values(t)),await Promise.all(s),e("event",r,i||{})}catch(e){Re.error(e)}}(e,t,n,s,o):"config"===i?await async function(e,t,n,r,i,s){const o=r[i];try{if(o)await t[o];else{const e=(await De(n)).find((e=>e.measurementId===i));e&&await t[e.appId]}}catch(e){Re.error(e)}e("config",i,s)}(e,t,n,r,s,o):e("set",s)}catch(e){Re.error(e)}}}(s,e,t,n),{gtagCore:s,wrappedGtag:window.gtag}}(je,qe,Be);He=e,$e=t,ze=!0}return je[r]=Fe(e,qe,Be,t,$e,Ke,n),new Ve(e)}const We="@firebase/analytics",Je="0.7.4";j(new I(Ce,((e,{options:t})=>Ge(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)),"PUBLIC")),j(new I("analytics-internal",(function(e){try{const t=e.getProvider(Ce).getImmediate();return{logEvent:(e,n,r)=>function(e,t,n,r){e=w(e),async function(e,t,n,r,i){if(i&&i.global)e("event",n,r);else{const i=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:i}))}}(He,je[e.app.options.appId],t,n,r).catch((e=>Re.error(e)))}(t,e,n,r)}}catch(e){throw Le.create("interop-component-reg-failed",{reason:e})}}),"PRIVATE")),z(We,Je),z(We,Je,"esm2017");const Xe=function(e,t={}){"object"!=typeof t&&(t={name:t});const n=Object.assign({name:"[DEFAULT]",automaticDataCollectionEnabled:!1},t),r=n.name;if("string"!=typeof r||!r)throw B.create("bad-app-name",{appName:String(r)});const i=U.get(r);if(i){if(h(e,i.options)&&h(n,i.config))return i;throw B.create("duplicate-app",{appName:r})}const s=new b(r);for(const e of F.values())s.addComponent(e);const o=new $(e,n,s);return U.set(r,o),o}({apiKey:"AIzaSyCtAdfUZ8tR-mODZgkDRe6ZACdDdsA36kU",authDomain:"type-master-ecd50.firebaseapp.com",projectId:"type-master-ecd50",storageBucket:"type-master-ecd50.appspot.com",messagingSenderId:"310756367551",appId:"1:310756367551:web:9823810463c7c3e8e63a0a",measurementId:"MISSING_ENV_VAR".FIREBASE_MEADUREMENT_ID});function Qe(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);ie,"Short delay should be less than long delay!"),this.isMobile=i()||o()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===ht()||"https:"===ht()||s()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function ft(e,t){at(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class pt{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:void ot("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:void ot("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:void ot("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const mt={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error"},gt=new dt(3e4,6e4);function yt(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function vt(e,t,n,r,i={}){return wt(e,i,(async()=>{let i={},s={};r&&("GET"===t?s=r:i={body:JSON.stringify(r)});const o=f(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),pt.fetch()(Tt(e,e.config.apiHost,n,o),Object.assign({method:t,headers:a,referrerPolicy:"no-referrer"},i))}))}async function wt(e,t,n){e._canInitEmulator=!1;const r=Object.assign(Object.assign({},mt),t);try{const t=new Et(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw bt(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[n,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw bt(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===n)throw bt(e,"email-already-in-use",s);const a=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw function(e,t,n){const r=Object.assign(Object.assign({},Ye()),{[t]:n});return new u("auth","Firebase",r).create(t,{appName:e.name})}(e,a,o);nt(e,a)}}catch(t){if(t instanceof c)throw t;nt(e,"network-request-failed")}}async function It(e,t,n,r,i={}){const s=await vt(e,t,n,r,i);return"mfaPendingCredential"in s&&nt(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Tt(e,t,n,r){const i=`${t}${n}?${r}`;return e.config.emulator?ft(e.config,i):`${e.config.apiScheme}://${i}`}class Et{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(rt(this.auth,"timeout"))),gt.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function bt(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=rt(e,t,r);return i.customData._tokenResponse=n,i}function _t(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function St(e){return 1e3*Number(e)}function kt(t){const[n,r,i]=t.split(".");if(void 0===n||void 0===r||void 0===i)return tt("JWT malformed, contained fewer than 3 sections"),null;try{const t=function(t){try{return e.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(r);return t?JSON.parse(t):(tt("Failed to decode base64 JWT payload"),null)}catch(e){return tt("Caught error parsing JWT payload as JSON",e),null}}async function At(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof c&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class Ct{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"===e.code&&this.schedule(!0))}this.schedule()}}class Nt{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=_t(this.lastLoginAt),this.creationTime=_t(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Rt(e){var t;const n=e.auth,r=await e.getIdToken(),i=await At(e,async function(e,t){return vt(e,"POST","/v1/accounts:lookup",t)}(n,{idToken:r}));st(null==i?void 0:i.users.length,n,"internal-error");const s=i.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?s.providerUserInfo.map((e=>{var{providerId:t}=e,n=Qe(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[],a=(c=e.providerData,u=o,[...c.filter((e=>!u.some((t=>t.providerId===e.providerId)))),...u]);var c,u;const l=e.isAnonymous,h=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!l&&h,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new Nt(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,f)}class Dt{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){st(e.idToken,"internal-error"),st(void 0!==e.idToken,"internal-error"),st(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):function(e){const t=kt(e);return st(t,"internal-error"),st(void 0!==t.exp,"internal-error"),st(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e,t=!1){return st(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=await async function(e,t){const n=await wt(e,{},(async()=>{const n=f({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:i}=e.config,s=Tt(e,r,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",pt.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,r,Number(i))}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:r,expirationTime:i}=t,s=new Dt;return n&&(st("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(st("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(st("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new Dt,this.toJSON())}_performRefresh(){return ot("not implemented")}}function Lt(e,t){st("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Ot{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=Qe(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.emailVerified=!1,this.isAnonymous=!1,this.tenantId=null,this.providerData=[],this.proactiveRefresh=new Ct(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.metadata=new Nt(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){const t=await At(this,this.stsTokenManager.getToken(this.auth,e));return st(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=w(e),r=await n.getIdToken(t),i=kt(r);st(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s="object"==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:_t(St(i.auth_time)),issuedAtTime:_t(St(i.iat)),expirationTime:_t(St(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=w(e);await Rt(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(st(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){return new Ot(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){st(!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 Rt(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await At(this,async function(e,t){return vt(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,r,i,s,o,a,c,u;const l=null!==(n=t.displayName)&&void 0!==n?n:void 0,h=null!==(r=t.email)&&void 0!==r?r:void 0,d=null!==(i=t.phoneNumber)&&void 0!==i?i:void 0,f=null!==(s=t.photoURL)&&void 0!==s?s:void 0,p=null!==(o=t.tenantId)&&void 0!==o?o:void 0,m=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=t.createdAt)&&void 0!==c?c:void 0,y=null!==(u=t.lastLoginAt)&&void 0!==u?u:void 0,{uid:v,emailVerified:w,isAnonymous:I,providerData:T,stsTokenManager:E}=t;st(v&&E,e,"internal-error");const b=Dt.fromJSON(this.name,E);st("string"==typeof v,e,"internal-error"),Lt(l,e.name),Lt(h,e.name),st("boolean"==typeof w,e,"internal-error"),st("boolean"==typeof I,e,"internal-error"),Lt(d,e.name),Lt(f,e.name),Lt(p,e.name),Lt(m,e.name),Lt(g,e.name),Lt(y,e.name);const _=new Ot({uid:v,auth:e,email:h,emailVerified:w,displayName:l,isAnonymous:I,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:b,createdAt:g,lastLoginAt:y});return T&&Array.isArray(T)&&(_.providerData=T.map((e=>Object.assign({},e)))),m&&(_._redirectEventId=m),_}static async _fromIdTokenResponse(e,t,n=!1){const r=new Dt;r.updateFromServerResponse(t);const i=new Ot({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Rt(i),i}}class Pt{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){}}Pt.type="NONE";const Mt=Pt;function xt(e,t,n){return`firebase:${e}:${t}:${n}`}class Ut{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=xt(this.userKey,r.apiKey,i),this.fullPersistenceKey=xt("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?Ot._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 Ut(ut(Mt),e,n);const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=r[0]||ut(Mt);const s=xt(n,e.config.apiKey,e.name);let o=null;for(const n of t)try{const t=await n._get(s);if(t){const r=Ot._fromJSON(e,t);n!==i&&(o=r),i=n;break}}catch(e){}const a=r.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new Ut(i,e,n)):new Ut(i,e,n)}}function Ft(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Bt(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Vt(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(Ht(t))return"Blackberry";if(Kt(t))return"Webos";if(jt(t))return"Safari";if((t.includes("chrome/")||qt(t))&&!t.includes("edge/"))return"Chrome";if($t(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 Vt(e=r()){return/firefox\//i.test(e)}function jt(e=r()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function qt(e=r()){return/crios\//i.test(e)}function Bt(e=r()){return/iemobile/i.test(e)}function $t(e=r()){return/android/i.test(e)}function Ht(e=r()){return/blackberry/i.test(e)}function Kt(e=r()){return/webos/i.test(e)}function zt(e=r()){return/iphone|ipad|ipod/i.test(e)}function Gt(e=r()){return zt(e)||$t(e)||Kt(e)||Ht(e)||/windows phone/i.test(e)||Bt(e)}function Wt(e,t=[]){let n;switch(e){case"Browser":n=Ft(r());break;case"Worker":n=`${Ft(r())}-${e}`;break;default:n=e}return`${n}/JsCore/9.6.1/${t.length?t.join(","):"FirebaseCore-web"}`}class Jt{constructor(e,t){this.app=e,this.config=t,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Qt(this),this.idTokenSubscription=new Qt(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=Ze,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=t.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=ut(t)),this._initializationPromise=this.queue((async()=>{var n,r;if(!this._deleted&&(this.persistenceManager=await Ut.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===(r=this.currentUser)||void 0===r?void 0:r.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):void 0}async initializeCurrentUser(e){var t;let n=await this.assertedPersistence.getCurrentUser();if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const r=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,i=null==n?void 0:n._redirectEventId,s=await this.tryRedirectSignIn(e);r&&r!==i||!(null==s?void 0:s.user)||(n=s.user)}return n?n._redirectEventId?(st(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)):this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Rt(e)}catch(e){if("auth/network-request-failed"!==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){const t=e?w(e):null;return t&&st(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){if(!this._deleted)return e&&st(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(e){return this.queue((async()=>{await this.assertedPersistence.setPersistence(ut(e))}))}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new u("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&ut(e)||this._popupRedirectResolver;st(t,this,"argument-error"),this.redirectPersistenceManager=await Ut.create(this,[ut(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,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return st(s,this,"internal-error"),s.then((()=>i(this.currentUser))),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&(this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh()),this.currentUser=e,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 st(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Wt(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};return this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId),e}}function Xt(e){return w(e)}class Qt{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){const n=new g(e,void 0);return n.subscribe.bind(n)}((e=>this.observer=e))}get next(){return st(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}class Yt{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return ot("not implemented")}_getIdTokenResponse(e){return ot("not implemented")}_linkToIdToken(e,t){return ot("not implemented")}_getReauthenticationResolver(e){return ot("not implemented")}}class Zt extends Yt{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new Zt(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Zt(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 async function(e,t){return It(e,"POST","/v1/accounts:signInWithPassword",yt(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return It(e,"POST","/v1/accounts:signInWithEmailLink",yt(e,t))}(e,{email:this._email,oobCode:this._password});default:nt(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return async function(e,t){return vt(e,"POST","/v1/accounts:update",t)}(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return It(e,"POST","/v1/accounts:signInWithEmailLink",yt(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:nt(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function en(e,t){return It(e,"POST","/v1/accounts:signInWithIdp",yt(e,t))}class tn extends Yt{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new tn(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):nt("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:r}=t,i=Qe(t,["providerId","signInMethod"]);if(!n||!r)return null;const s=new tn(n,r);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return en(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,en(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,en(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=f(t)}return e}}const nn={USER_NOT_FOUND:"user-not-found"};class rn extends Yt{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new rn({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new rn({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return It(e,"POST","/v1/accounts:signInWithPhoneNumber",yt(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await It(e,"POST","/v1/accounts:signInWithPhoneNumber",yt(e,t));if(n.temporaryProof)throw bt(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return It(e,"POST","/v1/accounts:signInWithPhoneNumber",yt(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),nn)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;return n||t||r||i?new rn({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class sn{constructor(e){var t,n,r,i,s,o;const a=p(m(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,u=null!==(n=a.oobCode)&&void 0!==n?n:null,l=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!==(r=a.mode)&&void 0!==r?r:null);st(c&&u&&l,"argument-error"),this.apiKey=c,this.operation=l,this.code=u,this.continueUrl=null!==(i=a.continueUrl)&&void 0!==i?i: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=p(m(e)).link,n=t?p(m(t)).deep_link_id:null,r=p(m(e)).deep_link_id;return(r?p(m(r)).link:null)||r||n||t||e}(e);try{return new sn(t)}catch(e){return null}}}class on{constructor(){this.providerId=on.PROVIDER_ID}static credential(e,t){return Zt._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=sn.parseLink(t);return st(n,"argument-error"),Zt._fromEmailAndCode(e,n.code,n.tenantId)}}on.PROVIDER_ID="password",on.EMAIL_PASSWORD_SIGN_IN_METHOD="password",on.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class an{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 cn extends an{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class un extends cn{constructor(){super("facebook.com")}static credential(e){return tn._fromParams({providerId:un.PROVIDER_ID,signInMethod:un.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return un.credentialFromTaggedObject(e)}static credentialFromError(e){return un.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return un.credential(e.oauthAccessToken)}catch(e){return null}}}un.FACEBOOK_SIGN_IN_METHOD="facebook.com",un.PROVIDER_ID="facebook.com";class ln extends cn{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return tn._fromParams({providerId:ln.PROVIDER_ID,signInMethod:ln.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return ln.credentialFromTaggedObject(e)}static credentialFromError(e){return ln.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return ln.credential(t,n)}catch(e){return null}}}ln.GOOGLE_SIGN_IN_METHOD="google.com",ln.PROVIDER_ID="google.com";class hn extends cn{constructor(){super("github.com")}static credential(e){return tn._fromParams({providerId:hn.PROVIDER_ID,signInMethod:hn.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return hn.credentialFromTaggedObject(e)}static credentialFromError(e){return hn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return hn.credential(e.oauthAccessToken)}catch(e){return null}}}hn.GITHUB_SIGN_IN_METHOD="github.com",hn.PROVIDER_ID="github.com";class dn extends cn{constructor(){super("twitter.com")}static credential(e,t){return tn._fromParams({providerId:dn.PROVIDER_ID,signInMethod:dn.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return dn.credentialFromTaggedObject(e)}static credentialFromError(e){return dn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return dn.credential(t,n)}catch(e){return null}}}dn.TWITTER_SIGN_IN_METHOD="twitter.com",dn.PROVIDER_ID="twitter.com";class fn{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){const i=await Ot._fromIdTokenResponse(e,n,r),s=pn(n);return new fn({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const r=pn(n);return new fn({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function pn(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class mn extends c{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,mn.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new mn(e,t,n,r)}}function gn(e,t,n,r){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw mn._fromErrorAndOperation(e,n,t,r);throw n}))}async function yn(e,t,n=!1){const r="signIn",i=await gn(e,r,t),s=await fn._fromIdTokenResponse(e,r,i);return n||await e._updateCurrentUser(s.user),s}async function vn(e,{displayName:t,photoURL:n}){if(void 0===t&&void 0===n)return;const r=w(e),i={idToken:await r.getIdToken(),displayName:t,photoUrl:n,returnSecureToken:!0},s=await At(r,async function(e,t){return vt(e,"POST","/v1/accounts:update",t)}(r.auth,i));r.displayName=s.displayName||null,r.photoURL=s.photoUrl||null;const o=r.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=r.displayName,o.photoURL=r.photoURL),await r._updateTokensIfNecessary(s)}new WeakMap;const wn="__sak";class In{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(wn,"1"),this.storage.removeItem(wn),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 Tn extends In{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=r();return jt(e)||zt(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Gt(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),r=this.localCache[t];n!==r&&e(t,r,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 r=this.storage.getItem(n);if(e.newValue!==r)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const r=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},i=this.storage.getItem(n);a()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,10):r()}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]}}Tn.type="LOCAL";const En=Tn;class bn extends In{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}bn.type="SESSION";const _n=bn;class Sn{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 Sn(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data,s=this.handlersMap[r];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const o=Array.from(s).map((async e=>e(t.origin,i))),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:r,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 kn(e="",t=10){let n="";for(let e=0;e{const c=kn("",20);r.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),o(t.data.response);break;default:clearTimeout(u),clearTimeout(i),a(new Error("invalid_response"))}}},this.handlers.add(s),r.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[r.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function Cn(){return window}function Nn(){return void 0!==Cn().WorkerGlobalScope&&"function"==typeof Cn().importScripts}const Rn="firebaseLocalStorageDb",Dn="firebaseLocalStorage",Ln="fbase_key";class On{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 Pn(e,t){return e.transaction([Dn],t?"readwrite":"readonly").objectStore(Dn)}function Mn(){const e=indexedDB.open(Rn,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(Dn,{keyPath:Ln})}catch(e){n(e)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(Dn)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(Rn);return new On(e).toPromise()}(),t(await Mn()))}))}))}async function xn(e,t,n){const r=Pn(e,!0).put({[Ln]:t,value:n});return new On(r).toPromise()}function Un(e,t){const n=Pn(e,!0).delete(t);return new On(n).toPromise()}class Fn{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 Mn()),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 Nn()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Sn._getInstance(Nn()?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 An(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){if(this.sender&&this.activeServiceWorker&&function(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Mn();return await xn(e,wn,"1"),await Un(e,wn),!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=>xn(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=Pn(e,!1).get(t),r=await new On(n).toPromise();return void 0===r?null:r.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>Un(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=Pn(e,!1).getAll();return new On(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));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()}}Fn.type="LOCAL";const Vn=Fn;function jn(e){return`__${e}${Math.floor(1e6*Math.random())}`}jn("rcb"),new dt(3e4,6e4);class qn{constructor(e){this.providerId=qn.PROVIDER_ID,this.auth=Xt(e)}verifyPhoneNumber(e,t){return async function(e,t,n){var r;const i=await n.verify();try{let s;if(st("string"==typeof i,e,"argument-error"),st("recaptcha"===n.type,e,"argument-error"),s="string"==typeof t?{phoneNumber:t}:t,"session"in s){const t=s.session;if("phoneNumber"in s){st("enroll"===t.type,e,"internal-error");const n=await function(e,t){return vt(e,"POST","/v2/accounts/mfaEnrollment:start",yt(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:i}});return n.phoneSessionInfo.sessionInfo}{st("signin"===t.type,e,"internal-error");const n=(null===(r=s.multiFactorHint)||void 0===r?void 0:r.uid)||s.multiFactorUid;st(n,e,"missing-multi-factor-info");const o=await function(e,t){return vt(e,"POST","/v2/accounts/mfaSignIn:start",yt(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:i}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return vt(e,"POST","/v1/accounts:sendVerificationCode",yt(e,t))}(e,{phoneNumber:s.phoneNumber,recaptchaToken:i});return t}}finally{n._reset()}}(this.auth,e,w(t))}static credential(e,t){return rn._fromVerification(e,t)}static credentialFromResult(e){const t=e;return qn.credentialFromTaggedObject(t)}static credentialFromError(e){return qn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?rn._fromTokenResponse(t,n):null}}qn.PROVIDER_ID="phone",qn.PHONE_SIGN_IN_METHOD="phone";class Bn extends Yt{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return en(e,this._buildIdpRequest())}_linkToIdToken(e,t){return en(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return en(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 $n(e){return yn(e.auth,new Bn(e),e.bypassAuthState)}function Hn(e){const{auth:t,user:n}=e;return st(n,t,"internal-error"),async function(e,t,n=!1){const{auth:r}=e,i="reauthenticate";try{const s=await At(e,gn(r,i,t,e),n);st(s.idToken,r,"internal-error");const o=kt(s.idToken);st(o,r,"internal-error");const{sub:a}=o;return st(e.uid===a,r,"user-mismatch"),fn._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&nt(r,"user-mismatch"),e}}(n,new Bn(e),e.bypassAuthState)}async function Kn(e){const{auth:t,user:n}=e;return st(n,t,"internal-error"),async function(e,t,n=!1){const r=await At(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return fn._forOperation(e,"link",r)}(n,new Bn(e),e.bypassAuthState)}class zn{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return $n;case"linkViaPopup":case"linkViaRedirect":return Kn;case"reauthViaPopup":case"reauthViaRedirect":return Hn;default:nt(this.auth,"internal-error")}}resolve(e){at(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){at(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 Gn=new dt(2e3,1e4);class Wn extends zn{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,Wn.currentPopupAction&&Wn.currentPopupAction.cancel(),Wn.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return st(e,this.auth,"internal-error"),e}async onExecution(){at(1===this.filter.length,"Popup operations only handle one event");const e=kn();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(rt(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(rt(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Wn.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(rt(this.auth,"popup-closed-by-user"))}),2e3):this.pollId=window.setTimeout(e,Gn.get())};e()}}Wn.currentPopupAction=null;const Jn=new Map;class Xn extends zn{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=Jn.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=function(e){return xt("pendingRedirect",e.config.apiKey,e.name)}(t),r=function(e){return ut(e._redirectPersistence)}(e);if(!await r._isAvailable())return!1;const i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth),n=t?await super.execute():null;e=()=>Promise.resolve(n)}catch(t){e=()=>Promise.reject(t)}Jn.set(this.auth._key(),e)}return this.bypassAuthState||Jn.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 Qn(e,t,n=!1){const r=Xt(e),i=function(e,t){return t?ut(t):(st(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}(r,t),s=new Xn(r,i,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,t)),o}class Yn{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 er(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!er(e)){const r=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(rt(this.auth,r))}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(Zn(e))}saveEventToCache(e){this.cachedEventUids.add(Zn(e)),this.lastProcessedEventTime=Date.now()}}function Zn(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function er({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}const tr=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,nr=/^https?/;function rr(e){const t=lt(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!nr.test(n))return!1;if(tr.test(e))return r===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}const ir=new dt(3e4,6e4);function sr(){const e=Cn().___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 r,i,s,o;function a(){sr(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{sr(),n(rt(e,"network-request-failed"))},timeout:ir.get()})}if(null===(i=null===(r=Cn().gapi)||void 0===r?void 0:r.iframes)||void 0===i?void 0:i.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=Cn().gapi)||void 0===s?void 0:s.load)){const t=jn("iframefcb");return Cn()[t]=()=>{gapi.load?a():n(rt(e,"network-request-failed"))},(o=`https://apis.google.com/js/api.js?onload=${t}`,new Promise(((e,t)=>{const n=document.createElement("script");n.setAttribute("src",o),n.onload=e,n.onerror=e=>{const n=rt("internal-error");n.customData=e,t(n)},n.type="text/javascript",n.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(n)}))).catch((e=>n(e)))}a()}})).catch((e=>{throw or=null,e}))}(e),or}const cr=new dt(5e3,15e3),ur={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},lr=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function hr(e){const t=e.config;st(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?ft(t,"emulator/auth/iframe"):`https://${e.config.authDomain}/__/auth/iframe`,r={apiKey:t.apiKey,appName:e.name,v:H},i=lr.get(e.config.apiHost);i&&(r.eid=i);const s=e._getFrameworks();return s.length&&(r.fw=s.join(",")),`${n}?${f(r).slice(1)}`}const dr={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class fr{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function pr(e,t,n,r,i,s){st(e.config.authDomain,e,"auth-domain-config-required"),st(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:H,eventId:i};if(t instanceof an){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(s||{}))o[e]=t}if(t instanceof cn){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];return`${function({config:e}){return e.emulator?ft(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${f(a).slice(1)}`}const mr="webStorageSupport",gr=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=_n,this._completeRedirectFn=Qn}async _openPopup(e,t,n,i){var s;return at(null===(s=this.eventManagers[e._key()])||void 0===s?void 0:s.manager,"_initialize() not called before _openPopup()"),function(e,t,n,i=500,s=600){const o=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-i)/2,0).toString();let c="";const u=Object.assign(Object.assign({},dr),{width:i.toString(),height:s.toString(),top:o,left:a}),l=r().toLowerCase();n&&(c=qt(l)?"_blank":n),Vt(l)&&(t=t||"http://localhost",u.scrollbars="yes");const h=Object.entries(u).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(function(e=r()){var t;return zt(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(l)&&"_self"!==c)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",c),new fr(null);const d=window.open(t||"",c,h);st(d,e,"popup-blocked");try{d.focus()}catch(e){}return new fr(d)}(e,pr(e,t,n,lt(),i),kn())}async _openRedirect(e,t,n,r){var i;return await this._originValidation(e),i=pr(e,t,n,lt(),r),Cn().location.href=i,new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(at(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 ar(e),n=Cn().gapi;return st(n,e,"internal-error"),t.open({where:document.body,url:hr(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:ur,dontclear:!0},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:!1});const i=rt(e,"network-request-failed"),s=Cn().setTimeout((()=>{r(i)}),cr.get());function o(){Cn().clearTimeout(s),n(t)}t.ping(o).then(o,(()=>{r(i)}))}))))}(e),n=new Yn(e);return t.register("authEvent",(t=>(st(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(mr,{type:mr},(n=>{var r;const i=null===(r=null==n?void 0:n[0])||void 0===r?void 0:r.webStorageSupport;void 0!==i&&t(!!i),nt(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 async function(e,t={}){return vt(e,"GET","/v1/projects",t)}(e);for(const e of t)try{if(rr(e))return}catch(e){}nt(e,"unauthorized-domain")}(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Gt()||jt()||zt()}};var yr,vr="@firebase/auth",wr="0.19.4";class Ir{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=>{var n;e((null===(n=t)||void 0===n?void 0:n.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(){st(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Tr(e=K()){const t=q(e,"auth");return t.isInitialized()?t.getImmediate():function(e,t){const n=q(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(h(n.getOptions(),null!=t?t:{}))return e;nt(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:gr,persistence:[Vn,En,_n]})}yr="Browser",j(new I("auth",((e,{options:t})=>{const n=e.getProvider("app").getImmediate(),{apiKey:r,authDomain:i}=n.options;return(e=>{st(r&&!r.includes(":"),"invalid-api-key",{appName:e.name}),st(!(null==i?void 0:i.includes(":")),"argument-error",{appName:e.name});const n={apiKey:r,authDomain:i,clientPlatform:yr,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Wt(yr)},s=new Jt(e,n);return function(e,t){const n=(null==t?void 0:t.persistence)||[],r=(Array.isArray(n)?n:[n]).map(ut);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(s,t),s})(n)}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),j(new I("auth-internal",(e=>(e=>new Ir(e))(Xt(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),z(vr,wr,void 0),z(vr,wr,"esm2017");var Er,br="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{},_r={},Sr=Sr||{},kr=br||self;function Ar(){}function Cr(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Nr(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Rr="closure_uid_"+(1e9*Math.random()>>>0),Dr=0;function Lr(e,t,n){return e.call.apply(e.bind,arguments)}function Or(e,t,n){if(!e)throw Error();if(2t?1:0}e:{var Wr=kr.navigator;if(Wr){var Jr=Wr.userAgent;if(Jr){Hr=Jr;break e}}Hr=""}function Xr(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function Qr(e){const t={};for(const n in e)t[n]=e[n];return t}var Yr="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Zr(e,t){let n,r;for(let t=1;tparseFloat(li)){ti=String(di);break e}}ti=li}var fi,pi={};function mi(){return e=pi,Object.prototype.hasOwnProperty.call(e,9)?e[9]:e[9]=function(){let e=0;const t=Kr(String(ti)).split("."),n=Kr("9").split("."),r=Math.max(t.length,n.length);for(let o=0;0==e&&o>>0);function Vi(e){return"function"==typeof e?e:(e[Fi]||(e[Fi]=function(t){return e.handleEvent(t)}),e[Fi])}function ji(){Ur.call(this),this.i=new Si(this),this.P=this,this.I=null}function qi(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t)t=new vi(t,e);else if(t instanceof vi)t.target=t.target||e;else{var i=t;Zr(t=new vi(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var o=t.g=n[s];i=Bi(o,r,!0,t)&&i}if(i=Bi(o=t.g=e,r,!0,t)&&i,i=Bi(o,r,!1,t)&&i,n)for(s=0;snew Gi),(e=>e.reset()));class Gi{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Wi(e){kr.setTimeout((()=>{throw e}),0)}function Ji(e,t){Ki||function(){var e=kr.Promise.resolve(void 0);Ki=function(){e.then(Yi)}}(),Xi||(Ki(),Xi=!0),Qi.add(e,t)}var Xi=!1,Qi=new class{constructor(){this.h=this.g=null}add(e,t){const n=zi.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Yi(){for(var e;e=Hi();){try{e.h.call(e.g)}catch(e){Wi(e)}var t=zi;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}Xi=!1}function Zi(e,t){ji.call(this),this.h=e||1,this.g=t||kr,this.j=Pr(this.kb,this),this.l=Date.now()}function es(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function ts(e,t,n){if("function"==typeof e)n&&(e=Pr(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Pr(e.handleEvent,e)}return 2147483647{e.g=null,e.i&&(e.i=!1,ns(e))}),e.j);const t=e.h;e.h=null,e.m.apply(null,t)}xr(Zi,ji),(Er=Zi.prototype).da=!1,Er.S=null,Er.kb=function(){if(this.da){var e=Date.now()-this.l;0r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;ot.length?Os:(t=t.substr(r,n),e.C=r+n,t))}function Vs(e){e.Y=Date.now()+e.P,js(e,e.P)}function js(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=vs(Pr(e.eb,e),t)}function qs(e){e.B&&(kr.clearTimeout(e.B),e.B=null)}function Bs(e){0==e.l.G||e.I||da(e.l,e)}function $s(e){qs(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,es(e.W),as(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Hs(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||bo(n.i,e)))if(n.I=e.N,!e.J&&bo(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3i[2]&&n.N&&0==n.A&&!n.v&&(n.v=vs(Pr(n.ab,n),6e3));if(1>=Eo(n.i)&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else pa(n,11)}else if((e.J||n.g==e)&&ha(n),!$r(t))for(i=n.Ca.g.parse(t),t=0;tl)&&(3!=l||oi||this.g&&(this.h.h||this.g.ga()||Jo(this.g)))){this.I||4!=l||7==t||ps(8==t||0>=h?3:2),qs(this);var n=this.g.ba();this.N=n;t:if(xs(this)){var r=Jo(this.g);e="";var i=r.length,s=4==Wo(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){$s(this),Bs(this);var o="";break t}this.h.i=new kr.TextDecoder}for(t=0;tt)throw Error("Bad port number "+t);e.m=t}else e.m=null}function to(e,t,n){t instanceof fo?(e.h=t,function(e,t){t&&!e.j&&(po(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(mo(this,t),yo(this,n,e))}),e)),e.j=t}(e.h,e.g)):(n||(t=so(t,lo)),e.h=new fo(t,e.g))}function no(e,t,n){e.h.set(t,n)}function ro(e){return no(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function io(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function so(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,oo),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function oo(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Xs.prototype.toString=function(){var e=[],t=this.j;t&&e.push(so(t,ao,!0),":");var n=this.i;return(n||"file"==t)&&(e.push("//"),(t=this.s)&&e.push(so(t,ao,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&e.push("/"),e.push(so(n,"/"==n.charAt(0)?uo:co,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",so(n,ho)),e.join("")};var ao=/[#\/\?@]/g,co=/[#\?:]/g,uo=/[#\?]/g,lo=/[#\?@]/g,ho=/#/g;function fo(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function po(e){e.g||(e.g=new zs,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n2*e.i&&Gs(e)))}function go(e,t){return po(e),t=vo(e,t),Ws(e.g.h,t)}function yo(e,t,n){mo(e,t),0=e.j}function Eo(e){return e.h?1:e.g?e.g.size:0}function bo(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function _o(e,t){e.g?e.g.add(t):e.h=t}function So(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function ko(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.D);return t}return Br(e.i)}function Ao(){}function Co(){this.g=new Ao}function No(e,t,n){const r=n||"";try{Ks(e,(function(e,n){let i=e;Nr(e)&&(i=$i(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function Ro(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function Do(e){this.l=e.$b||null,this.j=e.ib||!1}function Lo(e,t){ji.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=Oo,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}wo.prototype.cancel=function(){if(this.i=ko(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},Ao.prototype.stringify=function(e){return kr.JSON.stringify(e,void 0)},Ao.prototype.parse=function(e){return kr.JSON.parse(e,void 0)},xr(Do,Ts),Do.prototype.g=function(){return new Lo(this.l,this.j)},Do.prototype.i=function(e){return function(){return e}}({}),xr(Lo,ji);var Oo=0;function Po(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function Mo(e){e.readyState=4,e.l=null,e.j=null,e.A=null,xo(e)}function xo(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(Er=Lo.prototype).open=function(e,t){if(this.readyState!=Oo)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,xo(this)},Er.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||kr).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},Er.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mo(this)),this.readyState=Oo},Er.Va=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,xo(this)),this.g&&(this.readyState=3,xo(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==kr.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;Po(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},Er.Sa=function(e){if(this.g){if(this.u&&e.value)this.response.push(e.value);else if(!this.u){var t=e.value?e.value:new Uint8Array(0);(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?Mo(this):xo(this),3==this.readyState&&Po(this)}},Er.Ua=function(e){this.g&&(this.response=this.responseText=e,Mo(this))},Er.Ta=function(e){this.g&&(this.response=e,Mo(this))},Er.ha=function(){this.g&&Mo(this)},Er.setRequestHeader=function(e,t){this.v.append(e,t)},Er.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},Er.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Lo.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var Uo=kr.JSON.parse;function Fo(e){ji.call(this),this.headers=new zs,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=Vo,this.K=this.L=!1}xr(Fo,ji);var Vo="",jo=/^https?$/i,qo=["POST","PUT"];function Bo(e){return"content-type"==e.toLowerCase()}function $o(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Ho(e),zo(e)}function Ho(e){e.D||(e.D=!0,qi(e,"complete"),qi(e,"error"))}function Ko(e){if(e.h&&void 0!==Sr&&(!e.C[1]||4!=Wo(e)||2!=e.ba()))if(e.v&&4==Wo(e))ts(e.Fa,0,e);else if(qi(e,"readystatechange"),4==Wo(e)){e.h=!1;try{const a=e.ba();e:switch(a){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===a){var i=String(e.H).match(Js)[1]||null;if(!i&&kr.self&&kr.self.location){var s=kr.self.location.protocol;i=s.substr(0,s.length-1)}r=!jo.test(i?i.toLowerCase():"")}n=r}if(n)qi(e,"complete"),qi(e,"success");else{e.m=6;try{var o=2n)t=Math.max(0,i[o].h-100),s=!1;else try{No(a,e,"req"+n+"_")}catch(e){r&&r(a)}}if(s){r=e.join("&");break e}}}return e=e.l.splice(0,n),t.D=e,r}function aa(e){e.g||e.u||(e.Y=1,Ji(e.Ga,e),e.A=0)}function ca(e){return!(e.g||e.u||3<=e.A||(e.Y++,e.u=vs(Pr(e.Ga,e),fa(e,e.A)),e.A++,0))}function ua(e){null!=e.B&&(kr.clearTimeout(e.B),e.B=null)}function la(e){e.g=new Ns(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=Qs(e.oa);no(t,"RID","rpc"),no(t,"SID",e.J),no(t,"CI",e.N?"0":"1"),no(t,"AID",e.U),sa(e,t),no(t,"TYPE","xmlhttp"),e.o&&e.s&&Xo(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=ro(Qs(t)),n.s=null,n.U=!0,Ms(n,e)}function ha(e){null!=e.v&&(kr.clearTimeout(e.v),e.v=null)}function da(e,t){var n=null;if(e.g==t){ha(e),ua(e),e.g=null;var r=2}else{if(!bo(e.i,t))return;n=t.D,So(e.i,t),r=1}if(e.I=t.N,0!=e.G)if(t.i)if(1==r){n=t.s?t.s.length:0,t=Date.now()-t.F;var i=e.C;qi(r=ds(),new ys(r,n,t,i)),ra(e)}else aa(e);else if(3==(i=t.o)||0==i&&0=e.i.j-(e.m?1:0)||(e.m?(e.l=t.D.concat(e.l),0):1==e.G||2==e.G||e.C>=(e.Xa?0:e.Ya)||(e.m=vs(Pr(e.Ha,e,t),fa(e,e.C)),e.C++,0)))}(e,t)||2==r&&ca(e)))switch(n&&0t?null:"string"==typeof e?e.charAt(t):e[t]}(i.T()),n=kr.FormData&&e instanceof kr.FormData,!(0<=Vr(qo,t))||r||n||i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach((function(e,t){this.g.setRequestHeader(t,e)}),this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Go(this),0=this.O)){var e=2*this.O;this.h.info("BP detection timer enabled: "+e),this.B=vs(Pr(this.bb,this),e)}},Er.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,gs(10),ea(this),la(this))},Er.ab=function(){null!=this.v&&(this.v=null,ea(this),ca(this),gs(19))},Er.jb=function(e){e?(this.h.info("Successfully pinged google.com"),gs(2)):(this.h.info("Failed to ping google.com"),gs(1))},(Er=va.prototype).xa=function(){},Er.wa=function(){},Er.va=function(){},Er.ua=function(){},Er.Oa=function(){},wa.prototype.g=function(e,t){return new Ia(e,t)},xr(Ia,ji),Ia.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),Ji(Pr(e.hb,e,t))),gs(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=ga(e,null,e.W),ra(e)},Ia.prototype.close=function(){Zo(this.g)},Ia.prototype.u=function(e){if("string"==typeof e){var t={};t.__data__=e,na(this.g,t)}else this.v?((t={}).__data__=$i(e),na(this.g,t)):na(this.g,e)},Ia.prototype.M=function(){this.g.j=null,delete this.j,Zo(this.g),delete this.g,Ia.Z.M.call(this)},xr(Ta,ks),xr(Ea,As),xr(ba,va),ba.prototype.xa=function(){qi(this.g,"a")},ba.prototype.wa=function(e){qi(this.g,new Ta(e))},ba.prototype.va=function(e){qi(this.g,new Ea(e))},ba.prototype.ua=function(){qi(this.g,"b")},wa.prototype.createWebChannel=wa.prototype.g,Ia.prototype.send=Ia.prototype.u,Ia.prototype.open=Ia.prototype.m,Ia.prototype.close=Ia.prototype.close,ws.NO_ERROR=0,ws.TIMEOUT=8,ws.HTTP_ERROR=6,Is.COMPLETE="complete",bs.EventType=Ss,Ss.OPEN="a",Ss.CLOSE="b",Ss.ERROR="c",Ss.MESSAGE="d",ji.prototype.listen=ji.prototype.N,Fo.prototype.listenOnce=Fo.prototype.O,Fo.prototype.getLastError=Fo.prototype.La,Fo.prototype.getLastErrorCode=Fo.prototype.Da,Fo.prototype.getStatus=Fo.prototype.ba,Fo.prototype.getResponseJson=Fo.prototype.Qa,Fo.prototype.getResponseText=Fo.prototype.ga,Fo.prototype.send=Fo.prototype.ea;var _a=_r.createWebChannelTransport=function(){return new wa},Sa=_r.getStatEventTarget=function(){return ds()},ka=_r.ErrorCode=ws,Aa=_r.EventType=Is,Ca=_r.Event=ls,Na=_r.Stat={rb:0,ub:1,vb:2,Ob:3,Tb:4,Qb:5,Rb:6,Pb:7,Nb:8,Sb:9,PROXY:10,NOPROXY:11,Lb:12,Hb:13,Ib:14,Gb:15,Jb:16,Kb:17,nb:18,mb:19,ob:20},Ra=_r.FetchXmlHttpFactory=Do,Da=_r.WebChannel=bs,La=_r.XhrIo=Fo;const Oa="@firebase/firestore";class Pa{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}Pa.UNAUTHENTICATED=new Pa(null),Pa.GOOGLE_CREDENTIALS=new Pa("google-credentials-uid"),Pa.FIRST_PARTY=new Pa("first-party-uid"),Pa.MOCK_USER=new Pa("mock-user");let Ma="9.6.1";const xa=new D("@firebase/firestore");function Ua(){return xa.logLevel}function Fa(e,...t){if(xa.logLevel<=S.DEBUG){const n=t.map(qa);xa.debug(`Firestore (${Ma}): ${e}`,...n)}}function Va(e,...t){if(xa.logLevel<=S.ERROR){const n=t.map(qa);xa.error(`Firestore (${Ma}): ${e}`,...n)}}function ja(e,...t){if(xa.logLevel<=S.WARN){const n=t.map(qa);xa.warn(`Firestore (${Ma}): ${e}`,...n)}}function qa(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}var t}function Ba(e="Unexpected state"){const t=`FIRESTORE (${Ma}) INTERNAL ASSERTION FAILED: `+e;throw Va(t),new Error(t)}function $a(e,t){e||Ba()}function Ha(e,t){return e}const Ka={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class za extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Ga{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class Wa{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Ja{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(Pa.UNAUTHENTICATED)))}shutdown(){}}class Xa{constructor(e){this.t=e,this.currentUser=Pa.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new Ga;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Ga,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{Fa("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),s()};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(Fa("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Ga)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(Fa("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?($a("string"==typeof t.accessToken),new Wa(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return $a(null===e||"string"==typeof e),new Pa(e)}}class Qa{constructor(e,t,n){this.type="FirstParty",this.user=Pa.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);const r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class Ya{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Qa(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable((()=>t(Pa.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class Za{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class ec{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null}start(e,t){this.o=n=>{e.enqueueRetryable((()=>(e=>(null!=e.error&&Fa("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`),t(e.token)))(n)))};const n=e=>{Fa("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit((e=>n(e))),setTimeout((()=>{if(!this.appCheck){const e=this.g.getImmediate({optional:!0});e?n(e):Fa("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?($a("string"==typeof e.token),new Za(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class tc{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.p(e),this.T=e=>t.writeSequenceNumber(e))}p(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.T&&this.T(e),e}}function nc(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;tt?1:0}function sc(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}class oc{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new za(Ka.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new za(Ka.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new za(Ka.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new za(Ka.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return oc.fromMillis(Date.now())}static fromDate(e){return oc.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new oc(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?ic(this.nanoseconds,e.nanoseconds):ic(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class ac{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ac(e)}static min(){return new ac(new oc(0,0))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function cc(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function uc(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function lc(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class hc{constructor(e,t,n){void 0===t?t=0:t>e.length&&Ba(),void 0===n?n=e.length-t:n>e.length-t&&Ba(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===hc.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof hc?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.lengthi)return 1}return e.lengtht.length?1:0}}class dc extends hc{construct(e,t,n){return new dc(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new za(Ka.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new dc(t)}static emptyPath(){return new dc([])}}const fc=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class pc extends hc{construct(e,t,n){return new pc(e,t,n)}static isValidIdentifier(e){return fc.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),pc.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new pc(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new za(Ka.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;re.isEqual(t)))}}class gc{constructor(e){this.binaryString=e}static fromBase64String(e){const t=atob(e);return new gc(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n=2&&this.path.get(this.path.length-2)===e}isEqual(e){return null!==e&&0===dc.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return dc.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new kc(new dc(e.slice()))}}function Ac(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?Tc(e)?4:10:Ba()}function Cc(e,t){const n=Ac(e);if(n!==Ac(t))return!1;switch(n){case 0:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return bc(e).isEqual(bc(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=vc(e.timestampValue),r=vc(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return Ic(e.bytesValue).isEqual(Ic(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return wc(e.geoPointValue.latitude)===wc(t.geoPointValue.latitude)&&wc(e.geoPointValue.longitude)===wc(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return wc(e.integerValue)===wc(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=wc(e.doubleValue),r=wc(t.doubleValue);return n===r?Sc(n)===Sc(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return sc(e.arrayValue.values||[],t.arrayValue.values||[],Cc);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(cc(n)!==cc(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Cc(n[e],r[e])))return!1;return!0}(e,t);default:return Ba()}}function Nc(e,t){return void 0!==(e.values||[]).find((e=>Cc(e,t)))}function Rc(e,t){const n=Ac(e),r=Ac(t);if(n!==r)return ic(n,r);switch(n){case 0:return 0;case 1:return ic(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=wc(e.integerValue||e.doubleValue),r=wc(t.integerValue||t.doubleValue);return nr?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return Dc(e.timestampValue,t.timestampValue);case 4:return Dc(bc(e),bc(t));case 5:return ic(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ic(e),r=Ic(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let e=0;et.mapValue.fields[e]=Vc(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Vc(e.arrayValue.values[n]);return t}return Object.assign({},e)}class jc{constructor(e){this.value=e}static empty(){return new jc({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=Vc(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Fc(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Cc(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;ne[t]=n));for(const t of n)delete e[t]}clone(){return new jc(Vc(this.value))}}function qc(e){const t=[];return uc(e.fields,((e,n)=>{const r=new pc([e]);if(Fc(n)){const e=qc(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new mc(t)}class Bc{constructor(e,t,n,r,i){this.key=e,this.documentType=t,this.version=n,this.data=r,this.documentState=i}static newInvalidDocument(e){return new Bc(e,0,ac.min(),jc.empty(),0)}static newFoundDocument(e,t,n){return new Bc(e,1,t,n,0)}static newNoDocument(e,t){return new Bc(e,2,t,jc.empty(),0)}static newUnknownDocument(e,t){return new Bc(e,3,t,jc.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=jc.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=jc.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Bc&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}clone(){return new Bc(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class $c{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.R=null}}function Hc(e,t=null,n=[],r=[],i=null,s=null,o=null){return new $c(e,t,n,r,i,s,o)}function Kc(e){const t=Ha(e);if(null===t.R){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>function(e){return e.field.canonicalString()+e.op.toString()+Lc(e.value)}(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),_c(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=iu(t.startAt)),t.endAt&&(e+="|ub:",e+=iu(t.endAt)),t.R=e}return t.R}function zc(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n":return e>0;case">=":return e>=0;default:return Ba()}}V(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}}class Jc extends Wc{constructor(e,t,n){super(e,t,n),this.key=kc.fromName(n.referenceValue)}matches(e){const t=kc.comparator(e.key,this.key);return this.v(t)}}class Xc extends Wc{constructor(e,t){super(e,"in",t),this.keys=Yc(0,t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class Qc extends Wc{constructor(e,t){super(e,"not-in",t),this.keys=Yc(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function Yc(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>kc.fromName(e.referenceValue)))}class Zc extends Wc{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Mc(t)&&Nc(t.arrayValue,this.value)}}class eu extends Wc{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Nc(this.value.arrayValue,t)}}class tu extends Wc{constructor(e,t){super(e,"not-in",t)}matches(e){if(Nc(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Nc(this.value.arrayValue,t)}}class nu extends Wc{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Mc(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Nc(this.value.arrayValue,e)))}}class ru{constructor(e,t){this.position=e,this.before=t}}function iu(e){return`${e.before?"b":"a"}:${e.position.map((e=>Lc(e))).join(",")}`}class su{constructor(e,t="asc"){this.field=e,this.dir=t}}function ou(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}function au(e,t,n){let r=0;for(let i=0;i0?e.explicitOrderBy[0].field:null}function pu(e){for(const t of e.filters)if(t.V())return t.field;return null}function mu(e){const t=Ha(e);if(null===t.S){t.S=[];const e=pu(t),n=fu(t);if(null!==e&&null===n)e.isKeyField()||t.S.push(new su(e)),t.S.push(new su(pc.keyField(),"asc"));else{let e=!1;for(const n of t.explicitOrderBy)t.S.push(n),n.field.isKeyField()&&(e=!0);if(!e){const e=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.S.push(new su(pc.keyField(),e))}}}return t.S}function gu(e){const t=Ha(e);if(!t.D)if("F"===t.limitType)t.D=Hc(t.path,t.collectionGroup,mu(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const n of mu(t)){const t="desc"===n.dir?"asc":"desc";e.push(new su(n.field,t))}const n=t.endAt?new ru(t.endAt.position,!t.endAt.before):null,r=t.startAt?new ru(t.startAt.position,!t.startAt.before):null;t.D=Hc(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.D}function yu(e,t,n){return new uu(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function vu(e,t){return zc(gu(e),gu(t))&&e.limitType===t.limitType}function wu(e){return`${Kc(gu(e))}|lt:${e.limitType}`}function Iu(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>{return`${(t=e).field.canonicalString()} ${t.op} ${Lc(t.value)}`;var t})).join(", ")}]`),_c(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: "+iu(e.startAt)),e.endAt&&(t+=", endAt: "+iu(e.endAt)),`Target(${t})`}(gu(e))}; limitType=${e.limitType})`}function Tu(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):kc.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of e.explicitOrderBy)if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!au(e.startAt,mu(e),t)||e.endAt&&au(e.endAt,mu(e),t))}(e,t)}function Eu(e){return(t,n)=>{let r=!1;for(const i of mu(e)){const e=bu(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function bu(e,t,n){const r=e.field.isKeyField()?kc.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Rc(r,i):Ba()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Ba()}}function _u(e,t){if(e.C){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Sc(t)?"-0":t}}function Su(e){return{integerValue:""+e}}function ku(e,t){return function(e){return"number"==typeof e&&Number.isInteger(e)&&!Sc(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}(t)?Su(t):_u(e,t)}class Au{constructor(){this._=void 0}}function Cu(e,t,n){return e instanceof Du?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof Lu?Ou(e,t):e instanceof Pu?Mu(e,t):function(e,t){const n=Ru(e,t),r=Uu(n)+Uu(e.N);return Pc(n)&&Pc(e.N)?Su(r):_u(e.k,r)}(e,t)}function Nu(e,t,n){return e instanceof Lu?Ou(e,t):e instanceof Pu?Mu(e,t):n}function Ru(e,t){return e instanceof xu?Pc(n=t)||function(e){return!!e&&"doubleValue"in e}(n)?t:{integerValue:0}:null;var n}class Du extends Au{}class Lu extends Au{constructor(e){super(),this.elements=e}}function Ou(e,t){const n=Fu(t);for(const t of e.elements)n.some((e=>Cc(e,t)))||n.push(t);return{arrayValue:{values:n}}}class Pu extends Au{constructor(e){super(),this.elements=e}}function Mu(e,t){let n=Fu(t);for(const t of e.elements)n=n.filter((e=>!Cc(e,t)));return{arrayValue:{values:n}}}class xu extends Au{constructor(e,t){super(),this.k=e,this.N=t}}function Uu(e){return wc(e.integerValue||e.doubleValue)}function Fu(e){return Mc(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Vu{constructor(e,t){this.version=e,this.transformResults=t}}class ju{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new ju}static exists(e){return new ju(void 0,e)}static updateTime(e){return new ju(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function qu(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Bu{}function $u(e,t,n){e instanceof Wu?function(e,t,n){const r=e.value.clone(),i=Qu(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Ju?function(e,t,n){if(!qu(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=Qu(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Xu(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function Hu(e,t,n){e instanceof Wu?function(e,t,n){if(!qu(e.precondition,t))return;const r=e.value.clone(),i=Yu(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(Gu(t),r).setHasLocalMutations()}(e,t,n):e instanceof Ju?function(e,t,n){if(!qu(e.precondition,t))return;const r=Yu(e.fieldTransforms,n,t),i=t.data;i.setAll(Xu(e)),i.setAll(r),t.convertToFoundDocument(Gu(t),i).setHasLocalMutations()}(e,t,n):function(e,t){qu(e.precondition,t)&&t.convertToNoDocument(ac.min())}(e,t)}function Ku(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=Ru(r.transform,e||null);null!=i&&(null==n&&(n=jc.empty()),n.set(r.field,i))}return n||null}function zu(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&sc(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof Lu&&t instanceof Lu||e instanceof Pu&&t instanceof Pu?sc(e.elements,t.elements,Cc):e instanceof xu&&t instanceof xu?Cc(e.N,t.N):e instanceof Du&&t instanceof Du}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}function Gu(e){return e.isFoundDocument()?e.version:ac.min()}class Wu extends Bu{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Ju extends Bu{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}}function Xu(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function Qu(e,t,n){const r=new Map;$a(e.length===n.length);for(let i=0;i0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new ol(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ol(this.root,e,this.comparator,!1)}getReverseIterator(){return new ol(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ol(this.root,e,this.comparator,!0)}}class ol{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class al{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:al.RED,this.left=null!=r?r:al.EMPTY,this.right=null!=i?i:al.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new al(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return al.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return al.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,al.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,al.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Ba();if(this.right.isRed())throw Ba();const e=this.left.check();if(e!==this.right.check())throw Ba();return e+(this.isRed()?0:1)}}al.EMPTY=null,al.RED=!0,al.BLACK=!1,al.EMPTY=new class{constructor(){this.size=0}get key(){throw Ba()}get value(){throw Ba()}get color(){throw Ba()}get left(){throw Ba()}get right(){throw Ba()}copy(e,t,n,r,i){return this}insert(e,t,n){return new al(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class cl{constructor(e){this.comparator=e,this.data=new sl(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ul(this.data.getIterator())}getIteratorFrom(e){return new ul(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size{t=t.add(e)})),t}isEqual(e){if(!(e instanceof cl))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new cl(this.comparator);return t.data=e,t}}class ul{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const ll=new sl(kc.comparator);function hl(){return ll}const dl=new sl(kc.comparator);function fl(){return dl}const pl=new sl(kc.comparator);const ml=new cl(kc.comparator);function gl(...e){let t=ml;for(const n of e)t=t.add(n);return t}const yl=new cl(ic);function vl(){return yl}class wl{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,Il.createSynthesizedTargetChangeForCurrentChange(e,t)),new wl(ac.min(),n,vl(),hl(),gl())}}class Il{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t){return new Il(gc.EMPTY_BYTE_STRING,t,gl(),gl(),gl())}}class Tl{constructor(e,t,n,r){this.$=e,this.removedTargetIds=t,this.key=n,this.F=r}}class El{constructor(e,t){this.targetId=e,this.O=t}}class bl{constructor(e,t,n=gc.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class _l{constructor(){this.M=0,this.L=Al(),this.B=gc.EMPTY_BYTE_STRING,this.U=!1,this.q=!0}get current(){return this.U}get resumeToken(){return this.B}get K(){return 0!==this.M}get j(){return this.q}W(e){e.approximateByteSize()>0&&(this.q=!0,this.B=e)}G(){let e=gl(),t=gl(),n=gl();return this.L.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:Ba()}})),new Il(this.B,this.U,e,t,n)}H(){this.q=!1,this.L=Al()}J(e,t){this.q=!0,this.L=this.L.insert(e,t)}Y(e){this.q=!0,this.L=this.L.remove(e)}X(){this.M+=1}Z(){this.M-=1}tt(){this.q=!0,this.U=!0}}class Sl{constructor(e){this.et=e,this.nt=new Map,this.st=hl(),this.it=kl(),this.rt=new cl(ic)}ot(e){for(const t of e.$)e.F&&e.F.isFoundDocument()?this.at(t,e.F):this.ct(t,e.key,e.F);for(const t of e.removedTargetIds)this.ct(t,e.key,e.F)}ut(e){this.forEachTarget(e,(t=>{const n=this.ht(t);switch(e.state){case 0:this.lt(t)&&n.W(e.resumeToken);break;case 1:n.Z(),n.K||n.H(),n.W(e.resumeToken);break;case 2:n.Z(),n.K||this.removeTarget(t);break;case 3:this.lt(t)&&(n.tt(),n.W(e.resumeToken));break;case 4:this.lt(t)&&(this.ft(t),n.W(e.resumeToken));break;default:Ba()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.nt.forEach(((e,n)=>{this.lt(n)&&t(n)}))}dt(e){const t=e.targetId,n=e.O.count,r=this.wt(t);if(r){const e=r.target;if(Gc(e))if(0===n){const n=new kc(e.path);this.ct(t,n,Bc.newNoDocument(n,ac.min()))}else $a(1===n);else this._t(t)!==n&&(this.ft(t),this.rt=this.rt.add(t))}}gt(e){const t=new Map;this.nt.forEach(((n,r)=>{const i=this.wt(r);if(i){if(n.current&&Gc(i.target)){const t=new kc(i.target.path);null!==this.st.get(t)||this.yt(r,t)||this.ct(r,t,Bc.newNoDocument(t,e))}n.j&&(t.set(r,n.G()),n.H())}}));let n=gl();this.it.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.wt(e);return!t||2===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))}));const r=new wl(e,t,this.rt,this.st,n);return this.st=hl(),this.it=kl(),this.rt=new cl(ic),r}at(e,t){if(!this.lt(e))return;const n=this.yt(e,t.key)?2:0;this.ht(e).J(t.key,n),this.st=this.st.insert(t.key,t),this.it=this.it.insert(t.key,this.Tt(t.key).add(e))}ct(e,t,n){if(!this.lt(e))return;const r=this.ht(e);this.yt(e,t)?r.J(t,1):r.Y(t),this.it=this.it.insert(t,this.Tt(t).delete(e)),n&&(this.st=this.st.insert(t,n))}removeTarget(e){this.nt.delete(e)}_t(e){const t=this.ht(e).G();return this.et.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}X(e){this.ht(e).X()}ht(e){let t=this.nt.get(e);return t||(t=new _l,this.nt.set(e,t)),t}Tt(e){let t=this.it.get(e);return t||(t=new cl(ic),this.it=this.it.insert(e,t)),t}lt(e){const t=null!==this.wt(e);return t||Fa("WatchChangeAggregator","Detected inactive target",e),t}wt(e){const t=this.nt.get(e);return t&&t.K?null:this.et.Et(e)}ft(e){this.nt.set(e,new _l),this.et.getRemoteKeysForTarget(e).forEach((t=>{this.ct(e,t,null)}))}yt(e,t){return this.et.getRemoteKeysForTarget(e).has(t)}}function kl(){return new sl(kc.comparator)}function Al(){return new sl(kc.comparator)}const Cl={asc:"ASCENDING",desc:"DESCENDING"},Nl={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class Rl{constructor(e,t){this.databaseId=e,this.C=t}}function Dl(e,t){return e.C?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Ll(e,t){return e.C?t.toBase64():t.toUint8Array()}function Ol(e,t){return Dl(e,t.toTimestamp())}function Pl(e){return $a(!!e),ac.fromTimestamp(function(e){const t=vc(e);return new oc(t.seconds,t.nanos)}(e))}function Ml(e,t){return function(e){return new dc(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function xl(e){const t=dc.fromString(e);return $a(nh(t)),t}function Ul(e,t){return Ml(e.databaseId,t.path)}function Fl(e,t){const n=xl(t);if(n.get(1)!==e.databaseId.projectId)throw new za(Ka.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new za(Ka.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new kc(ql(n))}function Vl(e,t){return Ml(e.databaseId,t)}function jl(e){return new dc(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function ql(e){return $a(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function Bl(e,t,n){return{name:Ul(e,t),fields:n.value.mapValue.fields}}function $l(e,t){return{documents:[Vl(e,t.path)]}}function Hl(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=Vl(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=Vl(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const i=function(e){if(0===e.length)return;const t=e.map((e=>function(e){if("=="===e.op){if(Uc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NAN"}};if(xc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Uc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NOT_NAN"}};if(xc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Ql(e.field),op:Xl(e.op),value:e.value}}}(e)));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}(t.filters);i&&(n.structuredQuery.where=i);const s=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:Ql(e.field),direction:Jl(e.dir)}}(e)))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);const o=function(e,t){return e.C||_c(t)?t:{value:t}}(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt=Gl(t.startAt)),t.endAt&&(n.structuredQuery.endAt=Gl(t.endAt)),n}function Kl(e){let t=function(e){const t=xl(e);return 4===t.length?dc.emptyPath():ql(t)}(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){$a(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=zl(n.where));let o=[];n.orderBy&&(o=n.orderBy.map((e=>function(e){return new su(Yl(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e))));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,_c(t)?null:t}(n.limit));let c=null;n.startAt&&(c=Wl(n.startAt));let u=null;return n.endAt&&(u=Wl(n.endAt)),function(e,t,n,r,i,s,o,a){return new uu(e,t,n,r,i,s,o,a)}(t,i,o,s,a,"F",c,u)}function zl(e){return e?void 0!==e.unaryFilter?[eh(e)]:void 0!==e.fieldFilter?[Zl(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map((e=>zl(e))).reduce(((e,t)=>e.concat(t))):Ba():[]}function Gl(e){return{before:e.before,values:e.position}}function Wl(e){const t=!!e.before,n=e.values||[];return new ru(n,t)}function Jl(e){return Cl[e]}function Xl(e){return Nl[e]}function Ql(e){return{fieldPath:e.canonicalString()}}function Yl(e){return pc.fromServerFormat(e.fieldPath)}function Zl(e){return Wc.create(Yl(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return Ba()}}(e.fieldFilter.op),e.fieldFilter.value)}function eh(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Yl(e.unaryFilter.field);return Wc.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Yl(e.unaryFilter.field);return Wc.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Yl(e.unaryFilter.field);return Wc.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=Yl(e.unaryFilter.field);return Wc.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Ba()}}function th(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function nh(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function rh(e){let t="";for(let n=0;n0&&(t=sh(t)),t=ih(e.get(n),t);return sh(t)}function ih(e,t){let n=t;const r=e.length;for(let t=0;t{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&Ba(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new wh(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof wh?t:wh.resolve(t)}catch(e){return wh.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):wh.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):wh.reject(t)}static resolve(e){return new wh(((t,n)=>{t(e)}))}static reject(e){return new wh(((t,n)=>{n(e)}))}static waitFor(e){return new wh(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=wh.resolve(!1);for(const n of e)t=t.next((e=>e?wh.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}}function Ih(e){return"IndexedDbTransactionError"===e.name}class Th{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let t=0;t{const n=e.get(t.key),r=n;this.applyToLocalView(r),n.isValidDocument()||r.convertToNoDocument(ac.min())}))}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),gl())}isEqual(e){return this.batchId===e.batchId&&sc(this.mutations,e.mutations,((e,t)=>zu(e,t)))&&sc(this.baseMutations,e.baseMutations,((e,t)=>zu(e,t)))}}class Eh{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){$a(e.mutations.length===n.length);let r=pl;const i=e.mutations;for(let e=0;e{for(const[t,r]of n)e(t,r)}))}isEmpty(){return lc(this.inner)}}class Lh{constructor(e,t,n){this.Je=e,this.An=t,this.Jt=n}Rn(e,t){return this.An.getAllMutationBatchesAffectingDocumentKey(e,t).next((n=>this.Pn(e,t,n)))}Pn(e,t,n){return this.Je.getEntry(e,t).next((e=>{for(const t of n)t.applyToLocalView(e);return e}))}bn(e,t){e.forEach(((e,n)=>{for(const e of t)e.applyToLocalView(n)}))}vn(e,t){return this.Je.getEntries(e,t).next((t=>this.Vn(e,t).next((()=>t))))}Vn(e,t){return this.An.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>this.bn(t,e)))}getDocumentsMatchingQuery(e,t,n){return function(e){return kc.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.Sn(e,t.path):function(e){return null!==e.collectionGroup}(t)?this.Dn(e,t,n):this.Cn(e,t,n)}Sn(e,t){return this.Rn(e,new kc(t)).next((e=>{let t=fl();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}Dn(e,t,n){const r=t.collectionGroup;let i=fl();return this.Jt.getCollectionParents(e,r).next((s=>wh.forEach(s,(s=>{const o=function(e,t){return new uu(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,s.child(r));return this.Cn(e,o,n).next((e=>{e.forEach(((e,t)=>{i=i.insert(e,t)}))}))})).next((()=>i))))}Cn(e,t,n){let r,i;return this.Je.getDocumentsMatchingQuery(e,t,n).next((n=>(r=n,this.An.getAllMutationBatchesAffectingQuery(e,t)))).next((t=>(i=t,this.Nn(e,i,r).next((e=>{r=e;for(const e of i)for(const t of e.mutations){const n=t.key;let i=r.get(n);null==i&&(i=Bc.newInvalidDocument(n),r=r.insert(n,i)),Hu(t,i,e.localWriteTime),i.isFoundDocument()||(r=r.remove(n))}}))))).next((()=>(r.forEach(((e,n)=>{Tu(t,n)||(r=r.remove(e))})),r)))}Nn(e,t,n){let r=gl();for(const e of t)for(const t of e.mutations)t instanceof Ju&&null===n.get(t.key)&&(r=r.add(t.key));let i=n;return this.Je.getEntries(e,r).next((e=>(e.forEach(((e,t)=>{t.isFoundDocument()&&(i=i.insert(e,t))})),i)))}}class Oh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.kn=n,this.xn=r}static $n(e,t){let n=gl(),r=gl();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new Oh(e,t.fromCache,n,r)}}class Ph{Fn(e){this.On=e}getDocumentsMatchingQuery(e,t,n,r){return function(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}(t)||n.isEqual(ac.min())?this.Mn(e,t):this.On.vn(e,r).next((i=>{const s=this.Ln(t,i);return(hu(t)||du(t))&&this.Bn(t.limitType,s,r,n)?this.Mn(e,t):(Ua()<=S.DEBUG&&Fa("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),Iu(t)),this.On.getDocumentsMatchingQuery(e,t,n).next((e=>(s.forEach((t=>{e=e.insert(t.key,t)})),e))))}))}Ln(e,t){let n=new cl(Eu(e));return t.forEach(((t,r)=>{Tu(e,r)&&(n=n.add(r))})),n}Bn(e,t,n,r){if(n.size!==t.size)return!0;const i="F"===e?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}Mn(e,t){return Ua()<=S.DEBUG&&Fa("QueryEngine","Using full collection scan to execute query:",Iu(t)),this.On.getDocumentsMatchingQuery(e,t,ac.min())}}class Mh{constructor(e,t,n,r){this.persistence=e,this.Un=t,this.k=r,this.qn=new sl(ic),this.Kn=new Dh((e=>Kc(e)),zc),this.jn=ac.min(),this.An=e.getMutationQueue(n),this.Qn=e.getRemoteDocumentCache(),this.He=e.getTargetCache(),this.Wn=new Lh(this.Qn,this.An,this.persistence.getIndexManager()),this.Ye=e.getBundleCache(),this.Un.Fn(this.Wn)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.qn)))}}async function xh(e,t){const n=Ha(e);let r=n.An,i=n.Wn;const s=await n.persistence.runTransaction("Handle user change","readonly",(e=>{let s;return n.An.getAllMutationBatches(e).next((o=>(s=o,r=n.persistence.getMutationQueue(t),i=new Lh(n.Qn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(e)))).next((t=>{const n=[],r=[];let o=gl();for(const e of s){n.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){r.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return i.vn(e,o).next((e=>({Gn:e,removedBatchIds:n,addedBatchIds:r})))}))}));return n.An=r,n.Wn=i,n.Un.Fn(n.Wn),s}function Uh(e){const t=Ha(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.He.getLastRemoteSnapshotVersion(e)))}function Fh(e,t){const n=Ha(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.An.getNextMutationBatchAfterBatchId(e,t))))}async function Vh(e,t,n){const r=Ha(e),i=r.qn.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!Ih(e))throw e;Fa("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qn=r.qn.remove(t),r.Kn.delete(i.target)}function jh(e,t,n){const r=Ha(e);let i=ac.min(),s=gl();return r.persistence.runTransaction("Execute query","readonly",(e=>function(e,t,n){const r=Ha(e),i=r.Kn.get(n);return void 0!==i?wh.resolve(r.qn.get(i)):r.He.getTargetData(t,n)}(r,e,gu(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.He.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r.Un.getDocumentsMatchingQuery(e,t,n?i:ac.min(),n?s:gl()))).next((e=>({documents:e,zn:s})))))}class qh{constructor(e){this.k=e,this.Xn=new Map,this.Zn=new Map}getBundleMetadata(e,t){return wh.resolve(this.Xn.get(t))}saveBundleMetadata(e,t){var n;return this.Xn.set(t.id,{id:(n=t).id,version:n.version,createTime:Pl(n.createTime)}),wh.resolve()}getNamedQuery(e,t){return wh.resolve(this.Zn.get(t))}saveNamedQuery(e,t){return this.Zn.set(t.name,function(e){return{name:e.name,query:Sh(e.bundledQuery),readTime:Pl(e.readTime)}}(t)),wh.resolve()}}class Bh{constructor(){this.ts=new cl($h.es),this.ns=new cl($h.ss)}isEmpty(){return this.ts.isEmpty()}addReference(e,t){const n=new $h(e,t);this.ts=this.ts.add(n),this.ns=this.ns.add(n)}rs(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.os(new $h(e,t))}cs(e,t){e.forEach((e=>this.removeReference(e,t)))}us(e){const t=new kc(new dc([])),n=new $h(t,e),r=new $h(t,e+1),i=[];return this.ns.forEachInRange([n,r],(e=>{this.os(e),i.push(e.key)})),i}hs(){this.ts.forEach((e=>this.os(e)))}os(e){this.ts=this.ts.delete(e),this.ns=this.ns.delete(e)}ls(e){const t=new kc(new dc([])),n=new $h(t,e),r=new $h(t,e+1);let i=gl();return this.ns.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new $h(e,0),n=this.ts.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class $h{constructor(e,t){this.key=e,this.fs=t}static es(e,t){return kc.comparator(e.key,t.key)||ic(e.fs,t.fs)}static ss(e,t){return ic(e.fs,t.fs)||kc.comparator(e.key,t.key)}}class Hh{constructor(e,t){this.Jt=e,this.referenceDelegate=t,this.An=[],this.ds=1,this.ws=new cl($h.es)}checkEmpty(e){return wh.resolve(0===this.An.length)}addMutationBatch(e,t,n,r){const i=this.ds;this.ds++,this.An.length>0&&this.An[this.An.length-1];const s=new Th(i,t,n,r);this.An.push(s);for(const t of r)this.ws=this.ws.add(new $h(t.key,i)),this.Jt.addToCollectionParentIndex(e,t.key.path.popLast());return wh.resolve(s)}lookupMutationBatch(e,t){return wh.resolve(this._s(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.gs(n),i=r<0?0:r;return wh.resolve(this.An.length>i?this.An[i]:null)}getHighestUnacknowledgedBatchId(){return wh.resolve(0===this.An.length?-1:this.ds-1)}getAllMutationBatches(e){return wh.resolve(this.An.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new $h(t,0),r=new $h(t,Number.POSITIVE_INFINITY),i=[];return this.ws.forEachInRange([n,r],(e=>{const t=this._s(e.fs);i.push(t)})),wh.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new cl(ic);return t.forEach((e=>{const t=new $h(e,0),r=new $h(e,Number.POSITIVE_INFINITY);this.ws.forEachInRange([t,r],(e=>{n=n.add(e.fs)}))})),wh.resolve(this.ys(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;kc.isDocumentKey(i)||(i=i.child(""));const s=new $h(new kc(i),0);let o=new cl(ic);return this.ws.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.fs)),!0)}),s),wh.resolve(this.ys(o))}ys(e){const t=[];return e.forEach((e=>{const n=this._s(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){$a(0===this.ps(t.batchId,"removed")),this.An.shift();let n=this.ws;return wh.forEach(t.mutations,(r=>{const i=new $h(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.ws=n}))}ee(e){}containsKey(e,t){const n=new $h(t,0),r=this.ws.firstAfterOrEqual(n);return wh.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.An.length,wh.resolve()}ps(e,t){return this.gs(e)}gs(e){return 0===this.An.length?0:e-this.An[0].batchId}_s(e){const t=this.gs(e);return t<0||t>=this.An.length?null:this.An[t]}}class Kh{constructor(e,t){this.Jt=e,this.Ts=t,this.docs=new sl(kc.comparator),this.size=0}addEntry(e,t,n){const r=t.key,i=this.docs.get(r),s=i?i.size:0,o=this.Ts(t);return this.docs=this.docs.insert(r,{document:t.clone(),size:o,readTime:n}),this.size+=o-s,this.Jt.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return wh.resolve(n?n.document.clone():Bc.newInvalidDocument(t))}getEntries(e,t){let n=hl();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.clone():Bc.newInvalidDocument(e))})),wh.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=hl();const i=new kc(t.path.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i,readTime:o}}=s.getNext();if(!t.path.isPrefixOf(e.path))break;o.compareTo(n)<=0||Tu(t,i)&&(r=r.insert(i.key,i.clone()))}return wh.resolve(r)}Es(e,t){return wh.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new zh(this)}getSize(e){return wh.resolve(this.size)}}class zh extends class{constructor(){this.changes=new Dh((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}getReadTime(e){const t=this.changes.get(e);return t?t.readTime:ac.min()}addEntry(e,t){this.assertNotApplied(),this.changes.set(e.key,{document:e,readTime:t})}removeEntry(e,t=null){this.assertNotApplied(),this.changes.set(e,{document:Bc.newInvalidDocument(e),readTime:t})}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?wh.resolve(n.document):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}{constructor(e){super(),this.De=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.document.isValidDocument()?t.push(this.De.addEntry(e,r.document,this.getReadTime(n))):this.De.removeEntry(n)})),wh.waitFor(t)}getFromCache(e,t){return this.De.getEntry(e,t)}getAllFromCache(e,t){return this.De.getEntries(e,t)}}class Gh{constructor(e){this.persistence=e,this.Is=new Dh((e=>Kc(e)),zc),this.lastRemoteSnapshotVersion=ac.min(),this.highestTargetId=0,this.As=0,this.Rs=new Bh,this.targetCount=0,this.Ps=Nh.ie()}forEachTarget(e,t){return this.Is.forEach(((e,n)=>t(n))),wh.resolve()}getLastRemoteSnapshotVersion(e){return wh.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return wh.resolve(this.As)}allocateTargetId(e){return this.highestTargetId=this.Ps.next(),wh.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.As&&(this.As=t),wh.resolve()}ce(e){this.Is.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Ps=new Nh(t),this.highestTargetId=t),e.sequenceNumber>this.As&&(this.As=e.sequenceNumber)}addTargetData(e,t){return this.ce(t),this.targetCount+=1,wh.resolve()}updateTargetData(e,t){return this.ce(t),wh.resolve()}removeTargetData(e,t){return this.Is.delete(t.target),this.Rs.us(t.targetId),this.targetCount-=1,wh.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.Is.forEach(((s,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Is.delete(s),i.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),wh.waitFor(i).next((()=>r))}getTargetCount(e){return wh.resolve(this.targetCount)}getTargetData(e,t){const n=this.Is.get(t)||null;return wh.resolve(n)}addMatchingKeys(e,t,n){return this.Rs.rs(t,n),wh.resolve()}removeMatchingKeys(e,t,n){this.Rs.cs(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),wh.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Rs.us(t),wh.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Rs.ls(t);return wh.resolve(n)}containsKey(e,t){return wh.resolve(this.Rs.containsKey(t))}}class Wh{constructor(e,t){this.bs={},this.Be=new tc(0),this.Ue=!1,this.Ue=!0,this.referenceDelegate=e(this),this.He=new Gh(this),this.Jt=new kh,this.Je=function(e,t){return new Kh(e,t)}(this.Jt,(e=>this.referenceDelegate.vs(e))),this.k=new _h(t),this.Ye=new qh(this.k)}start(){return Promise.resolve()}shutdown(){return this.Ue=!1,Promise.resolve()}get started(){return this.Ue}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Jt}getMutationQueue(e){let t=this.bs[e.toKey()];return t||(t=new Hh(this.Jt,this.referenceDelegate),this.bs[e.toKey()]=t),t}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getBundleCache(){return this.Ye}runTransaction(e,t,n){Fa("MemoryPersistence","Starting transaction:",e);const r=new Jh(this.Be.next());return this.referenceDelegate.Vs(),n(r).next((e=>this.referenceDelegate.Ss(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Ds(e,t){return wh.or(Object.values(this.bs).map((n=>()=>n.containsKey(e,t))))}}class Jh extends class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}{constructor(e){super(),this.currentSequenceNumber=e}}class Xh{constructor(e){this.persistence=e,this.Cs=new Bh,this.Ns=null}static ks(e){return new Xh(e)}get xs(){if(this.Ns)return this.Ns;throw Ba()}addReference(e,t,n){return this.Cs.addReference(n,t),this.xs.delete(n.toString()),wh.resolve()}removeReference(e,t,n){return this.Cs.removeReference(n,t),this.xs.add(n.toString()),wh.resolve()}markPotentiallyOrphaned(e,t){return this.xs.add(t.toString()),wh.resolve()}removeTarget(e,t){this.Cs.us(t.targetId).forEach((e=>this.xs.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.xs.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}Vs(){this.Ns=new Set}Ss(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return wh.forEach(this.xs,(n=>{const r=kc.fromPath(n);return this.$s(e,r).next((e=>{e||t.removeEntry(r)}))})).next((()=>(this.Ns=null,t.apply(e))))}updateLimboDocument(e,t){return this.$s(e,t).next((e=>{e?this.xs.delete(t.toString()):this.xs.add(t.toString())}))}vs(e){return 0}$s(e,t){return wh.or([()=>wh.resolve(this.Cs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ds(e,t)])}}class Qh{constructor(){this.activeTargetIds=vl()}Ms(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ls(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Os(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Yh{constructor(){this.pi=new Qh,this.Ti={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.pi.Ms(e),this.Ti[e]||"not-current"}updateQueryState(e,t,n){this.Ti[e]=t}removeLocalQueryTarget(e){this.pi.Ls(e)}isLocalQueryTarget(e){return this.pi.activeTargetIds.has(e)}clearQueryState(e){delete this.Ti[e]}getAllActiveQueryTargets(){return this.pi.activeTargetIds}isActiveQueryTarget(e){return this.pi.activeTargetIds.has(e)}start(){return this.pi=new Qh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class Zh{Ei(e){}shutdown(){}}class ed{constructor(){this.Ii=()=>this.Ai(),this.Ri=()=>this.Pi(),this.bi=[],this.vi()}Ei(e){this.bi.push(e)}shutdown(){window.removeEventListener("online",this.Ii),window.removeEventListener("offline",this.Ri)}vi(){window.addEventListener("online",this.Ii),window.addEventListener("offline",this.Ri)}Ai(){Fa("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.bi)e(0)}Pi(){Fa("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.bi)e(1)}static bt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const td={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class nd{constructor(e){this.Vi=e.Vi,this.Si=e.Si}Di(e){this.Ci=e}Ni(e){this.ki=e}onMessage(e){this.xi=e}close(){this.Si()}send(e){this.Vi(e)}$i(){this.Ci()}Fi(e){this.ki(e)}Oi(e){this.xi(e)}}class rd extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http";this.Mi=t+"://"+e.host,this.Li="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Bi(e,t,n,r,i){const s=this.Ui(e,t);Fa("RestConnection","Sending: ",s,n);const o={};return this.qi(o,r,i),this.Ki(e,s,o,n).then((e=>(Fa("RestConnection","Received: ",e),e)),(t=>{throw ja("RestConnection",`${e} failed with error: `,t,"url: ",s,"request:",n),t}))}ji(e,t,n,r,i){return this.Bi(e,t,n,r,i)}qi(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+Ma,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}Ui(e,t){const n=td[e];return`${this.Mi}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}Ki(e,t,n,r){return new Promise(((i,s)=>{const o=new La;o.listenOnce(Aa.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case ka.NO_ERROR:const t=o.getResponseJson();Fa("Connection","XHR received:",JSON.stringify(t)),i(t);break;case ka.TIMEOUT:Fa("Connection",'RPC "'+e+'" timed out'),s(new za(Ka.DEADLINE_EXCEEDED,"Request time out"));break;case ka.HTTP_ERROR:const n=o.getStatus();if(Fa("Connection",'RPC "'+e+'" failed with status:',n,"response text:",o.getResponseText()),n>0){const e=o.getResponseJson().error;if(e&&e.status&&e.message){const t=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(Ka).indexOf(t)>=0?t:Ka.UNKNOWN}(e.status);s(new za(t,e.message))}else s(new za(Ka.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new za(Ka.UNAVAILABLE,"Connection failed."));break;default:Ba()}}finally{Fa("Connection",'RPC "'+e+'" completed.')}}));const a=JSON.stringify(r);o.send(t,"POST",a,n,15)}))}Qi(e,t,n){const c=[this.Mi,"/","google.firestore.v1.Firestore","/",e,"/channel"],u=_a(),l=Sa(),h={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(h.xmlHttpFactory=new Ra({})),this.qi(h.initMessageHeaders,t,n),i()||o()||r().indexOf("Electron/")>=0||a()||r().indexOf("MSAppHost/")>=0||s()||(h.httpHeadersOverwriteParam="$httpHeaders");const d=c.join("");Fa("Connection","Creating WebChannel: "+d,h);const f=u.createWebChannel(d,h);let p=!1,m=!1;const g=new nd({Vi:e=>{m?Fa("Connection","Not sending because WebChannel is closed:",e):(p||(Fa("Connection","Opening WebChannel transport."),f.open(),p=!0),Fa("Connection","WebChannel sending:",e),f.send(e))},Si:()=>f.close()}),y=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return y(f,Da.EventType.OPEN,(()=>{m||Fa("Connection","WebChannel transport opened.")})),y(f,Da.EventType.CLOSE,(()=>{m||(m=!0,Fa("Connection","WebChannel transport closed"),g.Fi())})),y(f,Da.EventType.ERROR,(e=>{m||(m=!0,ja("Connection","WebChannel transport errored:",e),g.Fi(new za(Ka.UNAVAILABLE,"The operation could not be completed")))})),y(f,Da.EventType.MESSAGE,(e=>{var t;if(!m){const n=e.data[0];$a(!!n);const r=n,i=r.error||(null===(t=r[0])||void 0===t?void 0:t.error);if(i){Fa("Connection","WebChannel received error:",i);const e=i.status;let t=function(e){const t=nl[e];if(void 0!==t)return il(t)}(e),n=i.message;void 0===t&&(t=Ka.INTERNAL,n="Unknown error status: "+e+" with message "+i.message),m=!0,g.Fi(new za(t,n)),f.close()}else Fa("Connection","WebChannel received:",n),g.Oi(n)}})),y(l,Ca.STAT_EVENT,(e=>{e.stat===Na.PROXY?Fa("Connection","Detected buffering proxy"):e.stat===Na.NOPROXY&&Fa("Connection","Detected no buffering proxy")})),setTimeout((()=>{g.$i()}),0),g}}function id(){return"undefined"!=typeof document?document:null}function sd(e){return new Rl(e,!0)}class od{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Oe=e,this.timerId=t,this.Wi=n,this.Gi=r,this.zi=i,this.Hi=0,this.Ji=null,this.Yi=Date.now(),this.reset()}reset(){this.Hi=0}Xi(){this.Hi=this.zi}Zi(e){this.cancel();const t=Math.floor(this.Hi+this.tr()),n=Math.max(0,Date.now()-this.Yi),r=Math.max(0,t-n);r>0&&Fa("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Hi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Ji=this.Oe.enqueueAfterDelay(this.timerId,r,(()=>(this.Yi=Date.now(),e()))),this.Hi*=this.Gi,this.Hithis.zi&&(this.Hi=this.zi)}er(){null!==this.Ji&&(this.Ji.skipDelay(),this.Ji=null)}cancel(){null!==this.Ji&&(this.Ji.cancel(),this.Ji=null)}tr(){return(Math.random()-.5)*this.Hi}}class ad{constructor(e,t,n,r,i,s,o,a){this.Oe=e,this.nr=n,this.sr=r,this.ir=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.rr=0,this.ar=null,this.cr=null,this.stream=null,this.ur=new od(e,t)}hr(){return 1===this.state||5===this.state||this.lr()}lr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.dr()}async stop(){this.hr()&&await this.close(0)}wr(){this.state=0,this.ur.reset()}_r(){this.lr()&&null===this.ar&&(this.ar=this.Oe.enqueueAfterDelay(this.nr,6e4,(()=>this.mr())))}gr(e){this.yr(),this.stream.send(e)}async mr(){if(this.lr())return this.close(0)}yr(){this.ar&&(this.ar.cancel(),this.ar=null)}pr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(e,t){this.yr(),this.pr(),this.ur.cancel(),this.rr++,4!==e?this.ur.reset():t&&t.code===Ka.RESOURCE_EXHAUSTED?(Va(t.toString()),Va("Using maximum backoff delay to prevent overloading the backend."),this.ur.Xi()):t&&t.code===Ka.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Tr(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ni(t)}Tr(){}auth(){this.state=1;const e=this.Er(this.rr),t=this.rr;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.rr===t&&this.Ir(e,n)}),(t=>{e((()=>{const e=new za(Ka.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ar(e)}))}))}Ir(e,t){const n=this.Er(this.rr);this.stream=this.Rr(e,t),this.stream.Di((()=>{n((()=>(this.state=2,this.cr=this.Oe.enqueueAfterDelay(this.sr,1e4,(()=>(this.lr()&&(this.state=3),Promise.resolve()))),this.listener.Di())))})),this.stream.Ni((e=>{n((()=>this.Ar(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}dr(){this.state=5,this.ur.Zi((async()=>{this.state=0,this.start()}))}Ar(e){return Fa("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Er(e){return t=>{this.Oe.enqueueAndForget((()=>this.rr===e?t():(Fa("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class cd extends ad{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.k=i}Rr(e,t){return this.ir.Qi("Listen",e,t)}onMessage(e){this.ur.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:Ba()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.C?($a(void 0===t||"string"==typeof t),gc.fromBase64String(t||"")):($a(void 0===t||t instanceof Uint8Array),gc.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?Ka.UNKNOWN:il(e.code);return new za(t,e.message||"")}(o);n=new bl(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=Fl(e,r.document.name),s=Pl(r.document.updateTime),o=new jc({mapValue:{fields:r.document.fields}}),a=Bc.newFoundDocument(i,s,o),c=r.targetIds||[],u=r.removedTargetIds||[];n=new Tl(c,u,a.key,a)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=Fl(e,r.document),s=r.readTime?Pl(r.readTime):ac.min(),o=Bc.newNoDocument(i,s),a=r.removedTargetIds||[];n=new Tl([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=Fl(e,r.document),s=r.removedTargetIds||[];n=new Tl([],s,i,null)}else{if(!("filter"in t))return Ba();{t.filter;const e=t.filter;e.targetId;const r=e.count||0,i=new tl(r),s=e.targetId;n=new El(s,i)}}return n}(this.k,e),n=function(e){if(!("targetChange"in e))return ac.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?ac.min():t.readTime?Pl(t.readTime):ac.min()}(e);return this.listener.Pr(t,n)}br(e){const t={};t.database=jl(this.k),t.addTarget=function(e,t){let n;const r=t.target;return n=Gc(r)?{documents:$l(e,r)}:{query:Hl(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0?n.resumeToken=Ll(e,t.resumeToken):t.snapshotVersion.compareTo(ac.min())>0&&(n.readTime=Dl(e,t.snapshotVersion.toTimestamp())),n}(this.k,e);const n=function(e,t){const n=function(e,t){switch(t){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return Ba()}}(0,t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.k,e);n&&(t.labels=n),this.gr(t)}vr(e){const t={};t.database=jl(this.k),t.removeTarget=e,this.gr(t)}}class ud extends ad{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.k=i,this.Vr=!1}get Sr(){return this.Vr}start(){this.Vr=!1,this.lastStreamToken=void 0,super.start()}Tr(){this.Vr&&this.Dr([])}Rr(e,t){return this.ir.Qi("Write",e,t)}onMessage(e){if($a(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Vr){this.ur.reset();const t=function(e,t){return e&&e.length>0?($a(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?Pl(e.updateTime):Pl(t);return n.isEqual(ac.min())&&(n=Pl(t)),new Vu(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=Pl(e.commitTime);return this.listener.Cr(n,t)}return $a(!e.writeResults||0===e.writeResults.length),this.Vr=!0,this.listener.Nr()}kr(){const e={};e.database=jl(this.k),this.gr(e)}Dr(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>function(e,t){let n;if(t instanceof Wu)n={update:Bl(e,t.key,t.value)};else if(t instanceof Zu)n={delete:Ul(e,t.key)};else if(t instanceof Ju)n={update:Bl(e,t.key,t.data),updateMask:th(t.fieldMask)};else{if(!(t instanceof el))return Ba();n={verify:Ul(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof Du)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Lu)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof Pu)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof xu)return{fieldPath:t.field.canonicalString(),increment:n.N};throw Ba()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:Ol(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Ba()}(e,t.precondition)),n}(this.k,e)))};this.gr(t)}}class ld extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.ir=n,this.k=r,this.$r=!1}Fr(){if(this.$r)throw new za(Ka.FAILED_PRECONDITION,"The client has already been terminated.")}Bi(e,t,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,i])=>this.ir.Bi(e,t,n,r,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===Ka.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new za(Ka.UNKNOWN,e.toString())}))}ji(e,t,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,i])=>this.ir.ji(e,t,n,r,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===Ka.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new za(Ka.UNKNOWN,e.toString())}))}terminate(){this.$r=!0}}class hd{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Or=0,this.Mr=null,this.Lr=!0}Br(){0===this.Or&&(this.Ur("Unknown"),this.Mr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.Mr=null,this.qr("Backend didn't respond within 10 seconds."),this.Ur("Offline"),Promise.resolve()))))}Kr(e){"Online"===this.state?this.Ur("Unknown"):(this.Or++,this.Or>=1&&(this.jr(),this.qr(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Ur("Offline")))}set(e){this.jr(),this.Or=0,"Online"===e&&(this.Lr=!1),this.Ur(e)}Ur(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}qr(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.Lr?(Va(t),this.Lr=!1):Fa("OnlineStateTracker",t)}jr(){null!==this.Mr&&(this.Mr.cancel(),this.Mr=null)}}class dd{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Qr=[],this.Wr=new Map,this.Gr=new Set,this.zr=[],this.Hr=i,this.Hr.Ei((e=>{n.enqueueAndForget((async()=>{Td(this)&&(Fa("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=Ha(e);t.Gr.add(4),await pd(t),t.Jr.set("Unknown"),t.Gr.delete(4),await fd(t)}(this))}))})),this.Jr=new hd(n,r)}}async function fd(e){if(Td(e))for(const t of e.zr)await t(!0)}async function pd(e){for(const t of e.zr)await t(!1)}function md(e,t){const n=Ha(e);n.Wr.has(t.targetId)||(n.Wr.set(t.targetId,t),Id(n)?wd(n):Ud(n).lr()&&yd(n,t))}function gd(e,t){const n=Ha(e),r=Ud(n);n.Wr.delete(t),r.lr()&&vd(n,t),0===n.Wr.size&&(r.lr()?r._r():Td(n)&&n.Jr.set("Unknown"))}function yd(e,t){e.Yr.X(t.targetId),Ud(e).br(t)}function vd(e,t){e.Yr.X(t),Ud(e).vr(t)}function wd(e){e.Yr=new Sl({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Et:t=>e.Wr.get(t)||null}),Ud(e).start(),e.Jr.Br()}function Id(e){return Td(e)&&!Ud(e).hr()&&e.Wr.size>0}function Td(e){return 0===Ha(e).Gr.size}function Ed(e){e.Yr=void 0}async function bd(e){e.Wr.forEach(((t,n)=>{yd(e,t)}))}async function _d(e,t){Ed(e),Id(e)?(e.Jr.Kr(t),wd(e)):e.Jr.set("Unknown")}async function Sd(e,t,n){if(e.Jr.set("Online"),t instanceof bl&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.Wr.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Wr.delete(r),e.Yr.removeTarget(r))}(e,t)}catch(n){Fa("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await kd(e,n)}else if(t instanceof Tl?e.Yr.ot(t):t instanceof El?e.Yr.dt(t):e.Yr.ut(t),!n.isEqual(ac.min()))try{const t=await Uh(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.Yr.gt(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.Wr.get(r);i&&e.Wr.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach((t=>{const n=e.Wr.get(t);if(!n)return;e.Wr.set(t,n.withResumeToken(gc.EMPTY_BYTE_STRING,n.snapshotVersion)),vd(e,t);const r=new bh(n.target,t,1,n.sequenceNumber);yd(e,r)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){Fa("RemoteStore","Failed to raise snapshot:",t),await kd(e,t)}}async function kd(e,t,n){if(!Ih(t))throw t;e.Gr.add(1),await pd(e),e.Jr.set("Offline"),n||(n=()=>Uh(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{Fa("RemoteStore","Retrying IndexedDB access"),await n(),e.Gr.delete(1),await fd(e)}))}function Ad(e,t){return t().catch((n=>kd(e,n,t)))}async function Cd(e){const t=Ha(e),n=Fd(t);let r=t.Qr.length>0?t.Qr[t.Qr.length-1].batchId:-1;for(;Nd(t);)try{const e=await Fh(t.localStore,r);if(null===e){0===t.Qr.length&&n._r();break}r=e.batchId,Rd(t,e)}catch(e){await kd(t,e)}Dd(t)&&Ld(t)}function Nd(e){return Td(e)&&e.Qr.length<10}function Rd(e,t){e.Qr.push(t);const n=Fd(e);n.lr()&&n.Sr&&n.Dr(t.mutations)}function Dd(e){return Td(e)&&!Fd(e).hr()&&e.Qr.length>0}function Ld(e){Fd(e).start()}async function Od(e){Fd(e).kr()}async function Pd(e){const t=Fd(e);for(const n of e.Qr)t.Dr(n.mutations)}async function Md(e,t,n){const r=e.Qr.shift(),i=Eh.from(r,t,n);await Ad(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await Cd(e)}async function xd(e,t){t&&Fd(e).Sr&&await async function(e,t){if(function(e){switch(e){default:return Ba();case Ka.CANCELLED:case Ka.UNKNOWN:case Ka.DEADLINE_EXCEEDED:case Ka.RESOURCE_EXHAUSTED:case Ka.INTERNAL:case Ka.UNAVAILABLE:case Ka.UNAUTHENTICATED:return!1;case Ka.INVALID_ARGUMENT:case Ka.NOT_FOUND:case Ka.ALREADY_EXISTS:case Ka.PERMISSION_DENIED:case Ka.FAILED_PRECONDITION:case Ka.ABORTED:case Ka.OUT_OF_RANGE:case Ka.UNIMPLEMENTED:case Ka.DATA_LOSS:return!0}}(n=t.code)&&n!==Ka.ABORTED){const n=e.Qr.shift();Fd(e).wr(),await Ad(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Cd(e)}var n}(e,t),Dd(e)&&Ld(e)}function Ud(e){return e.Xr||(e.Xr=function(e,t,n){const r=Ha(e);return r.Fr(),new cd(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(e.datastore,e.asyncQueue,{Di:bd.bind(null,e),Ni:_d.bind(null,e),Pr:Sd.bind(null,e)}),e.zr.push((async t=>{t?(e.Xr.wr(),Id(e)?wd(e):e.Jr.set("Unknown")):(await e.Xr.stop(),Ed(e))}))),e.Xr}function Fd(e){return e.Zr||(e.Zr=function(e,t,n){const r=Ha(e);return r.Fr(),new ud(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(e.datastore,e.asyncQueue,{Di:Od.bind(null,e),Ni:xd.bind(null,e),Nr:Pd.bind(null,e),Cr:Md.bind(null,e)}),e.zr.push((async t=>{t?(e.Zr.wr(),await Cd(e)):(await e.Zr.stop(),e.Qr.length>0&&(Fa("RemoteStore",`Stopping write stream with ${e.Qr.length} pending writes`),e.Qr=[]))}))),e.Zr}class Vd{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new Ga,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new Vd(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new za(Ka.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function jd(e,t){if(Va("AsyncQueue",`${t}: ${e}`),Ih(e))return new za(Ka.UNAVAILABLE,`${t}: ${e}`);throw e}class qd{constructor(e){this.comparator=e?(t,n)=>e(t,n)||kc.comparator(t.key,n.key):(e,t)=>kc.comparator(e.key,t.key),this.keyedMap=fl(),this.sortedSet=new sl(this.comparator)}static emptySet(e){return new qd(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof qd))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new qd;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Bd{constructor(){this.eo=new sl(kc.comparator)}track(e){const t=e.doc.key,n=this.eo.get(t);n?0!==e.type&&3===n.type?this.eo=this.eo.insert(t,e):3===e.type&&1!==n.type?this.eo=this.eo.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.eo=this.eo.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.eo=this.eo.remove(t):1===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):Ba():this.eo=this.eo.insert(t,e)}no(){const e=[];return this.eo.inorderTraversal(((t,n)=>{e.push(n)})),e}}class $d{constructor(e,t,n,r,i,s,o,a){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(e,t,n,r){const i=[];return t.forEach((e=>{i.push({type:0,doc:e})})),new $d(e,t,qd.emptySet(t),i,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&vu(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;ewu(e)),vu),this.onlineState="Unknown",this.io=new Set}}async function zd(e,t){const n=Ha(e),r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new Hd),i)try{s.so=await n.onListen(r)}catch(e){const n=jd(e,`Initialization of query '${Iu(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.ro(n.onlineState),s.so&&t.oo(s.so)&&Xd(n)}async function Gd(e,t){const n=Ha(e),r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);e>=0&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Wd(e,t){const n=Ha(e);let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.oo(e)&&(r=!0);i.so=e}}r&&Xd(n)}function Jd(e,t,n){const r=Ha(e),i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}function Xd(e){e.io.forEach((e=>{e.next()}))}class Qd{constructor(e,t,n){this.query=e,this.ao=t,this.co=!1,this.uo=null,this.onlineState="Unknown",this.options=n||{}}oo(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new $d(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.co?this.ho(e)&&(this.ao.next(e),t=!0):this.lo(e,this.onlineState)&&(this.fo(e),t=!0),this.uo=e,t}onError(e){this.ao.error(e)}ro(e){this.onlineState=e;let t=!1;return this.uo&&!this.co&&this.lo(this.uo,e)&&(this.fo(this.uo),t=!0),t}lo(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return!(this.options.wo&&n||e.docs.isEmpty()&&"Offline"!==t)}ho(e){if(e.docChanges.length>0)return!0;const t=this.uo&&this.uo.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}fo(e){e=$d.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.co=!0,this.ao.next(e)}}class Yd{constructor(e){this.key=e}}class Zd{constructor(e){this.key=e}}class ef{constructor(e,t){this.query=e,this.To=t,this.Eo=null,this.current=!1,this.Io=gl(),this.mutatedKeys=gl(),this.Ao=Eu(e),this.Ro=new qd(this.Ao)}get Po(){return this.To}bo(e,t){const n=t?t.vo:new Bd,r=t?t.Ro:this.Ro;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,o=!1;const a=hu(this.query)&&r.size===this.query.limit?r.last():null,c=du(this.query)&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const u=r.get(e),l=Tu(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;u&&l?u.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.Vo(u,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.Ao(l,a)>0||c&&this.Ao(l,c)<0)&&(o=!0)):!u&&l?(n.track({type:0,doc:l}),f=!0):u&&!l&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(l?(s=s.add(l),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),hu(this.query)||du(this.query))for(;s.size>this.query.limit;){const e=hu(this.query)?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{Ro:s,vo:n,Bn:o,mutatedKeys:i}}Vo(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.Ro;this.Ro=e.Ro,this.mutatedKeys=e.mutatedKeys;const i=e.vo.no();i.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Ba()}};return n(e)-n(t)}(e.type,t.type)||this.Ao(e.doc,t.doc))),this.So(n);const s=t?this.Do():[],o=0===this.Io.size&&this.current?1:0,a=o!==this.Eo;return this.Eo=o,0!==i.length||a?{snapshot:new $d(this.query,e.Ro,r,i,e.mutatedKeys,0===o,a,!1),Co:s}:{Co:s}}ro(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ro:this.Ro,vo:new Bd,mutatedKeys:this.mutatedKeys,Bn:!1},!1)):{Co:[]}}No(e){return!this.To.has(e)&&!!this.Ro.has(e)&&!this.Ro.get(e).hasLocalMutations}So(e){e&&(e.addedDocuments.forEach((e=>this.To=this.To.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.To=this.To.delete(e))),this.current=e.current)}Do(){if(!this.current)return[];const e=this.Io;this.Io=gl(),this.Ro.forEach((e=>{this.No(e.key)&&(this.Io=this.Io.add(e.key))}));const t=[];return e.forEach((e=>{this.Io.has(e)||t.push(new Zd(e))})),this.Io.forEach((n=>{e.has(n)||t.push(new Yd(n))})),t}ko(e){this.To=e.zn,this.Io=gl();const t=this.bo(e.documents);return this.applyChanges(t,!0)}xo(){return $d.fromInitialDocuments(this.query,this.Ro,this.mutatedKeys,0===this.Eo)}}class tf{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class nf{constructor(e){this.key=e,this.$o=!1}}class rf{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Fo={},this.Oo=new Dh((e=>wu(e)),vu),this.Mo=new Map,this.Lo=new Set,this.Bo=new sl(kc.comparator),this.Uo=new Map,this.qo=new Bh,this.Ko={},this.jo=new Map,this.Qo=Nh.re(),this.onlineState="Unknown",this.Wo=void 0}get isPrimaryClient(){return!0===this.Wo}}async function sf(e,t){const n=function(e){const t=Ha(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=af.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Tf.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=uf.bind(null,t),t.Fo.Pr=Wd.bind(null,t.eventManager),t.Fo.zo=Jd.bind(null,t.eventManager),t}(e);let r,i;const s=n.Oo.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.xo();else{const e=await function(e,t){const n=Ha(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.He.getTargetData(e,t).next((i=>i?(r=i,wh.resolve(r)):n.He.allocateTargetId(e).next((i=>(r=new bh(t,i,0,e.currentSequenceNumber),n.He.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.qn.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.qn=n.qn.insert(e.targetId,e),n.Kn.set(t,e.targetId)),e}))}(n.localStore,gu(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await async function(e,t,n,r){e.Go=(t,n,r)=>async function(e,t,n,r){let i=t.view.bo(n);i.Bn&&(i=await jh(e.localStore,t.query,!1).then((({documents:e})=>t.view.bo(e,i))));const s=r&&r.targetChanges.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s);return gf(e,t.targetId,o.Co),o.snapshot}(e,t,n,r);const i=await jh(e.localStore,t,!0),s=new ef(t,i.zn),o=s.bo(i.documents),a=Il.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState),c=s.applyChanges(o,e.isPrimaryClient,a);gf(e,n,c.Co);const u=new tf(t,n,s);return e.Oo.set(t,u),e.Mo.has(n)?e.Mo.get(n).push(t):e.Mo.set(n,[t]),c.snapshot}(n,t,r,"current"===s),n.isPrimaryClient&&md(n.remoteStore,e)}return i}async function of(e,t){const n=Ha(e),r=n.Oo.get(t),i=n.Mo.get(r.targetId);if(i.length>1)return n.Mo.set(r.targetId,i.filter((e=>!vu(e,t)))),void n.Oo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Vh(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),gd(n.remoteStore,r.targetId),pf(n,r.targetId)})).catch(Rh)):(pf(n,r.targetId),await Vh(n.localStore,r.targetId,!0))}async function af(e,t){const n=Ha(e);try{const e=await function(e,t){const n=Ha(e),r=t.snapshotVersion;let i=n.qn;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.Qn.newChangeBuffer({trackRemovals:!0});i=n.qn;const o=[];t.targetChanges.forEach(((t,s)=>{const a=i.get(s);if(!a)return;o.push(n.He.removeMatchingKeys(e,t.removedDocuments,s).next((()=>n.He.addMatchingKeys(e,t.addedDocuments,s))));const c=t.resumeToken;if(c.approximateByteSize()>0){const u=a.withResumeToken(c,r).withSequenceNumber(e.currentSequenceNumber);i=i.insert(s,u),function(e,t,n){return $a(t.resumeToken.approximateByteSize()>0),0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(a,u,t)&&o.push(n.He.updateTargetData(e,u))}}));let a=hl();if(t.documentUpdates.forEach(((r,i)=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(function(e,t,n,r,i){let s=gl();return n.forEach((e=>s=s.add(e))),t.getEntries(e,s).next((e=>{let s=hl();return n.forEach(((n,o)=>{const a=e.get(n),c=(null==i?void 0:i.get(n))||r;o.isNoDocument()&&o.version.isEqual(ac.min())?(t.removeEntry(n,c),s=s.insert(n,o)):!a.isValidDocument()||o.version.compareTo(a.version)>0||0===o.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(o,c),s=s.insert(n,o)):Fa("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",o.version)})),s}))}(e,s,t.documentUpdates,r,void 0).next((e=>{a=e}))),!r.isEqual(ac.min())){const t=n.He.getLastRemoteSnapshotVersion(e).next((t=>n.He.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return wh.waitFor(o).next((()=>s.apply(e))).next((()=>n.Wn.Vn(e,a))).next((()=>a))})).then((e=>(n.qn=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.Uo.get(t);r&&($a(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.$o=!0:e.modifiedDocuments.size>0?$a(r.$o):e.removedDocuments.size>0&&($a(r.$o),r.$o=!1))})),await wf(n,e,t)}catch(e){await Rh(e)}}function cf(e,t,n){const r=Ha(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.Oo.forEach(((n,r)=>{const i=r.view.ro(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=Ha(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const e of n.listeners)e.ro(t)&&(r=!0)})),r&&Xd(n)}(r.eventManager,t),e.length&&r.Fo.Pr(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function uf(e,t,n){const r=Ha(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Uo.get(t),s=i&&i.key;if(s){let e=new sl(kc.comparator);e=e.insert(s,Bc.newNoDocument(s,ac.min()));const n=gl().add(s),i=new wl(ac.min(),new Map,new cl(ic),e,n);await af(r,i),r.Bo=r.Bo.remove(s),r.Uo.delete(t),vf(r)}else await Vh(r.localStore,t,!1).then((()=>pf(r,t,n))).catch(Rh)}async function lf(e,t){const n=Ha(e),r=t.batch.batchId;try{const e=await function(e,t){const n=Ha(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.Qn.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let o=wh.resolve();return s.forEach((e=>{o=o.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);$a(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&r.addEntry(t,n.commitVersion))}))})),o.next((()=>e.An.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.An.performConsistencyCheck(e))).next((()=>n.Wn.vn(e,r)))}))}(n.localStore,t);ff(n,r,null),df(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await wf(n,e)}catch(e){await Rh(e)}}async function hf(e,t,n){const r=Ha(e);try{const e=await function(e,t){const n=Ha(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.An.lookupMutationBatch(e,t).next((t=>($a(null!==t),r=t.keys(),n.An.removeMutationBatch(e,t)))).next((()=>n.An.performConsistencyCheck(e))).next((()=>n.Wn.vn(e,r)))}))}(r.localStore,t);ff(r,t,n),df(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await wf(r,e)}catch(n){await Rh(n)}}function df(e,t){(e.jo.get(t)||[]).forEach((e=>{e.resolve()})),e.jo.delete(t)}function ff(e,t,n){const r=Ha(e);let i=r.Ko[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Ko[r.currentUser.toKey()]=i}}function pf(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.Mo.get(t))e.Oo.delete(r),n&&e.Fo.zo(r,n);e.Mo.delete(t),e.isPrimaryClient&&e.qo.us(t).forEach((t=>{e.qo.containsKey(t)||mf(e,t)}))}function mf(e,t){e.Lo.delete(t.path.canonicalString());const n=e.Bo.get(t);null!==n&&(gd(e.remoteStore,n),e.Bo=e.Bo.remove(t),e.Uo.delete(n),vf(e))}function gf(e,t,n){for(const r of n)r instanceof Yd?(e.qo.addReference(r.key,t),yf(e,r)):r instanceof Zd?(Fa("SyncEngine","Document no longer in limbo: "+r.key),e.qo.removeReference(r.key,t),e.qo.containsKey(r.key)||mf(e,r.key)):Ba()}function yf(e,t){const n=t.key,r=n.path.canonicalString();e.Bo.get(n)||e.Lo.has(r)||(Fa("SyncEngine","New document in limbo: "+n),e.Lo.add(r),vf(e))}function vf(e){for(;e.Lo.size>0&&e.Bo.size{o.push(r.Go(a,t,n).then((e=>{if(e){r.isPrimaryClient&&r.sharedClientState.updateQueryState(a.targetId,e.fromCache?"not-current":"current"),i.push(e);const t=Oh.$n(a.targetId,e);s.push(t)}})))})),await Promise.all(o),r.Fo.Pr(i),await async function(e,t){const n=Ha(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>wh.forEach(t,(t=>wh.forEach(t.kn,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>wh.forEach(t.xn,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!Ih(e))throw e;Fa("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=n.qn.get(t),r=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(r);n.qn=n.qn.insert(t,i)}}}(r.localStore,s))}async function If(e,t){const n=Ha(e);if(!n.currentUser.isEqual(t)){Fa("SyncEngine","User change. New user:",t.toKey());const e=await xh(n.localStore,t);n.currentUser=t,function(e,t){e.jo.forEach((e=>{e.forEach((e=>{e.reject(new za(Ka.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.jo.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await wf(n,e.Gn)}}function Tf(e,t){const n=Ha(e),r=n.Uo.get(t);if(r&&r.$o)return gl().add(r.key);{let e=gl();const r=n.Mo.get(t);if(!r)return e;for(const t of r){const r=n.Oo.get(t);e=e.unionWith(r.view.Po)}return e}}function Ef(e){const t=Ha(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=lf.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=hf.bind(null,t),t}class bf{constructor(){this.synchronizeTabs=!1}async initialize(e){this.k=sd(e.databaseInfo.databaseId),this.sharedClientState=this.Jo(e),this.persistence=this.Yo(e),await this.persistence.start(),this.gcScheduler=this.Xo(e),this.localStore=this.Zo(e)}Xo(e){return null}Zo(e){return function(e,t,n,r){return new Mh(e,t,n,r)}(this.persistence,new Ph,e.initialUser,this.k)}Yo(e){return new Wh(Xh.ks,this.k)}Jo(e){return new Yh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class _f{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>cf(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=If.bind(null,this.syncEngine),await async function(e,t){const n=Ha(e);t?(n.Gr.delete(2),await fd(n)):t||(n.Gr.add(2),await pd(n),n.Jr.set("Unknown"))}(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Kd}createDatastore(e){const t=sd(e.databaseInfo.databaseId),n=(r=e.databaseInfo,new rd(r));var r;return function(e,t,n,r){return new ld(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>cf(this.syncEngine,e,0),s=ed.bt()?new ed:new Zh,new dd(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new rf(e,t,n,r,i,s);return o&&(a.Wo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=Ha(e);Fa("RemoteStore","RemoteStore shutting down."),t.Gr.add(5),await pd(t),t.Hr.shutdown(),t.Jr.set("Unknown")}(this.remoteStore)}}class Sf{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.ea(this.observer.next,e)}error(e){this.observer.error?this.ea(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}na(){this.muted=!0}ea(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class kf{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Pa.UNAUTHENTICATED,this.clientId=rc.A(),this.authCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{Fa("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(()=>Promise.resolve()))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new za(Ka.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new Ga;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=jd(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function Af(e,t){e.asyncQueue.verifyOperationInProgress();const n=await async function(e){return e.offlineComponents||(Fa("FirestoreClient","Using default OfflineComponentProvider"),await async function(e,t){e.asyncQueue.verifyOperationInProgress(),Fa("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await xh(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e.offlineComponents=t}(e,new bf)),e.offlineComponents}(e);Fa("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>async function(e,t){const n=Ha(e);n.asyncQueue.verifyOperationInProgress(),Fa("RemoteStore","RemoteStore received new credentials");const r=Td(n);n.Gr.add(3),await pd(n),r&&n.Jr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Gr.delete(3),await fd(n)}(t.remoteStore,e))),e.onlineComponents=t}async function Cf(e){return e.onlineComponents||(Fa("FirestoreClient","Using default OnlineComponentProvider"),await Af(e,new _f)),e.onlineComponents}async function Nf(e){const t=await Cf(e),n=t.eventManager;return n.onListen=sf.bind(null,t.syncEngine),n.onUnlisten=of.bind(null,t.syncEngine),n}class Rf{constructor(e,t,n,r,i,s,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class Df{constructor(e,t){this.projectId=e,this.database=t||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Df&&e.projectId===this.projectId&&e.database===this.database}}const Lf=new Map;function Of(e,t,n){if(!n)throw new za(Ka.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Pf(e){if(!kc.isDocumentKey(e))throw new za(Ka.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Mf(e){if(kc.isDocumentKey(e))throw new za(Ka.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function xf(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":Ba()}function Uf(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new za(Ka.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=xf(e);throw new za(Ka.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}class Ff{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new za(Ka.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new za(Ka.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,function(e,t,n,r){if(!0===t&&!0===r)throw new za(Ka.INVALID_ARGUMENT,"experimentalForceLongPolling and experimentalAutoDetectLongPolling cannot be used together.")}(0,e.experimentalForceLongPolling,0,e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Vf{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Ff({}),this._settingsFrozen=!1,e instanceof Df?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new za(Ka.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Df(e.options.projectId)}(e))}get app(){if(!this._app)throw new za(Ka.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new za(Ka.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Ff(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Ja;switch(e.type){case"gapi":const t=e.client;return $a(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new Ya(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new za(Ka.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Lf.get(e);t&&(Fa("ComponentProvider","Removing Datastore"),Lf.delete(e),t.terminate())}(this),Promise.resolve()}}class jf{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Bf(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new jf(this.firestore,e,this._key)}}class qf{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new qf(this.firestore,e,this._query)}}class Bf extends qf{constructor(e,t,n){super(e,t,lu(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new jf(this.firestore,null,new kc(e))}withConverter(e){return new Bf(this.firestore,e,this._path)}}function $f(e,t,...n){if(e=w(e),1===arguments.length&&(t=rc.A()),Of("doc","path",t),e instanceof Vf){const r=dc.fromString(t,...n);return Pf(r),new jf(e,null,new kc(r))}{if(!(e instanceof jf||e instanceof Bf))throw new za(Ka.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(dc.fromString(t,...n));return Pf(r),new jf(e.firestore,e instanceof Bf?e.converter:null,new kc(r))}}class Hf{constructor(){this.ma=Promise.resolve(),this.ga=[],this.ya=!1,this.pa=[],this.Ta=null,this.Ea=!1,this.Ia=!1,this.Aa=[],this.ur=new od(this,"async_queue_retry"),this.Ra=()=>{const e=id();e&&Fa("AsyncQueue","Visibility state changed to "+e.visibilityState),this.ur.er()};const e=id();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Ra)}get isShuttingDown(){return this.ya}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Pa(),this.ba(e)}enterRestrictedMode(e){if(!this.ya){this.ya=!0,this.Ia=e||!1;const t=id();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Ra)}}enqueue(e){if(this.Pa(),this.ya)return new Promise((()=>{}));const t=new Ga;return this.ba((()=>this.ya&&this.Ia?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.ga.push(e),this.va())))}async va(){if(0!==this.ga.length){try{await this.ga[0](),this.ga.shift(),this.ur.reset()}catch(e){if(!Ih(e))throw e;Fa("AsyncQueue","Operation failed with retryable error: "+e)}this.ga.length>0&&this.ur.Zi((()=>this.va()))}}ba(e){const t=this.ma.then((()=>(this.Ea=!0,e().catch((e=>{this.Ta=e,this.Ea=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw Va("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.Ea=!1,e))))));return this.ma=t,t}enqueueAfterDelay(e,t,n){this.Pa(),this.Aa.indexOf(e)>-1&&(t=0);const r=Vd.createAndSchedule(this,e,t,n,(e=>this.Va(e)));return this.pa.push(r),r}Pa(){this.Ta&&Ba()}verifyOperationInProgress(){}async Sa(){let e;do{e=this.ma,await e}while(e!==this.ma)}Da(e){for(const t of this.pa)if(t.timerId===e)return!0;return!1}Ca(e){return this.Sa().then((()=>{this.pa.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.pa)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Sa()}))}Na(e){this.Aa.push(e)}Va(e){const t=this.pa.indexOf(e);this.pa.splice(t,1)}}function Kf(e){return function(e,t){if("object"!=typeof e||null===e)return!1;const n=e;for(const e of["next","error","complete"])if(e in n&&"function"==typeof n[e])return!0;return!1}(e)}class zf extends Vf{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new Hf,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||Wf(this),this._firestoreClient.terminate()}}function Gf(e){return e._firestoreClient||Wf(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Wf(e){var t;const n=e._freezeSettings(),r=function(e,t,n,r){return new Rf(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,n);e._firestoreClient=new kf(e._authCredentials,e._appCheckCredentials,e._queue,r)}class Jf{constructor(...e){for(let t=0;t90)throw new za(Ka.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new za(Ka.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return ic(this._lat,e._lat)||ic(this._long,e._long)}}const Zf=/^__.*__$/;class ep{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Ju(e,this.data,this.fieldMask,t,this.fieldTransforms):new Wu(e,this.data,t,this.fieldTransforms)}}function tp(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Ba()}}class np{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.k=n,this.ignoreUndefinedProperties=r,void 0===i&&this.ka(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get xa(){return this.settings.xa}$a(e){return new np(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.k,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Fa(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$a({path:n,Oa:!1});return r.Ma(e),r}La(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$a({path:n,Oa:!1});return r.ka(),r}Ba(e){return this.$a({path:void 0,Oa:!0})}Ua(e){return fp(e,this.settings.methodName,this.settings.qa||!1,this.path,this.settings.Ka)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}ka(){if(this.path)for(let e=0;ec.covers(e.field)))}else c=null,u=o.fieldTransforms;return new ep(new jc(a),c,u)}function op(e,t){if(cp(e=w(e)))return up("Unsupported field value:",t,e),ap(e,t);if(e instanceof Qf)return function(e,t){if(!tp(t.xa))throw t.Ua(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Ua(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Oa&&4!==t.xa)throw t.Ua("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=op(i,t.Ba(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=w(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ku(t.k,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=oc.fromDate(e);return{timestampValue:Dl(t.k,n)}}if(e instanceof oc){const n=new oc(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Dl(t.k,n)}}if(e instanceof Yf)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Xf)return{bytesValue:Ll(t.k,e._byteString)};if(e instanceof jf){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.Ua(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:Ml(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Ua(`Unsupported field value: ${xf(e)}`)}(e,t)}function ap(e,t){const n={};return lc(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):uc(e,((e,r)=>{const i=op(r,t.Fa(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function cp(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof oc||e instanceof Yf||e instanceof Xf||e instanceof jf||e instanceof Qf)}function up(e,t,n){if(!cp(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=xf(n);throw"an object"===r?t.Ua(e+" a custom object"):t.Ua(e+" "+r)}}function lp(e,t,n){if((t=w(t))instanceof Jf)return t._internalPath;if("string"==typeof t)return dp(e,t);throw fp("Field path arguments must be of type string or FieldPath.",e,!1,void 0,n)}const hp=new RegExp("[~\\*/\\[\\]]");function dp(e,t,n){if(t.search(hp)>=0)throw fp(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new Jf(...t.split("."))._internalPath}catch(r){throw fp(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function fp(e,t,n,r,i){const s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new za(Ka.INVALID_ARGUMENT,a+e+c)}function pp(e,t){return e.some((e=>e.isEqual(t)))}class mp{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new jf(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new gp(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(yp("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class gp extends mp{data(){return super.data()}}function yp(e,t){return"string"==typeof t?dp(e,t):t instanceof Jf?t._internalPath:t._delegate._internalPath}class vp{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class wp extends mp{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new Ip(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){const n=this._document.data.field(yp("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Ip extends wp{data(e={}){return super.data(e)}}class Tp{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new vp(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Ip(this._firestore,this._userDataWriter,n.key,n,new vp(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new za(Ka.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>({type:"added",doc:new Ip(e._firestore,e._userDataWriter,n.doc.key,n.doc,new vp(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter),oldIndex:-1,newIndex:t++})))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Ip(e._firestore,e._userDataWriter,t.doc.key,t.doc,new vp(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:Ep(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Ep(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Ba()}}class bp{}class _p extends bp{constructor(e,t){super(),this.Ga=e,this.Ja=t,this.type="orderBy"}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new za(Ka.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new za(Ka.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const r=new su(t,n);return function(e,t){if(null===fu(e)){const n=pu(e);null!==n&&function(e,t,n){if(!n.isEqual(t))throw new za(Ka.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}(0,n,t.field)}}(e,r),r}(e._query,this.Ga,this.Ja);return new qf(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new uu(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class Sp extends bp{constructor(e,t,n){super(),this.type=e,this.Ya=t,this.Xa=n}_apply(e){return new qf(e.firestore,e.converter,yu(e._query,this.Ya,this.Xa))}}class kp extends class{convertValue(e,t="none"){switch(Ac(e)){case 0:return null;case 1:return e.booleanValue;case 2:return wc(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Ic(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw Ba()}}convertObject(e,t){const n={};return uc(e.fields,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new Yf(wc(e.latitude),wc(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=Ec(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(bc(e));default:return null}}convertTimestamp(e){const t=vc(e);return new oc(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=dc.fromString(e);$a(nh(n));const r=new Df(n.get(1),n.get(3)),i=new kc(n.popFirst(5));return r.isEqual(t)||Va(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}{constructor(e){super(),this.firestore=e}convertBytes(e){return new Xf(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new jf(this.firestore,null,t)}}function Ap(e,t){return function(e,t){const n=new Ga;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=Ef(e);try{const e=await function(e,t){const n=Ha(e),r=oc.now(),i=t.reduce(((e,t)=>e.add(t.key)),gl());let s;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>n.Wn.vn(e,i).next((i=>{s=i;const o=[];for(const e of t){const t=Ku(e,s.get(e.key));null!=t&&o.push(new Ju(e.key,t,qc(t.value.mapValue),ju.exists(!0)))}return n.An.addMutationBatch(e,r,o,t)})))).then((e=>(e.applyToLocalDocumentSet(s),{batchId:e.batchId,changes:s})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Ko[e.currentUser.toKey()];r||(r=new sl(ic)),r=r.insert(t,n),e.Ko[e.currentUser.toKey()]=r}(r,e.batchId,n),await wf(r,e.changes),await Cd(r.remoteStore)}catch(e){const t=jd(e,"Failed to persist write");n.reject(t)}}(await function(e){return Cf(e).then((e=>e.syncEngine))}(e),t,n))),n.promise}(Gf(e),t)}function Cp(e,t,n){const r=n.docs.get(t._key),i=new kp(e);return new wp(e,i,t._key,r,new vp(n.hasPendingWrites,n.fromCache),t.converter)}!function(e,t=!0){Ma="9.6.1",j(new I("firestore",((e,{options:n})=>{const r=e.getProvider("app").getImmediate(),i=new zf(r,new Xa(e.getProvider("auth-internal")),new ec(e.getProvider("app-check-internal")));return n=Object.assign({useFetchStreams:t},n),i._setSettings(n),i}),"PUBLIC")),z(Oa,"3.4.1",e),z(Oa,"3.4.1","esm2017")}();const Np=document.querySelector("body"),Rp=document.querySelector(".saveStats"),Dp=document.querySelector(".profile>.routs>.signUp"),Lp=document.querySelector(".windowTop>.options>.signupBtn"),Op=document.querySelector(".profileBtn"),Pp=document.querySelector(".profile"),Mp=document.querySelectorAll(".options>.close"),xp=document.querySelectorAll(".windowTop>.move"),Up=document.querySelector(".settingsBtn"),Fp=document.querySelector(".settings"),Vp=document.querySelector(".themeSelector"),jp=document.querySelector(".profile>.routs"),qp=document.querySelector(".text"),Bp=document.querySelector(".stats"),$p=document.querySelector(".containerStats>.speed"),Hp=document.querySelector(".loginBtn"),Kp=document.querySelector(".profile>.routs>.signIn"),zp=document.querySelector(".updateBtn"),Gp=document.querySelector(".profile>.routs>.update"),Wp=document.querySelector(".logoutBtn"),Jp=document.querySelector(".info"),Xp=document.querySelector(".loader"),Qp=(document.querySelector(".options"),document.querySelector(".leaderBoard")),Yp=document.querySelector(".leaderBoard>.content"),Zp=document.querySelector(".leaderBoardBtn"),em=document.querySelector(".container>.info"),tm=document.querySelector(".username"),nm=document.querySelector(".textOptions"),rm=document.querySelector(".nextBtn");function im(e,t){if(t){let n=`${e}${t.userName}${t.speed}`,r=document.createElement("li");r.innerHTML=n,r.classList.add("leaderBoardListItem"),Yp.appendChild(r)}}const sm=function(e=K()){return q(e,"firestore").getImmediate()}(Xe),om=async()=>{let e=Tr(),t=e.currentUser&&e.currentUser.uid;if(t){const e=$f(sm,`scores/${t}`);let n=e&&await function(e){e=Uf(e,jf);const t=Uf(e.firestore,zf);return function(e,t,n={}){const r=new Ga;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new Sf({next:s=>{t.enqueueAndForget((()=>Gd(e,o)));const a=s.docs.has(n);!a&&s.fromCache?i.reject(new za(Ka.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&s.fromCache&&r&&"server"===r.source?i.reject(new za(Ka.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):i.resolve(s)},error:e=>i.reject(e)}),o=new Qd(lu(n.path),s,{includeMetadataChanges:!0,wo:!0});return zd(e,o)}(await Nf(e),e.asyncQueue,t,n,r))),r.promise}(Gf(t),e._key).then((n=>Cp(t,e,n)))}(e);return n.exists()?n.data():null}return null},am=e=>{(function(e,t,n){e=Uf(e,jf);const r=Uf(e.firestore,zf),i=function(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}(e.converter,t,n);return Ap(r,[sp(ip(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,ju.none())])})($f(sm,`scores/${e.uId}`),e,{merge:!0}).then(console.log("added successfully")).catch((e=>console.error("I got an error",e)))};let cm;const um="user.data";async function lm(){return navigator.onLine?await om():JSON.parse(localStorage.getItem(um))}function hm(){return JSON.parse(localStorage.getItem(um))}function dm(e){return localStorage.setItem(um,JSON.stringify(e)),e}function fm(e){return localStorage.setItem(um,JSON.stringify(e)),am(e),e}var pm;var mm;const gm=async()=>{let e=await fetch("https://api.quotable.io/random").then((e=>e.json())).then((e=>e.content)).catch((e=>{console.error(e.message),qp.innerText="check your network connection"})),t=hm();t.punctuationMode||(e=e.replace(/[^ \w]/g,"")),t.smallCaseMode&&(e=e.toLowerCase()),mm=qp.innerText=e,Nm(),km(qp),(e=>{let t,n,r=!0,i=e,s=0,o=0,a=document.querySelectorAll(".text>span");a[s].classList.add("blink"),document.addEventListener("keypress",(c=>{c.key===i[0]?(r&&(t=(new Date).getTime(),r=!1),i=i.substr(1),a[s].classList.add("correctWord"),a[s].classList.remove("blink"),s{let n=e/(t.toPrecision(2)/60);pm=Math.floor(n.toPrecision(3)),$p.innerText=pm;let r=await lm();r&&pm>r.topSpeed?(r={...r,topSpeed:pm},console.log("setUserData called"),fm(r)):r&&dm({...r,lastSpeed:pm}),em.classList.toggle("hide"),em.classList.toggle("fadeOut"),setTimeout((()=>{gm(),em.classList.toggle("fadeOut"),setTimeout((()=>{em.classList.toggle("hide")}),500)}),500)})(_m,(n-t)/1e3)),s++):null!=a[s]&&a[s].classList.add("wrongWord")}))})(mm)};function ym(e){e?(Wp.classList.remove("hide"),zp.classList.remove("hide"),Lp.classList.add("hide"),Hp.classList.add("hide")):(Wp.classList.add("hide"),zp.classList.add("hide"),Lp.classList.remove("hide"),Hp.classList.remove("hide"))}ym();const vm=(e,t)=>{jp.childNodes.forEach((n=>{n.classList&&(n==e?(n.classList.remove("hide"),n.classList.contains("stats")&&t?Rp.classList.remove("hide"):Rp.classList.add("hide")):!n.classList.contains("hide")&&n.classList.add("hide"))}))};n(162);var wm=n(306),Im=n.n(wm);let Tm=!1,Em=!0,bm="dark";var _m;const Sm=document.querySelector(".words"),km=e=>{let t=[];for(let e=0;e${mm[e]}`);let n=t.join("");e.innerHTML=n};Op.addEventListener("click",(async()=>{if(Pp.classList.contains("hide")){Pp.classList.toggle("hide");let e=await lm();ym(e),!e||0===Object.entries(e).length&&e.constructor===Object?vm(Jp):(Cm(e),zp.classList.remove("hide"),Lp.classList.add("hide"))}else Pp.classList.add("hide")})),Mp.forEach((e=>{e.addEventListener("click",(e=>{let t=e.target.parentElement.parentElement.parentElement;vm(Xp),t.classList.toggle("hide")}))})),xp.forEach((e=>{e.addEventListener("drag",(e=>{e.target.parentElement.parentElement.style.filter="brightness(.7)"}))})),xp.forEach((e=>{e.addEventListener("dragend",(e=>{let t=e.target.parentElement.parentElement;t.style.filter="brightness(1)",Am(e,t)}))}));const Am=(e,t)=>{t.style.left=e.pageX-20+"px",t.style.top=e.pageY-20+"px"},Cm=async e=>(!e||0===Object.entries(e).length&&e.constructor===Object?vm(Jp):(Bp.lastElementChild.lastElementChild.childNodes.forEach((t=>{t.classList&&(t.classList.contains("name")?(e.userName.length>10?t.style.fontSize=20:e.userName.length>20&&(t.style.fontSize=15),t.innerHTML=e.userName):t.classList.contains("speed")&&(e.userName.length>10&&(t.style.fontSize=30),t.innerHTML=e.topSpeed))})),vm(Bp,e)),e);Up.addEventListener("click",(()=>{Fp.classList.toggle("hide")})),Vp.addEventListener("change",(async e=>{let t=await lm();if(e.target.options.light.selected){if(Np.classList.contains("light"))return;Np.classList.remove("dark"),Np.classList.add("light"),t?fm({...t,theme:"light"}):(t=hm(),dm({...t,theme:"light"}))}else if(e.target.options.dark.selected){if(Np.classList.contains("dark"))return;Np.classList.remove("light"),Np.classList.add("dark"),t?fm({...t,theme:"dark"}):(t=hm(),dm({...t,theme:"dark"}))}})),Rp.addEventListener("click",(()=>{Im().toBlob(Bp).then((e=>{window.saveAs(e,"stats.png")}))})),Dp.addEventListener("submit",(e=>{e.preventDefault(),Lm({email:e.target.email.value,username:e.target.username.value,password:e.target.password.value}),vm(Xp)})),Kp.addEventListener("submit",(e=>{e.preventDefault(),Dm({email:e.target.email.value,password:e.target.password.value}),vm(Xp)})),Lp.addEventListener("click",(()=>{vm(Dp)})),Hp.addEventListener("click",(()=>{vm(Kp)})),Wp.addEventListener("click",(()=>{Om()})),zp.addEventListener("click",(()=>{vm(Gp)})),Gp.addEventListener("submit",(e=>{e.preventDefault();let t=e.target.username.value;t&&" "!=t[0]&&t.length>0?Pm(t):console.log("enter username",t)})),Zp.addEventListener("click",(()=>{Yp.parentElement.classList.contains("hide")?(Yp.parentElement.classList.toggle("hide"),setTimeout((()=>{Yp.parentElement.classList.toggle("fadeOut")}),200)):(Yp.parentElement.classList.toggle("fadeOut"),setTimeout((()=>{Yp.parentElement.classList.toggle("hide")}),500))})),Qp.addEventListener("click",(e=>{e.target.classList.contains("leaderBoard")&&(Qp.classList.toggle("fadeOut"),setTimeout((()=>{Qp.classList.toggle("hide")}),200))})),nm.addEventListener("click",(async e=>{let t=await lm();e.target.classList.contains("smallCase")?(e.target.classList.contains("active")?(Tm=!1,e.target.classList.remove("active")):(Tm=!0,e.target.classList.add("active")),t?fm({...t,smallCaseMode:Tm}):(t=hm(),dm({...t,smallCaseMode:Tm}))):e.target.classList.contains("punctuation")&&(e.target.classList.contains("active")?(Em=!1,e.target.classList.remove("active")):(Em=!0,e.target.classList.add("active")),t?fm({...t,punctuationMode:Em}):(t=hm(),dm({...t,punctuationMode:Em})))})),rm.addEventListener("click",(()=>{gm()}));const Nm=(e=0)=>{let t,n=/ /g,r=[];for(;t=n.exec(mm);)r.push(t.index);_m=r.length+1,Sm.innerText=`${_m}/${e}`},Rm=Tr(Xe),Dm=async({email:e,password:t})=>{try{await function(e,t,n){return async function(e,t){return yn(Xt(e),t)}(w(e),on.credential(t,n))}(Rm,e,t)}catch(e){alert(e.code)}},Lm=async({email:e,password:t,username:n})=>{try{const r=await async function(e,t,n){const r=Xt(e),i=await async function(e,t){return It(e,"POST","/v1/accounts:signUp",yt(e,t))}(r,{returnSecureToken:!0,email:t,password:n}),s=await fn._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(s.user),s}(Rm,e,t);await vn(r.user,{displayName:n||r.email.split("@")[0]}).then((()=>{console.log("updated the name"),fm({uId:r.user.uid,userName:r.user.displayName,topSpeed:0,theme:bm,punctuationMode:Em,smallCaseMode:Tm,lastSpeed:0})}))}catch(e){alert(e.code)}},Om=()=>{try{!function(e){w(e).signOut()}(Rm),console.log("user logged out")}catch(e){alert(e.code)}},Pm=async e=>{try{let t=Rm.currentUser;vm(Xp),await vn(t,{displayName:e}).then((()=>{console.log("updated the name"),function(e){am(e);let t=getUserTheme();localStorage.setItem(um,JSON.stringify({...t,userName:e.username}))}({uId:t.uid,userName:t.displayName}),lm().then((e=>{Cm(e)}))}))}catch(e){alert("check your network")}};window.onload=()=>{if(hm()){let e=hm().theme;"dark"!=e&&(Np.classList.remove("dark"),Np.classList.add(e)),Vp.options[e].selected=!0,hm().punctuationMode?nm.children[0].classList.add("active"):nm.children[0].classList.remove("active"),hm().smallCaseMode?nm.children[1].classList.add("active"):nm.children[1].classList.remove("active"),function(e){e&&($p.innerText=e)}(hm().lastSpeed)}else dm({punctuationMode:Em,smallCaseMode:Tm,theme:bm})},gm(),function(e,t,n,r){w(e).onAuthStateChanged((async e=>{e?(ym(e=await lm()),Cm(e),tm.innerText=e.userName):(ym(e),Cm(e),tm.innerText=" ")}),void 0,void 0)}(Rm),function(){const e=function(e,t,...n){if(e=w(e),Of("collection","path",t),e instanceof Vf){const r=dc.fromString(t,...n);return Mf(r),new Bf(e,null,r)}{if(!(e instanceof jf||e instanceof Bf))throw new za(Ka.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(dc.fromString(t,...n));return Mf(r),new Bf(e.firestore,null,r)}}(sm,"scores"),t=function(e,...t){for(const n of t)e=n._apply(e);return e}(e,function(e,t="asc"){const n=t,r=yp("orderBy","topSpeed");return new _p(r,n)}(0,"desc"),(function(e,t){if(t<=0)throw new za(Ka.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}("limit",10),new Sp("limit",10,"F")));cm=function(e,...t){var n,r,i;e=w(e);let s={includeMetadataChanges:!1},o=0;"object"!=typeof t[o]||Kf(t[o])||(s=t[o],o++);const a={includeMetadataChanges:s.includeMetadataChanges};if(Kf(t[o])){const e=t[o];t[o]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[o+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[o+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}let c,u,l;if(e instanceof jf)u=Uf(e.firestore,zf),l=lu(e._key.path),c={next:n=>{t[o]&&t[o](Cp(u,e,n))},error:t[o+1],complete:t[o+2]};else{const n=Uf(e,qf);u=Uf(n.firestore,zf),l=n._query;const r=new kp(u);c={next:e=>{t[o]&&t[o](new Tp(u,r,n,e))},error:t[o+1],complete:t[o+2]},function(e){if(du(e)&&0===e.explicitOrderBy.length)throw new za(Ka.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query)}return function(e,t,n,r){const i=new Sf(r),s=new Qd(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>zd(await Nf(e),s))),()=>{i.na(),e.asyncQueue.enqueueAndForget((async()=>Gd(await Nf(e),s)))}}(Gf(u),l,a,c)}(t,e,(e=>{if(e){const t=[];!function(){for(;Yp.firstChild;)Yp.firstChild.remove()}(),function(){let e=document.createElement("li");e.classList.add("leaderBoardHeader"),e.innerText="leaderboard";let t=document.createElement("li");t.classList.add("leaderBoardInfo"),t.innerHTML='RankUsernameTop Speed',Yp.appendChild(e),Yp.appendChild(t)}(),e.forEach((e=>{let n=e.data();n.topSpeed>0&&t.push({userName:n.userName,speed:n.topSpeed})}));for(let e=0;e{var e={306:function(e){!function(t){"use strict";var n=function(){return{escape:function(e){return e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")},parseExtension:t,mimeType:function(e){var n,r;return(n="application/font-woff",r="image/jpeg",{woff:n,woff2:n,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:r,jpeg:r,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml"})[t(e).toLowerCase()]||""},dataAsUrl:function(e,t){return"data:"+t+";base64,"+e},isDataUrl:function(e){return-1!==e.search(/^(data:)/)},canvasToBlob:function(e){return e.toBlob?new Promise((function(t){e.toBlob(t)})):function(e){return new Promise((function(t){for(var n=window.atob(e.toDataURL().split(",")[1]),r=n.length,i=new Uint8Array(r),s=0;s'+e+""})).then((function(e){return''+e+""})).then((function(e){return"data:image/svg+xml;charset=utf-8,"+e}))}(r,t.width||n.width(e),t.height||n.height(e))}))}function l(e,t){return u(e,t).then(n.makeImage).then(n.delay(100)).then((function(r){var i=function(e){var r=document.createElement("canvas");if(r.width=t.width||n.width(e),r.height=t.height||n.height(e),t.bgcolor){var i=r.getContext("2d");i.fillStyle=t.bgcolor,i.fillRect(0,0,r.width,r.height)}return r}(e);return i.getContext("2d").drawImage(r,0,0),i}))}function h(e,t,r){return r||!t||t(e)?Promise.resolve(e).then((function(e){return e instanceof HTMLCanvasElement?n.makeImage(e.toDataURL()):e.cloneNode(!1)})).then((function(r){return function(e,t,r){var i=e.childNodes;return 0===i.length?Promise.resolve(t):function(e,t,n){var r=Promise.resolve();return t.forEach((function(t){r=r.then((function(){return h(t,n)})).then((function(t){t&&e.appendChild(t)}))})),r}(t,n.asArray(i),r).then((function(){return t}))}(e,r,t)})).then((function(t){return function(e,t){return t instanceof Element?Promise.resolve().then((function(){r=window.getComputedStyle(e),i=t.style,r.cssText?i.cssText=r.cssText:function(e,t){n.asArray(e).forEach((function(n){t.setProperty(n,e.getPropertyValue(n),e.getPropertyPriority(n))}))}(r,i);var r,i})).then((function(){[":before",":after"].forEach((function(r){!function(r){var i=window.getComputedStyle(e,r),s=i.getPropertyValue("content");if(""!==s&&"none"!==s){var o=n.uid();t.className=t.className+" "+o;var a=document.createElement("style");a.appendChild(function(e,t,r){var i="."+e+":"+t,s=r.cssText?o(r):a(r);return document.createTextNode(i+"{"+s+"}");function o(e){var t=e.getPropertyValue("content");return e.cssText+" content: "+t+";"}function a(e){return n.asArray(e).map(t).join("; ")+";";function t(t){return t+": "+e.getPropertyValue(t)+(e.getPropertyPriority(t)?" !important":"")}}}(o,r,i)),t.appendChild(a)}}(r)}))})).then((function(){e instanceof HTMLTextAreaElement&&(t.innerHTML=e.value),e instanceof HTMLInputElement&&t.setAttribute("value",e.value)})).then((function(){t instanceof SVGElement&&(t.setAttribute("xmlns","http://www.w3.org/2000/svg"),t instanceof SVGRectElement&&["width","height"].forEach((function(e){var n=t.getAttribute(e);n&&t.style.setProperty(e,n)})))})).then((function(){return t})):t}(e,t)})):Promise.resolve()}function d(e){return i.resolveAll().then((function(t){var n=document.createElement("style");return e.appendChild(n),n.appendChild(document.createTextNode(t)),e}))}function f(e){return s.inlineAll(e).then((function(){return e}))}e.exports=c}()},162:function(e,t,n){var r;void 0===(r=function(){"use strict";function t(e,t,n){var r=new XMLHttpRequest;r.open("GET",e),r.responseType="blob",r.onload=function(){a(r.response,t,n)},r.onerror=function(){console.error("could not download file")},r.send()}function r(e){var t=new XMLHttpRequest;t.open("HEAD",e,!1);try{t.send()}catch(e){}return 200<=t.status&&299>=t.status}function i(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(n){var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(t)}}var s="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof n.g&&n.g.global===n.g?n.g:void 0,o=s.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),a=s.saveAs||("object"!=typeof window||window!==s?function(){}:"download"in HTMLAnchorElement.prototype&&!o?function(e,n,o){var a=s.URL||s.webkitURL,c=document.createElement("a");n=n||e.name||"download",c.download=n,c.rel="noopener","string"==typeof e?(c.href=e,c.origin===location.origin?i(c):r(c.href)?t(e,n,o):i(c,c.target="_blank")):(c.href=a.createObjectURL(e),setTimeout((function(){a.revokeObjectURL(c.href)}),4e4),setTimeout((function(){i(c)}),0))}:"msSaveOrOpenBlob"in navigator?function(e,n,s){if(n=n||e.name||"download","string"!=typeof e)navigator.msSaveOrOpenBlob(function(e,t){return void 0===t?t={autoBom:!1}:"object"!=typeof t&&(console.warn("Deprecated: Expected third argument to be a object"),t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e}(e,s),n);else if(r(e))t(e,n,s);else{var o=document.createElement("a");o.href=e,o.target="_blank",setTimeout((function(){i(o)}))}}:function(e,n,r,i){if((i=i||open("","_blank"))&&(i.document.title=i.document.body.innerText="downloading..."),"string"==typeof e)return t(e,n,r);var a="application/octet-stream"===e.type,c=/constructor/i.test(s.HTMLElement)||s.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||a&&c||o)&&"undefined"!=typeof FileReader){var l=new FileReader;l.onloadend=function(){var e=l.result;e=u?e:e.replace(/^data:[^;]*;/,"data:attachment/file;"),i?i.location.href=e:location=e,i=null},l.readAsDataURL(e)}else{var h=s.URL||s.webkitURL,d=h.createObjectURL(e);i?i.location=d:location.href=d,i=null,setTimeout((function(){h.revokeObjectURL(d)}),4e4)}});s.saveAs=a.saveAs=a,e.exports=a}.apply(t,[]))||(e.exports=r)},676:function(e,t){!function(e){"use strict";function t(e){return Array.prototype.slice.call(e)}function n(e){return new Promise((function(t,n){e.onsuccess=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function r(e,t,r){var i,s=new Promise((function(s,o){n(i=e[t].apply(e,r)).then(s,o)}));return s.request=i,s}function i(e,t,n){var i=r(e,t,n);return i.then((function(e){if(e)return new l(e,i.request)}))}function s(e,t,n){n.forEach((function(n){Object.defineProperty(e.prototype,n,{get:function(){return this[t][n]},set:function(e){this[t][n]=e}})}))}function o(e,t,n,i){i.forEach((function(i){i in n.prototype&&(e.prototype[i]=function(){return r(this[t],i,arguments)})}))}function a(e,t,n,r){r.forEach((function(r){r in n.prototype&&(e.prototype[r]=function(){return this[t][r].apply(this[t],arguments)})}))}function c(e,t,n,r){r.forEach((function(r){r in n.prototype&&(e.prototype[r]=function(){return i(this[t],r,arguments)})}))}function u(e){this._index=e}function l(e,t){this._cursor=e,this._request=t}function h(e){this._store=e}function d(e){this._tx=e,this.complete=new Promise((function(t,n){e.oncomplete=function(){t()},e.onerror=function(){n(e.error)},e.onabort=function(){n(e.error)}}))}function f(e,t,n){this._db=e,this.oldVersion=t,this.transaction=new d(n)}function p(e){this._db=e}s(u,"_index",["name","keyPath","multiEntry","unique"]),o(u,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),c(u,"_index",IDBIndex,["openCursor","openKeyCursor"]),s(l,"_cursor",["direction","key","primaryKey","value"]),o(l,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(e){e in IDBCursor.prototype&&(l.prototype[e]=function(){var t=this,r=arguments;return Promise.resolve().then((function(){return t._cursor[e].apply(t._cursor,r),n(t._request).then((function(e){if(e)return new l(e,t._request)}))}))})})),h.prototype.createIndex=function(){return new u(this._store.createIndex.apply(this._store,arguments))},h.prototype.index=function(){return new u(this._store.index.apply(this._store,arguments))},s(h,"_store",["name","keyPath","indexNames","autoIncrement"]),o(h,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),c(h,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),a(h,"_store",IDBObjectStore,["deleteIndex"]),d.prototype.objectStore=function(){return new h(this._tx.objectStore.apply(this._tx,arguments))},s(d,"_tx",["objectStoreNames","mode"]),a(d,"_tx",IDBTransaction,["abort"]),f.prototype.createObjectStore=function(){return new h(this._db.createObjectStore.apply(this._db,arguments))},s(f,"_db",["name","version","objectStoreNames"]),a(f,"_db",IDBDatabase,["deleteObjectStore","close"]),p.prototype.transaction=function(){return new d(this._db.transaction.apply(this._db,arguments))},s(p,"_db",["name","version","objectStoreNames"]),a(p,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(e){[h,u].forEach((function(n){e in n.prototype&&(n.prototype[e.replace("open","iterate")]=function(){var n=t(arguments),r=n[n.length-1],i=this._store||this._index,s=i[e].apply(i,n.slice(0,-1));s.onsuccess=function(){r(s.result)}})}))})),[u,h].forEach((function(e){e.prototype.getAll||(e.prototype.getAll=function(e,t){var n=this,r=[];return new Promise((function(i){n.iterateCursor(e,(function(e){e?(r.push(e.value),void 0===t||r.length!=t?e.continue():i(r)):i(r)}))}))})})),e.openDb=function(e,t,n){var i=r(indexedDB,"open",[e,t]),s=i.request;return s&&(s.onupgradeneeded=function(e){n&&n(new f(s.result,e.oldVersion,s.transaction))}),i.then((function(e){return new p(e)}))},e.deleteDb=function(e){return r(indexedDB,"deleteDatabase",[e])},Object.defineProperty(e,"__esModule",{value:!0})}(t)}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},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.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e={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_,r=[];for(let t=0;t>2,l=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let n=0;for(let r=0;r>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],o=e[n++];t[r++]=String.fromCharCode((15&i)<<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_,r=[];for(let t=0;t>4;if(r.push(c),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==a){const e=o<<6&192|a;r.push(e)}}}return r},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 t{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 r(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function i(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(r())}function s(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function o(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function a(){const e=r();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}class c extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,c.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,u.prototype.create)}}class u{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],s=i?function(e,t){return e.replace(l,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",o=`${this.serviceName}: ${s} (${r}).`;return new c(r,o,n)}}const l=/\{\$([^}]+)}/g;function h(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],s=t[i];if(d(n)&&d(s)){if(!h(n,s))return!1}else if(n!==s)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function d(e){return null!==e&&"object"==typeof e}function f(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function p(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),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 g{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(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 r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const 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===r.next&&(r.next=y),void 0===r.error&&(r.error=y),void 0===r.complete&&(r.complete=y);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=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 y(){}function v(e,t=1e3,n=2){const r=t*Math.pow(n,e),i=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(144e5,r+i)}function w(e){return e&&e._delegate?e._delegate:e}class T{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 I="[DEFAULT]";class E{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 n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){const e=new t;if(this.instancesDeferred.set(n,e),this.isInitialized(n)||this.shouldAutoInitialize())try{const t=this.getOrInitializeService({instanceIdentifier:n});t&&e.resolve(t)}catch(e){}}return this.instancesDeferred.get(n).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:I})}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="[DEFAULT]"){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="[DEFAULT]"){return this.instances.has(e)}getOptions(e="[DEFAULT]"){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 r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(r);return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===I?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e="[DEFAULT]"){return this.component?this.component.multipleInstances?e:I:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class b{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 E(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const _=[];var S,k;(k=S||(S={}))[k.DEBUG=0]="DEBUG",k[k.VERBOSE=1]="VERBOSE",k[k.INFO=2]="INFO",k[k.WARN=3]="WARN",k[k.ERROR=4]="ERROR",k[k.SILENT=5]="SILENT";const A={debug:S.DEBUG,verbose:S.VERBOSE,info:S.INFO,warn:S.WARN,error:S.ERROR,silent:S.SILENT},C=S.INFO,N={[S.DEBUG]:"log",[S.VERBOSE]:"log",[S.INFO]:"info",[S.WARN]:"warn",[S.ERROR]:"error"},R=(e,t,...n)=>{if(t{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 O="@firebase/app",P="0.7.11",M=new D("@firebase/app"),x={[O]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},U=new Map,F=new Map;function V(e,t){try{e.container.addComponent(t)}catch(n){M.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function j(e){const t=e.name;if(F.has(t))return M.debug(`There were multiple attempts to register component ${t}.`),!1;F.set(t,e);for(const t of U.values())V(t,e);return!0}function q(e,t){return e.container.getProvider(t)}const B=new u("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","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."});class ${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 T("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw B.create("app-deleted",{appName:this._name})}}const H="9.6.1";function K(e="[DEFAULT]"){const t=U.get(e);if(!t)throw B.create("no-app",{appName:e});return t}function z(e,t,n){var r;let i=null!==(r=x[e])&&void 0!==r?r:e;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${t}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void M.warn(e.join(" "))}j(new T(`${i}-version`,(()=>({library:i,version:t})),"VERSION"))}j(new T("platform-logger",(e=>new L(e)),"PRIVATE")),z(O,P,""),z(O,P,"esm2017"),z("fire-js",""),z("firebase","9.6.1","app");var G=n(676);const W="@firebase/installations",J="0.5.4",X="w:0.5.4",Q=new u("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Y(e){return e instanceof c&&e.code.includes("request-failed")}function Z({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function ee(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function te(e,t){const n=(await t.json()).error;return Q.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function ne({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}async function re(e){const t=await e();return t.status>=500&&t.status<600?e():t}function ie(e){return new Promise((t=>{setTimeout(t,e)}))}const se=/^[cdef][\w-]{21}$/;function oe(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){return(t=e,btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var t}(e);return se.test(t)?t:""}catch(e){return""}}function ae(e){return`${e.appName}!${e.appId}`}const ce=new Map;function ue(e,t){const n=ae(e);le(n,t),function(e,t){const n=(!he&&"BroadcastChannel"in self&&(he=new BroadcastChannel("[Firebase] FID Change"),he.onmessage=e=>{le(e.data.key,e.data.fid)}),he);n&&n.postMessage({key:e,fid:t}),0===ce.size&&he&&(he.close(),he=null)}(n,t)}function le(e,t){const n=ce.get(e);if(n)for(const e of n)e(t)}let he=null;const de="firebase-installations-store";let fe=null;function pe(){return fe||(fe=(0,G.openDb)("firebase-installations-database",1,(e=>{0===e.oldVersion&&e.createObjectStore(de)}))),fe}async function me(e,t){const n=ae(e),r=(await pe()).transaction(de,"readwrite"),i=r.objectStore(de),s=await i.get(n);return await i.put(t,n),await r.complete,s&&s.fid===t.fid||ue(e,t.fid),t}async function ge(e){const t=ae(e),n=(await pe()).transaction(de,"readwrite");await n.objectStore(de).delete(t),await n.complete}async function ye(e,t){const n=ae(e),r=(await pe()).transaction(de,"readwrite"),i=r.objectStore(de),s=await i.get(n),o=t(s);return void 0===o?await i.delete(n):await i.put(o,n),await r.complete,!o||s&&s.fid===o.fid||ue(e,o.fid),o}async function ve(e){let t;const n=await ye(e,(n=>{const r=function(e){return Ie(e||{fid:oe(),registrationStatus:0})}(n),i=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine)return{installationEntry:t,registrationPromise:Promise.reject(Q.create("app-offline"))};const n={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},r=async function(e,t){try{const n=await async function(e,{fid:t}){const n=Z(e),r=ne(e),i={fid:t,authVersion:"FIS_v2",appId:e.appId,sdkVersion:X},s={method:"POST",headers:r,body:JSON.stringify(i)},o=await re((()=>fetch(n,s)));if(o.ok){const e=await o.json();return{fid:e.fid||t,registrationStatus:2,refreshToken:e.refreshToken,authToken:ee(e.authToken)}}throw await te("Create Installation",o)}(e,t);return me(e,n)}catch(n){throw Y(n)&&409===n.customData.serverCode?await ge(e):await me(e,{fid:t.fid,registrationStatus:0}),n}}(e,n);return{installationEntry:n,registrationPromise:r}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:we(e)}:{installationEntry:t}}(e,r);return t=i.registrationPromise,i.installationEntry}));return""===n.fid?{installationEntry:await t}:{installationEntry:n,registrationPromise:t}}async function we(e){let t=await Te(e);for(;1===t.registrationStatus;)await ie(100),t=await Te(e);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:n}=await ve(e);return n||t}return t}function Te(e){return ye(e,(e=>{if(!e)throw Q.create("installation-not-found");return Ie(e)}))}function Ie(e){return 1===(t=e).registrationStatus&&t.registrationTime+1e4fetch(r,a)));if(c.ok)return ee(await c.json());throw await te("Generate Auth Token",c)}async function be(e,t=!1){let n;const r=await ye(e.appConfig,(r=>{if(!Se(r))throw Q.create("not-registered");const i=r.authToken;if(!t&&(2===(s=i).requestStatus&&!function(e){const t=Date.now();return t{if(!Se(e))throw Q.create("not-registered");return 1===(t=e.authToken).requestStatus&&t.requestTime+1e4{const t=e.getProvider("app").getImmediate(),n=function(e){if(!e||!e.options)throw ke("App Configuration");if(!e.name)throw ke("App Name");const t=["projectId","apiKey","appId"];for(const n of t)if(!e.options[n])throw ke(n);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:n,platformLoggerProvider:q(t,"platform-logger"),_delete:()=>Promise.resolve()}}),"PUBLIC")),j(new T("installations-internal",(e=>{const t=q(e.getProvider("app").getImmediate(),Ae).getImmediate();return{getId:()=>async function(e){const t=e,{installationEntry:n,registrationPromise:r}=await ve(t.appConfig);return r?r.catch(console.error):be(t).catch(console.error),n.fid}(t),getToken:e=>async function(e,t=!1){const n=e;return await async function(e){const{registrationPromise:t}=await ve(e);t&&await t}(n.appConfig),(await be(n,t)).token}(t,e)}}),"PRIVATE")),z(W,J),z(W,J,"esm2017");const Ce="analytics",Ne="https://www.googletagmanager.com/gtag/js",Re=new D("@firebase/analytics");function De(e){return Promise.all(e.map((e=>e.catch((e=>e)))))}const Le=new u("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Oe=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};function Pe(e){return new Headers({Accept:"application/json","x-goog-api-key":e})}async function Me(e,t=Oe,n){const{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Le.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Le.create("no-api-key")}const o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()},a=new Ue;return setTimeout((async()=>{a.abort()}),void 0!==n?n:6e4),xe({appId:r,apiKey:i,measurementId:s},o,a,t)}async function xe(e,{throttleEndTimeMillis:t,backoffCount:n},r,i=Oe){const{appId:s,measurementId:o}=e;try{await function(e,t){return new Promise(((n,r)=>{const i=Math.max(t-Date.now(),0),s=setTimeout(n,i);e.addEventListener((()=>{clearTimeout(s),r(Le.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(r,t)}catch(e){if(o)return Re.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:s,measurementId:o};throw e}try{const t=await async function(e){var t;const{appId:n,apiKey:r}=e,i={method:"GET",headers:Pe(r)},s="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(s,i);if(200!==o.status&&304!==o.status){let e="";try{const n=await o.json();(null===(t=n.error)||void 0===t?void 0:t.message)&&(e=n.error.message)}catch(e){}throw Le.create("config-fetch-failed",{httpStatus:o.status,responseMessage:e})}return o.json()}(e);return i.deleteThrottleMetadata(s),t}catch(t){if(!function(e){if(!(e instanceof c&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t)){if(i.deleteThrottleMetadata(s),o)return Re.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${t.message}]`),{appId:s,measurementId:o};throw t}const a=503===Number(t.customData.httpStatus)?v(n,i.intervalMillis,30):v(n,i.intervalMillis),u={throttleEndTimeMillis:Date.now()+a,backoffCount:n+1};return i.setThrottleMetadata(s,u),Re.debug(`Calling attemptFetch again in ${a} millis`),xe(e,u,r,i)}}class Ue{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}async function Fe(e,t,n,r,i,s,o){var a;const c=Me(e);c.then((t=>{n[t.measurementId]=t.appId,e.options.measurementId&&t.measurementId!==e.options.measurementId&&Re.warn(`The measurement ID in the local Firebase config (${e.options.measurementId}) does not match the measurement ID fetched from the server (${t.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((e=>Re.error(e))),t.push(c);const u=async function(){if("object"!=typeof indexedDB)return Re.warn(Le.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}catch(e){return Re.warn(Le.create("indexeddb-unavailable",{errorInfo:e}).message),!1}return!0}().then((e=>e?r.getId():void 0)),[l,h]=await Promise.all([c,u]);(function(){const e=window.document.getElementsByTagName("script");for(const t of Object.values(e))if(t.src&&t.src.includes(Ne))return t;return null})()||function(e,t){const n=document.createElement("script");n.src=`${Ne}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const d=null!==(a=null==o?void 0:o.config)&&void 0!==a?a:{};return d.origin="firebase",d.update=!0,null!=h&&(d.firebase_id=h),i("config",l.measurementId,d),l.measurementId}class Ve{constructor(e){this.app=e}_delete(){return delete je[this.app.options.appId],Promise.resolve()}}let je={},qe=[];const Be={};let $e,He,Ke="dataLayer",ze=!1;function Ge(e,t,n){!function(){const e=[];if(s()&&e.push("This is a browser extension environment."),"undefined"!=typeof navigator&&navigator.cookieEnabled||e.push("Cookies are not available."),e.length>0){const t=e.map(((e,t)=>`(${t+1}) ${e}`)).join(" "),n=Le.create("invalid-analytics-context",{errorInfo:t});Re.warn(n.message)}}();const r=e.options.appId;if(!r)throw Le.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Le.create("no-api-key");Re.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=je[r])throw Le.create("already-exists",{id:r});if(!ze){!function(e){let t=[];Array.isArray(window.dataLayer)?t=window.dataLayer:window.dataLayer=t}();const{wrappedGtag:e,gtagCore:t}=function(e,t,n,r,i){let s=function(...e){window.dataLayer.push(arguments)};return window.gtag&&"function"==typeof window.gtag&&(s=window.gtag),window.gtag=function(e,t,n,r){return async function(i,s,o){try{"event"===i?await async function(e,t,n,r,i){try{let s=[];if(i&&i.send_to){let e=i.send_to;Array.isArray(e)||(e=[e]);const r=await De(n);for(const n of e){const e=r.find((e=>e.measurementId===n)),i=e&&t[e.appId];if(!i){s=[];break}s.push(i)}}0===s.length&&(s=Object.values(t)),await Promise.all(s),e("event",r,i||{})}catch(e){Re.error(e)}}(e,t,n,s,o):"config"===i?await async function(e,t,n,r,i,s){const o=r[i];try{if(o)await t[o];else{const e=(await De(n)).find((e=>e.measurementId===i));e&&await t[e.appId]}}catch(e){Re.error(e)}e("config",i,s)}(e,t,n,r,s,o):e("set",s)}catch(e){Re.error(e)}}}(s,e,t,n),{gtagCore:s,wrappedGtag:window.gtag}}(je,qe,Be);He=e,$e=t,ze=!0}return je[r]=Fe(e,qe,Be,t,$e,Ke,n),new Ve(e)}const We="@firebase/analytics",Je="0.7.4";j(new T(Ce,((e,{options:t})=>Ge(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)),"PUBLIC")),j(new T("analytics-internal",(function(e){try{const t=e.getProvider(Ce).getImmediate();return{logEvent:(e,n,r)=>function(e,t,n,r){e=w(e),async function(e,t,n,r,i){if(i&&i.global)e("event",n,r);else{const i=await t;e("event",n,Object.assign(Object.assign({},r),{send_to:i}))}}(He,je[e.app.options.appId],t,n,r).catch((e=>Re.error(e)))}(t,e,n,r)}}catch(e){throw Le.create("interop-component-reg-failed",{reason:e})}}),"PRIVATE")),z(We,Je),z(We,Je,"esm2017");const Xe=function(e,t={}){"object"!=typeof t&&(t={name:t});const n=Object.assign({name:"[DEFAULT]",automaticDataCollectionEnabled:!1},t),r=n.name;if("string"!=typeof r||!r)throw B.create("bad-app-name",{appName:String(r)});const i=U.get(r);if(i){if(h(e,i.options)&&h(n,i.config))return i;throw B.create("duplicate-app",{appName:r})}const s=new b(r);for(const e of F.values())s.addComponent(e);const o=new $(e,n,s);return U.set(r,o),o}({apiKey:"AIzaSyCtAdfUZ8tR-mODZgkDRe6ZACdDdsA36kU",authDomain:"type-master-ecd50.firebaseapp.com",projectId:"type-master-ecd50",storageBucket:"type-master-ecd50.appspot.com",messagingSenderId:"310756367551",appId:"1:310756367551:web:9823810463c7c3e8e63a0a",measurementId:"MISSING_ENV_VAR".FIREBASE_MEADUREMENT_ID});function Qe(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);ie,"Short delay should be less than long delay!"),this.isMobile=i()||o()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===ht()||"https:"===ht()||s()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function ft(e,t){at(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class pt{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:void ot("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:void ot("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:void ot("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const mt={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error"},gt=new dt(3e4,6e4);function yt(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function vt(e,t,n,r,i={}){return wt(e,i,(async()=>{let i={},s={};r&&("GET"===t?s=r:i={body:JSON.stringify(r)});const o=f(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),pt.fetch()(It(e,e.config.apiHost,n,o),Object.assign({method:t,headers:a,referrerPolicy:"no-referrer"},i))}))}async function wt(e,t,n){e._canInitEmulator=!1;const r=Object.assign(Object.assign({},mt),t);try{const t=new Et(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw bt(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[n,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw bt(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===n)throw bt(e,"email-already-in-use",s);const a=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw function(e,t,n){const r=Object.assign(Object.assign({},Ye()),{[t]:n});return new u("auth","Firebase",r).create(t,{appName:e.name})}(e,a,o);nt(e,a)}}catch(t){if(t instanceof c)throw t;nt(e,"network-request-failed")}}async function Tt(e,t,n,r,i={}){const s=await vt(e,t,n,r,i);return"mfaPendingCredential"in s&&nt(e,"multi-factor-auth-required",{_serverResponse:s}),s}function It(e,t,n,r){const i=`${t}${n}?${r}`;return e.config.emulator?ft(e.config,i):`${e.config.apiScheme}://${i}`}class Et{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(rt(this.auth,"timeout"))),gt.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function bt(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=rt(e,t,r);return i.customData._tokenResponse=n,i}function _t(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function St(e){return 1e3*Number(e)}function kt(t){const[n,r,i]=t.split(".");if(void 0===n||void 0===r||void 0===i)return tt("JWT malformed, contained fewer than 3 sections"),null;try{const t=function(t){try{return e.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(r);return t?JSON.parse(t):(tt("Failed to decode base64 JWT payload"),null)}catch(e){return tt("Caught error parsing JWT payload as JSON",e),null}}async function At(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof c&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class Ct{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"===e.code&&this.schedule(!0))}this.schedule()}}class Nt{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=_t(this.lastLoginAt),this.creationTime=_t(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Rt(e){var t;const n=e.auth,r=await e.getIdToken(),i=await At(e,async function(e,t){return vt(e,"POST","/v1/accounts:lookup",t)}(n,{idToken:r}));st(null==i?void 0:i.users.length,n,"internal-error");const s=i.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?s.providerUserInfo.map((e=>{var{providerId:t}=e,n=Qe(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[],a=(c=e.providerData,u=o,[...c.filter((e=>!u.some((t=>t.providerId===e.providerId)))),...u]);var c,u;const l=e.isAnonymous,h=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!l&&h,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new Nt(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,f)}class Dt{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){st(e.idToken,"internal-error"),st(void 0!==e.idToken,"internal-error"),st(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):function(e){const t=kt(e);return st(t,"internal-error"),st(void 0!==t.exp,"internal-error"),st(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e,t=!1){return st(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=await async function(e,t){const n=await wt(e,{},(async()=>{const n=f({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:i}=e.config,s=It(e,r,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",pt.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,r,Number(i))}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:r,expirationTime:i}=t,s=new Dt;return n&&(st("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(st("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(st("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new Dt,this.toJSON())}_performRefresh(){return ot("not implemented")}}function Lt(e,t){st("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Ot{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=Qe(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.emailVerified=!1,this.isAnonymous=!1,this.tenantId=null,this.providerData=[],this.proactiveRefresh=new Ct(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.metadata=new Nt(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){const t=await At(this,this.stsTokenManager.getToken(this.auth,e));return st(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=w(e),r=await n.getIdToken(t),i=kt(r);st(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s="object"==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:_t(St(i.auth_time)),issuedAtTime:_t(St(i.iat)),expirationTime:_t(St(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=w(e);await Rt(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(st(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){return new Ot(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){st(!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 Rt(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await At(this,async function(e,t){return vt(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,r,i,s,o,a,c,u;const l=null!==(n=t.displayName)&&void 0!==n?n:void 0,h=null!==(r=t.email)&&void 0!==r?r:void 0,d=null!==(i=t.phoneNumber)&&void 0!==i?i:void 0,f=null!==(s=t.photoURL)&&void 0!==s?s:void 0,p=null!==(o=t.tenantId)&&void 0!==o?o:void 0,m=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=t.createdAt)&&void 0!==c?c:void 0,y=null!==(u=t.lastLoginAt)&&void 0!==u?u:void 0,{uid:v,emailVerified:w,isAnonymous:T,providerData:I,stsTokenManager:E}=t;st(v&&E,e,"internal-error");const b=Dt.fromJSON(this.name,E);st("string"==typeof v,e,"internal-error"),Lt(l,e.name),Lt(h,e.name),st("boolean"==typeof w,e,"internal-error"),st("boolean"==typeof T,e,"internal-error"),Lt(d,e.name),Lt(f,e.name),Lt(p,e.name),Lt(m,e.name),Lt(g,e.name),Lt(y,e.name);const _=new Ot({uid:v,auth:e,email:h,emailVerified:w,displayName:l,isAnonymous:T,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:b,createdAt:g,lastLoginAt:y});return I&&Array.isArray(I)&&(_.providerData=I.map((e=>Object.assign({},e)))),m&&(_._redirectEventId=m),_}static async _fromIdTokenResponse(e,t,n=!1){const r=new Dt;r.updateFromServerResponse(t);const i=new Ot({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Rt(i),i}}class Pt{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){}}Pt.type="NONE";const Mt=Pt;function xt(e,t,n){return`firebase:${e}:${t}:${n}`}class Ut{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=xt(this.userKey,r.apiKey,i),this.fullPersistenceKey=xt("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?Ot._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 Ut(ut(Mt),e,n);const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=r[0]||ut(Mt);const s=xt(n,e.config.apiKey,e.name);let o=null;for(const n of t)try{const t=await n._get(s);if(t){const r=Ot._fromJSON(e,t);n!==i&&(o=r),i=n;break}}catch(e){}const a=r.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new Ut(i,e,n)):new Ut(i,e,n)}}function Ft(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Bt(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Vt(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(Ht(t))return"Blackberry";if(Kt(t))return"Webos";if(jt(t))return"Safari";if((t.includes("chrome/")||qt(t))&&!t.includes("edge/"))return"Chrome";if($t(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 Vt(e=r()){return/firefox\//i.test(e)}function jt(e=r()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function qt(e=r()){return/crios\//i.test(e)}function Bt(e=r()){return/iemobile/i.test(e)}function $t(e=r()){return/android/i.test(e)}function Ht(e=r()){return/blackberry/i.test(e)}function Kt(e=r()){return/webos/i.test(e)}function zt(e=r()){return/iphone|ipad|ipod/i.test(e)}function Gt(e=r()){return zt(e)||$t(e)||Kt(e)||Ht(e)||/windows phone/i.test(e)||Bt(e)}function Wt(e,t=[]){let n;switch(e){case"Browser":n=Ft(r());break;case"Worker":n=`${Ft(r())}-${e}`;break;default:n=e}return`${n}/JsCore/9.6.1/${t.length?t.join(","):"FirebaseCore-web"}`}class Jt{constructor(e,t){this.app=e,this.config=t,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Qt(this),this.idTokenSubscription=new Qt(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=Ze,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=t.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=ut(t)),this._initializationPromise=this.queue((async()=>{var n,r;if(!this._deleted&&(this.persistenceManager=await Ut.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===(r=this.currentUser)||void 0===r?void 0:r.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):void 0}async initializeCurrentUser(e){var t;let n=await this.assertedPersistence.getCurrentUser();if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const r=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,i=null==n?void 0:n._redirectEventId,s=await this.tryRedirectSignIn(e);r&&r!==i||!(null==s?void 0:s.user)||(n=s.user)}return n?n._redirectEventId?(st(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)):this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Rt(e)}catch(e){if("auth/network-request-failed"!==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){const t=e?w(e):null;return t&&st(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){if(!this._deleted)return e&&st(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(e){return this.queue((async()=>{await this.assertedPersistence.setPersistence(ut(e))}))}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new u("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&ut(e)||this._popupRedirectResolver;st(t,this,"argument-error"),this.redirectPersistenceManager=await Ut.create(this,[ut(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,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return st(s,this,"internal-error"),s.then((()=>i(this.currentUser))),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&(this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh()),this.currentUser=e,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 st(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Wt(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};return this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId),e}}function Xt(e){return w(e)}class Qt{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){const n=new g(e,void 0);return n.subscribe.bind(n)}((e=>this.observer=e))}get next(){return st(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}class Yt{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return ot("not implemented")}_getIdTokenResponse(e){return ot("not implemented")}_linkToIdToken(e,t){return ot("not implemented")}_getReauthenticationResolver(e){return ot("not implemented")}}class Zt extends Yt{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new Zt(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Zt(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 async function(e,t){return Tt(e,"POST","/v1/accounts:signInWithPassword",yt(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Tt(e,"POST","/v1/accounts:signInWithEmailLink",yt(e,t))}(e,{email:this._email,oobCode:this._password});default:nt(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return async function(e,t){return vt(e,"POST","/v1/accounts:update",t)}(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Tt(e,"POST","/v1/accounts:signInWithEmailLink",yt(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:nt(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function en(e,t){return Tt(e,"POST","/v1/accounts:signInWithIdp",yt(e,t))}class tn extends Yt{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new tn(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):nt("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:r}=t,i=Qe(t,["providerId","signInMethod"]);if(!n||!r)return null;const s=new tn(n,r);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return en(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,en(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,en(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=f(t)}return e}}const nn={USER_NOT_FOUND:"user-not-found"};class rn extends Yt{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new rn({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new rn({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Tt(e,"POST","/v1/accounts:signInWithPhoneNumber",yt(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await Tt(e,"POST","/v1/accounts:signInWithPhoneNumber",yt(e,t));if(n.temporaryProof)throw bt(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Tt(e,"POST","/v1/accounts:signInWithPhoneNumber",yt(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),nn)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;return n||t||r||i?new rn({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class sn{constructor(e){var t,n,r,i,s,o;const a=p(m(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,u=null!==(n=a.oobCode)&&void 0!==n?n:null,l=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!==(r=a.mode)&&void 0!==r?r:null);st(c&&u&&l,"argument-error"),this.apiKey=c,this.operation=l,this.code=u,this.continueUrl=null!==(i=a.continueUrl)&&void 0!==i?i: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=p(m(e)).link,n=t?p(m(t)).deep_link_id:null,r=p(m(e)).deep_link_id;return(r?p(m(r)).link:null)||r||n||t||e}(e);try{return new sn(t)}catch(e){return null}}}class on{constructor(){this.providerId=on.PROVIDER_ID}static credential(e,t){return Zt._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=sn.parseLink(t);return st(n,"argument-error"),Zt._fromEmailAndCode(e,n.code,n.tenantId)}}on.PROVIDER_ID="password",on.EMAIL_PASSWORD_SIGN_IN_METHOD="password",on.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class an{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 cn extends an{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class un extends cn{constructor(){super("facebook.com")}static credential(e){return tn._fromParams({providerId:un.PROVIDER_ID,signInMethod:un.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return un.credentialFromTaggedObject(e)}static credentialFromError(e){return un.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return un.credential(e.oauthAccessToken)}catch(e){return null}}}un.FACEBOOK_SIGN_IN_METHOD="facebook.com",un.PROVIDER_ID="facebook.com";class ln extends cn{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return tn._fromParams({providerId:ln.PROVIDER_ID,signInMethod:ln.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return ln.credentialFromTaggedObject(e)}static credentialFromError(e){return ln.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return ln.credential(t,n)}catch(e){return null}}}ln.GOOGLE_SIGN_IN_METHOD="google.com",ln.PROVIDER_ID="google.com";class hn extends cn{constructor(){super("github.com")}static credential(e){return tn._fromParams({providerId:hn.PROVIDER_ID,signInMethod:hn.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return hn.credentialFromTaggedObject(e)}static credentialFromError(e){return hn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return hn.credential(e.oauthAccessToken)}catch(e){return null}}}hn.GITHUB_SIGN_IN_METHOD="github.com",hn.PROVIDER_ID="github.com";class dn extends cn{constructor(){super("twitter.com")}static credential(e,t){return tn._fromParams({providerId:dn.PROVIDER_ID,signInMethod:dn.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return dn.credentialFromTaggedObject(e)}static credentialFromError(e){return dn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return dn.credential(t,n)}catch(e){return null}}}dn.TWITTER_SIGN_IN_METHOD="twitter.com",dn.PROVIDER_ID="twitter.com";class fn{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){const i=await Ot._fromIdTokenResponse(e,n,r),s=pn(n);return new fn({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const r=pn(n);return new fn({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function pn(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class mn extends c{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,mn.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new mn(e,t,n,r)}}function gn(e,t,n,r){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw mn._fromErrorAndOperation(e,n,t,r);throw n}))}async function yn(e,t,n=!1){const r="signIn",i=await gn(e,r,t),s=await fn._fromIdTokenResponse(e,r,i);return n||await e._updateCurrentUser(s.user),s}async function vn(e,{displayName:t,photoURL:n}){if(void 0===t&&void 0===n)return;const r=w(e),i={idToken:await r.getIdToken(),displayName:t,photoUrl:n,returnSecureToken:!0},s=await At(r,async function(e,t){return vt(e,"POST","/v1/accounts:update",t)}(r.auth,i));r.displayName=s.displayName||null,r.photoURL=s.photoUrl||null;const o=r.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=r.displayName,o.photoURL=r.photoURL),await r._updateTokensIfNecessary(s)}new WeakMap;const wn="__sak";class Tn{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(wn,"1"),this.storage.removeItem(wn),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 In extends Tn{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=r();return jt(e)||zt(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Gt(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),r=this.localCache[t];n!==r&&e(t,r,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 r=this.storage.getItem(n);if(e.newValue!==r)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const r=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},i=this.storage.getItem(n);a()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,10):r()}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]}}In.type="LOCAL";const En=In;class bn extends Tn{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}bn.type="SESSION";const _n=bn;class Sn{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 Sn(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data,s=this.handlersMap[r];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const o=Array.from(s).map((async e=>e(t.origin,i))),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:r,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 kn(e="",t=10){let n="";for(let e=0;e{const c=kn("",20);r.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),o(t.data.response);break;default:clearTimeout(u),clearTimeout(i),a(new Error("invalid_response"))}}},this.handlers.add(s),r.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[r.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function Cn(){return window}function Nn(){return void 0!==Cn().WorkerGlobalScope&&"function"==typeof Cn().importScripts}const Rn="firebaseLocalStorageDb",Dn="firebaseLocalStorage",Ln="fbase_key";class On{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 Pn(e,t){return e.transaction([Dn],t?"readwrite":"readonly").objectStore(Dn)}function Mn(){const e=indexedDB.open(Rn,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(Dn,{keyPath:Ln})}catch(e){n(e)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(Dn)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(Rn);return new On(e).toPromise()}(),t(await Mn()))}))}))}async function xn(e,t,n){const r=Pn(e,!0).put({[Ln]:t,value:n});return new On(r).toPromise()}function Un(e,t){const n=Pn(e,!0).delete(t);return new On(n).toPromise()}class Fn{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 Mn()),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 Nn()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Sn._getInstance(Nn()?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 An(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){if(this.sender&&this.activeServiceWorker&&function(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Mn();return await xn(e,wn,"1"),await Un(e,wn),!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=>xn(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=Pn(e,!1).get(t),r=await new On(n).toPromise();return void 0===r?null:r.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>Un(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=Pn(e,!1).getAll();return new On(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));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()}}Fn.type="LOCAL";const Vn=Fn;function jn(e){return`__${e}${Math.floor(1e6*Math.random())}`}jn("rcb"),new dt(3e4,6e4);class qn{constructor(e){this.providerId=qn.PROVIDER_ID,this.auth=Xt(e)}verifyPhoneNumber(e,t){return async function(e,t,n){var r;const i=await n.verify();try{let s;if(st("string"==typeof i,e,"argument-error"),st("recaptcha"===n.type,e,"argument-error"),s="string"==typeof t?{phoneNumber:t}:t,"session"in s){const t=s.session;if("phoneNumber"in s){st("enroll"===t.type,e,"internal-error");const n=await function(e,t){return vt(e,"POST","/v2/accounts/mfaEnrollment:start",yt(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:i}});return n.phoneSessionInfo.sessionInfo}{st("signin"===t.type,e,"internal-error");const n=(null===(r=s.multiFactorHint)||void 0===r?void 0:r.uid)||s.multiFactorUid;st(n,e,"missing-multi-factor-info");const o=await function(e,t){return vt(e,"POST","/v2/accounts/mfaSignIn:start",yt(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:i}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return vt(e,"POST","/v1/accounts:sendVerificationCode",yt(e,t))}(e,{phoneNumber:s.phoneNumber,recaptchaToken:i});return t}}finally{n._reset()}}(this.auth,e,w(t))}static credential(e,t){return rn._fromVerification(e,t)}static credentialFromResult(e){const t=e;return qn.credentialFromTaggedObject(t)}static credentialFromError(e){return qn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?rn._fromTokenResponse(t,n):null}}qn.PROVIDER_ID="phone",qn.PHONE_SIGN_IN_METHOD="phone";class Bn extends Yt{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return en(e,this._buildIdpRequest())}_linkToIdToken(e,t){return en(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return en(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 $n(e){return yn(e.auth,new Bn(e),e.bypassAuthState)}function Hn(e){const{auth:t,user:n}=e;return st(n,t,"internal-error"),async function(e,t,n=!1){const{auth:r}=e,i="reauthenticate";try{const s=await At(e,gn(r,i,t,e),n);st(s.idToken,r,"internal-error");const o=kt(s.idToken);st(o,r,"internal-error");const{sub:a}=o;return st(e.uid===a,r,"user-mismatch"),fn._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&nt(r,"user-mismatch"),e}}(n,new Bn(e),e.bypassAuthState)}async function Kn(e){const{auth:t,user:n}=e;return st(n,t,"internal-error"),async function(e,t,n=!1){const r=await At(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return fn._forOperation(e,"link",r)}(n,new Bn(e),e.bypassAuthState)}class zn{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return $n;case"linkViaPopup":case"linkViaRedirect":return Kn;case"reauthViaPopup":case"reauthViaRedirect":return Hn;default:nt(this.auth,"internal-error")}}resolve(e){at(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){at(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 Gn=new dt(2e3,1e4);class Wn extends zn{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,Wn.currentPopupAction&&Wn.currentPopupAction.cancel(),Wn.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return st(e,this.auth,"internal-error"),e}async onExecution(){at(1===this.filter.length,"Popup operations only handle one event");const e=kn();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(rt(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(rt(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Wn.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(rt(this.auth,"popup-closed-by-user"))}),2e3):this.pollId=window.setTimeout(e,Gn.get())};e()}}Wn.currentPopupAction=null;const Jn=new Map;class Xn extends zn{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=Jn.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=function(e){return xt("pendingRedirect",e.config.apiKey,e.name)}(t),r=function(e){return ut(e._redirectPersistence)}(e);if(!await r._isAvailable())return!1;const i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth),n=t?await super.execute():null;e=()=>Promise.resolve(n)}catch(t){e=()=>Promise.reject(t)}Jn.set(this.auth._key(),e)}return this.bypassAuthState||Jn.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 Qn(e,t,n=!1){const r=Xt(e),i=function(e,t){return t?ut(t):(st(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}(r,t),s=new Xn(r,i,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,t)),o}class Yn{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 er(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!er(e)){const r=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(rt(this.auth,r))}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(Zn(e))}saveEventToCache(e){this.cachedEventUids.add(Zn(e)),this.lastProcessedEventTime=Date.now()}}function Zn(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function er({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}const tr=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,nr=/^https?/;function rr(e){const t=lt(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!nr.test(n))return!1;if(tr.test(e))return r===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}const ir=new dt(3e4,6e4);function sr(){const e=Cn().___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 r,i,s,o;function a(){sr(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{sr(),n(rt(e,"network-request-failed"))},timeout:ir.get()})}if(null===(i=null===(r=Cn().gapi)||void 0===r?void 0:r.iframes)||void 0===i?void 0:i.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=Cn().gapi)||void 0===s?void 0:s.load)){const t=jn("iframefcb");return Cn()[t]=()=>{gapi.load?a():n(rt(e,"network-request-failed"))},(o=`https://apis.google.com/js/api.js?onload=${t}`,new Promise(((e,t)=>{const n=document.createElement("script");n.setAttribute("src",o),n.onload=e,n.onerror=e=>{const n=rt("internal-error");n.customData=e,t(n)},n.type="text/javascript",n.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(n)}))).catch((e=>n(e)))}a()}})).catch((e=>{throw or=null,e}))}(e),or}const cr=new dt(5e3,15e3),ur={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},lr=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function hr(e){const t=e.config;st(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?ft(t,"emulator/auth/iframe"):`https://${e.config.authDomain}/__/auth/iframe`,r={apiKey:t.apiKey,appName:e.name,v:H},i=lr.get(e.config.apiHost);i&&(r.eid=i);const s=e._getFrameworks();return s.length&&(r.fw=s.join(",")),`${n}?${f(r).slice(1)}`}const dr={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class fr{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function pr(e,t,n,r,i,s){st(e.config.authDomain,e,"auth-domain-config-required"),st(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:H,eventId:i};if(t instanceof an){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(s||{}))o[e]=t}if(t instanceof cn){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];return`${function({config:e}){return e.emulator?ft(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${f(a).slice(1)}`}const mr="webStorageSupport",gr=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=_n,this._completeRedirectFn=Qn}async _openPopup(e,t,n,i){var s;return at(null===(s=this.eventManagers[e._key()])||void 0===s?void 0:s.manager,"_initialize() not called before _openPopup()"),function(e,t,n,i=500,s=600){const o=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-i)/2,0).toString();let c="";const u=Object.assign(Object.assign({},dr),{width:i.toString(),height:s.toString(),top:o,left:a}),l=r().toLowerCase();n&&(c=qt(l)?"_blank":n),Vt(l)&&(t=t||"http://localhost",u.scrollbars="yes");const h=Object.entries(u).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(function(e=r()){var t;return zt(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(l)&&"_self"!==c)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",c),new fr(null);const d=window.open(t||"",c,h);st(d,e,"popup-blocked");try{d.focus()}catch(e){}return new fr(d)}(e,pr(e,t,n,lt(),i),kn())}async _openRedirect(e,t,n,r){var i;return await this._originValidation(e),i=pr(e,t,n,lt(),r),Cn().location.href=i,new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(at(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 ar(e),n=Cn().gapi;return st(n,e,"internal-error"),t.open({where:document.body,url:hr(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:ur,dontclear:!0},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:!1});const i=rt(e,"network-request-failed"),s=Cn().setTimeout((()=>{r(i)}),cr.get());function o(){Cn().clearTimeout(s),n(t)}t.ping(o).then(o,(()=>{r(i)}))}))))}(e),n=new Yn(e);return t.register("authEvent",(t=>(st(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(mr,{type:mr},(n=>{var r;const i=null===(r=null==n?void 0:n[0])||void 0===r?void 0:r.webStorageSupport;void 0!==i&&t(!!i),nt(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 async function(e,t={}){return vt(e,"GET","/v1/projects",t)}(e);for(const e of t)try{if(rr(e))return}catch(e){}nt(e,"unauthorized-domain")}(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Gt()||jt()||zt()}};var yr,vr="@firebase/auth",wr="0.19.4";class Tr{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=>{var n;e((null===(n=t)||void 0===n?void 0:n.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(){st(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Ir(e=K()){const t=q(e,"auth");return t.isInitialized()?t.getImmediate():function(e,t){const n=q(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(h(n.getOptions(),null!=t?t:{}))return e;nt(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:gr,persistence:[Vn,En,_n]})}yr="Browser",j(new T("auth",((e,{options:t})=>{const n=e.getProvider("app").getImmediate(),{apiKey:r,authDomain:i}=n.options;return(e=>{st(r&&!r.includes(":"),"invalid-api-key",{appName:e.name}),st(!(null==i?void 0:i.includes(":")),"argument-error",{appName:e.name});const n={apiKey:r,authDomain:i,clientPlatform:yr,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Wt(yr)},s=new Jt(e,n);return function(e,t){const n=(null==t?void 0:t.persistence)||[],r=(Array.isArray(n)?n:[n]).map(ut);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(s,t),s})(n)}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),j(new T("auth-internal",(e=>(e=>new Tr(e))(Xt(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),z(vr,wr,void 0),z(vr,wr,"esm2017");var Er,br="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{},_r={},Sr=Sr||{},kr=br||self;function Ar(){}function Cr(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Nr(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Rr="closure_uid_"+(1e9*Math.random()>>>0),Dr=0;function Lr(e,t,n){return e.call.apply(e.bind,arguments)}function Or(e,t,n){if(!e)throw Error();if(2t?1:0}e:{var Wr=kr.navigator;if(Wr){var Jr=Wr.userAgent;if(Jr){Hr=Jr;break e}}Hr=""}function Xr(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function Qr(e){const t={};for(const n in e)t[n]=e[n];return t}var Yr="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Zr(e,t){let n,r;for(let t=1;tparseFloat(li)){ti=String(di);break e}}ti=li}var fi,pi={};function mi(){return e=pi,Object.prototype.hasOwnProperty.call(e,9)?e[9]:e[9]=function(){let e=0;const t=Kr(String(ti)).split("."),n=Kr("9").split("."),r=Math.max(t.length,n.length);for(let o=0;0==e&&o>>0);function Vi(e){return"function"==typeof e?e:(e[Fi]||(e[Fi]=function(t){return e.handleEvent(t)}),e[Fi])}function ji(){Ur.call(this),this.i=new Si(this),this.P=this,this.I=null}function qi(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t)t=new vi(t,e);else if(t instanceof vi)t.target=t.target||e;else{var i=t;Zr(t=new vi(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var o=t.g=n[s];i=Bi(o,r,!0,t)&&i}if(i=Bi(o=t.g=e,r,!0,t)&&i,i=Bi(o,r,!1,t)&&i,n)for(s=0;snew Gi),(e=>e.reset()));class Gi{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Wi(e){kr.setTimeout((()=>{throw e}),0)}function Ji(e,t){Ki||function(){var e=kr.Promise.resolve(void 0);Ki=function(){e.then(Yi)}}(),Xi||(Ki(),Xi=!0),Qi.add(e,t)}var Xi=!1,Qi=new class{constructor(){this.h=this.g=null}add(e,t){const n=zi.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Yi(){for(var e;e=Hi();){try{e.h.call(e.g)}catch(e){Wi(e)}var t=zi;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}Xi=!1}function Zi(e,t){ji.call(this),this.h=e||1,this.g=t||kr,this.j=Pr(this.kb,this),this.l=Date.now()}function es(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function ts(e,t,n){if("function"==typeof e)n&&(e=Pr(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Pr(e.handleEvent,e)}return 2147483647{e.g=null,e.i&&(e.i=!1,ns(e))}),e.j);const t=e.h;e.h=null,e.m.apply(null,t)}xr(Zi,ji),(Er=Zi.prototype).da=!1,Er.S=null,Er.kb=function(){if(this.da){var e=Date.now()-this.l;0r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;ot.length?Os:(t=t.substr(r,n),e.C=r+n,t))}function Vs(e){e.Y=Date.now()+e.P,js(e,e.P)}function js(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=vs(Pr(e.eb,e),t)}function qs(e){e.B&&(kr.clearTimeout(e.B),e.B=null)}function Bs(e){0==e.l.G||e.I||da(e.l,e)}function $s(e){qs(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,es(e.W),as(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Hs(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||bo(n.i,e)))if(n.I=e.N,!e.J&&bo(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3i[2]&&n.N&&0==n.A&&!n.v&&(n.v=vs(Pr(n.ab,n),6e3));if(1>=Eo(n.i)&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else pa(n,11)}else if((e.J||n.g==e)&&ha(n),!$r(t))for(i=n.Ca.g.parse(t),t=0;tl)&&(3!=l||oi||this.g&&(this.h.h||this.g.ga()||Jo(this.g)))){this.I||4!=l||7==t||ps(8==t||0>=h?3:2),qs(this);var n=this.g.ba();this.N=n;t:if(xs(this)){var r=Jo(this.g);e="";var i=r.length,s=4==Wo(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){$s(this),Bs(this);var o="";break t}this.h.i=new kr.TextDecoder}for(t=0;tt)throw Error("Bad port number "+t);e.m=t}else e.m=null}function to(e,t,n){t instanceof fo?(e.h=t,function(e,t){t&&!e.j&&(po(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(mo(this,t),yo(this,n,e))}),e)),e.j=t}(e.h,e.g)):(n||(t=so(t,lo)),e.h=new fo(t,e.g))}function no(e,t,n){e.h.set(t,n)}function ro(e){return no(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function io(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function so(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,oo),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function oo(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Xs.prototype.toString=function(){var e=[],t=this.j;t&&e.push(so(t,ao,!0),":");var n=this.i;return(n||"file"==t)&&(e.push("//"),(t=this.s)&&e.push(so(t,ao,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&e.push("/"),e.push(so(n,"/"==n.charAt(0)?uo:co,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",so(n,ho)),e.join("")};var ao=/[#\/\?@]/g,co=/[#\?:]/g,uo=/[#\?]/g,lo=/[#\?@]/g,ho=/#/g;function fo(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function po(e){e.g||(e.g=new zs,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n2*e.i&&Gs(e)))}function go(e,t){return po(e),t=vo(e,t),Ws(e.g.h,t)}function yo(e,t,n){mo(e,t),0=e.j}function Eo(e){return e.h?1:e.g?e.g.size:0}function bo(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function _o(e,t){e.g?e.g.add(t):e.h=t}function So(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function ko(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.D);return t}return Br(e.i)}function Ao(){}function Co(){this.g=new Ao}function No(e,t,n){const r=n||"";try{Ks(e,(function(e,n){let i=e;Nr(e)&&(i=$i(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function Ro(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function Do(e){this.l=e.$b||null,this.j=e.ib||!1}function Lo(e,t){ji.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=Oo,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}wo.prototype.cancel=function(){if(this.i=ko(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},Ao.prototype.stringify=function(e){return kr.JSON.stringify(e,void 0)},Ao.prototype.parse=function(e){return kr.JSON.parse(e,void 0)},xr(Do,Is),Do.prototype.g=function(){return new Lo(this.l,this.j)},Do.prototype.i=function(e){return function(){return e}}({}),xr(Lo,ji);var Oo=0;function Po(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function Mo(e){e.readyState=4,e.l=null,e.j=null,e.A=null,xo(e)}function xo(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(Er=Lo.prototype).open=function(e,t){if(this.readyState!=Oo)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,xo(this)},Er.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||kr).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},Er.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mo(this)),this.readyState=Oo},Er.Va=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,xo(this)),this.g&&(this.readyState=3,xo(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==kr.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;Po(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},Er.Sa=function(e){if(this.g){if(this.u&&e.value)this.response.push(e.value);else if(!this.u){var t=e.value?e.value:new Uint8Array(0);(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?Mo(this):xo(this),3==this.readyState&&Po(this)}},Er.Ua=function(e){this.g&&(this.response=this.responseText=e,Mo(this))},Er.Ta=function(e){this.g&&(this.response=e,Mo(this))},Er.ha=function(){this.g&&Mo(this)},Er.setRequestHeader=function(e,t){this.v.append(e,t)},Er.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},Er.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Lo.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var Uo=kr.JSON.parse;function Fo(e){ji.call(this),this.headers=new zs,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=Vo,this.K=this.L=!1}xr(Fo,ji);var Vo="",jo=/^https?$/i,qo=["POST","PUT"];function Bo(e){return"content-type"==e.toLowerCase()}function $o(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Ho(e),zo(e)}function Ho(e){e.D||(e.D=!0,qi(e,"complete"),qi(e,"error"))}function Ko(e){if(e.h&&void 0!==Sr&&(!e.C[1]||4!=Wo(e)||2!=e.ba()))if(e.v&&4==Wo(e))ts(e.Fa,0,e);else if(qi(e,"readystatechange"),4==Wo(e)){e.h=!1;try{const a=e.ba();e:switch(a){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===a){var i=String(e.H).match(Js)[1]||null;if(!i&&kr.self&&kr.self.location){var s=kr.self.location.protocol;i=s.substr(0,s.length-1)}r=!jo.test(i?i.toLowerCase():"")}n=r}if(n)qi(e,"complete"),qi(e,"success");else{e.m=6;try{var o=2n)t=Math.max(0,i[o].h-100),s=!1;else try{No(a,e,"req"+n+"_")}catch(e){r&&r(a)}}if(s){r=e.join("&");break e}}}return e=e.l.splice(0,n),t.D=e,r}function aa(e){e.g||e.u||(e.Y=1,Ji(e.Ga,e),e.A=0)}function ca(e){return!(e.g||e.u||3<=e.A||(e.Y++,e.u=vs(Pr(e.Ga,e),fa(e,e.A)),e.A++,0))}function ua(e){null!=e.B&&(kr.clearTimeout(e.B),e.B=null)}function la(e){e.g=new Ns(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=Qs(e.oa);no(t,"RID","rpc"),no(t,"SID",e.J),no(t,"CI",e.N?"0":"1"),no(t,"AID",e.U),sa(e,t),no(t,"TYPE","xmlhttp"),e.o&&e.s&&Xo(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=ro(Qs(t)),n.s=null,n.U=!0,Ms(n,e)}function ha(e){null!=e.v&&(kr.clearTimeout(e.v),e.v=null)}function da(e,t){var n=null;if(e.g==t){ha(e),ua(e),e.g=null;var r=2}else{if(!bo(e.i,t))return;n=t.D,So(e.i,t),r=1}if(e.I=t.N,0!=e.G)if(t.i)if(1==r){n=t.s?t.s.length:0,t=Date.now()-t.F;var i=e.C;qi(r=ds(),new ys(r,n,t,i)),ra(e)}else aa(e);else if(3==(i=t.o)||0==i&&0=e.i.j-(e.m?1:0)||(e.m?(e.l=t.D.concat(e.l),0):1==e.G||2==e.G||e.C>=(e.Xa?0:e.Ya)||(e.m=vs(Pr(e.Ha,e,t),fa(e,e.C)),e.C++,0)))}(e,t)||2==r&&ca(e)))switch(n&&0t?null:"string"==typeof e?e.charAt(t):e[t]}(i.T()),n=kr.FormData&&e instanceof kr.FormData,!(0<=Vr(qo,t))||r||n||i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach((function(e,t){this.g.setRequestHeader(t,e)}),this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Go(this),0=this.O)){var e=2*this.O;this.h.info("BP detection timer enabled: "+e),this.B=vs(Pr(this.bb,this),e)}},Er.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,gs(10),ea(this),la(this))},Er.ab=function(){null!=this.v&&(this.v=null,ea(this),ca(this),gs(19))},Er.jb=function(e){e?(this.h.info("Successfully pinged google.com"),gs(2)):(this.h.info("Failed to ping google.com"),gs(1))},(Er=va.prototype).xa=function(){},Er.wa=function(){},Er.va=function(){},Er.ua=function(){},Er.Oa=function(){},wa.prototype.g=function(e,t){return new Ta(e,t)},xr(Ta,ji),Ta.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),Ji(Pr(e.hb,e,t))),gs(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=ga(e,null,e.W),ra(e)},Ta.prototype.close=function(){Zo(this.g)},Ta.prototype.u=function(e){if("string"==typeof e){var t={};t.__data__=e,na(this.g,t)}else this.v?((t={}).__data__=$i(e),na(this.g,t)):na(this.g,e)},Ta.prototype.M=function(){this.g.j=null,delete this.j,Zo(this.g),delete this.g,Ta.Z.M.call(this)},xr(Ia,ks),xr(Ea,As),xr(ba,va),ba.prototype.xa=function(){qi(this.g,"a")},ba.prototype.wa=function(e){qi(this.g,new Ia(e))},ba.prototype.va=function(e){qi(this.g,new Ea(e))},ba.prototype.ua=function(){qi(this.g,"b")},wa.prototype.createWebChannel=wa.prototype.g,Ta.prototype.send=Ta.prototype.u,Ta.prototype.open=Ta.prototype.m,Ta.prototype.close=Ta.prototype.close,ws.NO_ERROR=0,ws.TIMEOUT=8,ws.HTTP_ERROR=6,Ts.COMPLETE="complete",bs.EventType=Ss,Ss.OPEN="a",Ss.CLOSE="b",Ss.ERROR="c",Ss.MESSAGE="d",ji.prototype.listen=ji.prototype.N,Fo.prototype.listenOnce=Fo.prototype.O,Fo.prototype.getLastError=Fo.prototype.La,Fo.prototype.getLastErrorCode=Fo.prototype.Da,Fo.prototype.getStatus=Fo.prototype.ba,Fo.prototype.getResponseJson=Fo.prototype.Qa,Fo.prototype.getResponseText=Fo.prototype.ga,Fo.prototype.send=Fo.prototype.ea;var _a=_r.createWebChannelTransport=function(){return new wa},Sa=_r.getStatEventTarget=function(){return ds()},ka=_r.ErrorCode=ws,Aa=_r.EventType=Ts,Ca=_r.Event=ls,Na=_r.Stat={rb:0,ub:1,vb:2,Ob:3,Tb:4,Qb:5,Rb:6,Pb:7,Nb:8,Sb:9,PROXY:10,NOPROXY:11,Lb:12,Hb:13,Ib:14,Gb:15,Jb:16,Kb:17,nb:18,mb:19,ob:20},Ra=_r.FetchXmlHttpFactory=Do,Da=_r.WebChannel=bs,La=_r.XhrIo=Fo;const Oa="@firebase/firestore";class Pa{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}Pa.UNAUTHENTICATED=new Pa(null),Pa.GOOGLE_CREDENTIALS=new Pa("google-credentials-uid"),Pa.FIRST_PARTY=new Pa("first-party-uid"),Pa.MOCK_USER=new Pa("mock-user");let Ma="9.6.1";const xa=new D("@firebase/firestore");function Ua(){return xa.logLevel}function Fa(e,...t){if(xa.logLevel<=S.DEBUG){const n=t.map(qa);xa.debug(`Firestore (${Ma}): ${e}`,...n)}}function Va(e,...t){if(xa.logLevel<=S.ERROR){const n=t.map(qa);xa.error(`Firestore (${Ma}): ${e}`,...n)}}function ja(e,...t){if(xa.logLevel<=S.WARN){const n=t.map(qa);xa.warn(`Firestore (${Ma}): ${e}`,...n)}}function qa(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}var t}function Ba(e="Unexpected state"){const t=`FIRESTORE (${Ma}) INTERNAL ASSERTION FAILED: `+e;throw Va(t),new Error(t)}function $a(e,t){e||Ba()}function Ha(e,t){return e}const Ka={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class za extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Ga{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class Wa{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Ja{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(Pa.UNAUTHENTICATED)))}shutdown(){}}class Xa{constructor(e){this.t=e,this.currentUser=Pa.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new Ga;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Ga,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{Fa("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),s()};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(Fa("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Ga)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(Fa("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?($a("string"==typeof t.accessToken),new Wa(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return $a(null===e||"string"==typeof e),new Pa(e)}}class Qa{constructor(e,t,n){this.type="FirstParty",this.user=Pa.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);const r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class Ya{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Qa(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable((()=>t(Pa.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class Za{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class ec{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null}start(e,t){this.o=n=>{e.enqueueRetryable((()=>(e=>(null!=e.error&&Fa("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`),t(e.token)))(n)))};const n=e=>{Fa("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit((e=>n(e))),setTimeout((()=>{if(!this.appCheck){const e=this.g.getImmediate({optional:!0});e?n(e):Fa("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?($a("string"==typeof e.token),new Za(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class tc{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.p(e),this.T=e=>t.writeSequenceNumber(e))}p(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.T&&this.T(e),e}}function nc(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;tt?1:0}function sc(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}class oc{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new za(Ka.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new za(Ka.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new za(Ka.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new za(Ka.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return oc.fromMillis(Date.now())}static fromDate(e){return oc.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new oc(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?ic(this.nanoseconds,e.nanoseconds):ic(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class ac{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ac(e)}static min(){return new ac(new oc(0,0))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function cc(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function uc(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function lc(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class hc{constructor(e,t,n){void 0===t?t=0:t>e.length&&Ba(),void 0===n?n=e.length-t:n>e.length-t&&Ba(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===hc.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof hc?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.lengthi)return 1}return e.lengtht.length?1:0}}class dc extends hc{construct(e,t,n){return new dc(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new za(Ka.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new dc(t)}static emptyPath(){return new dc([])}}const fc=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class pc extends hc{construct(e,t,n){return new pc(e,t,n)}static isValidIdentifier(e){return fc.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),pc.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new pc(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new za(Ka.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;re.isEqual(t)))}}class gc{constructor(e){this.binaryString=e}static fromBase64String(e){const t=atob(e);return new gc(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n=2&&this.path.get(this.path.length-2)===e}isEqual(e){return null!==e&&0===dc.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return dc.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new kc(new dc(e.slice()))}}function Ac(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?Ic(e)?4:10:Ba()}function Cc(e,t){const n=Ac(e);if(n!==Ac(t))return!1;switch(n){case 0:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return bc(e).isEqual(bc(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=vc(e.timestampValue),r=vc(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return Tc(e.bytesValue).isEqual(Tc(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return wc(e.geoPointValue.latitude)===wc(t.geoPointValue.latitude)&&wc(e.geoPointValue.longitude)===wc(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return wc(e.integerValue)===wc(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=wc(e.doubleValue),r=wc(t.doubleValue);return n===r?Sc(n)===Sc(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return sc(e.arrayValue.values||[],t.arrayValue.values||[],Cc);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(cc(n)!==cc(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Cc(n[e],r[e])))return!1;return!0}(e,t);default:return Ba()}}function Nc(e,t){return void 0!==(e.values||[]).find((e=>Cc(e,t)))}function Rc(e,t){const n=Ac(e),r=Ac(t);if(n!==r)return ic(n,r);switch(n){case 0:return 0;case 1:return ic(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=wc(e.integerValue||e.doubleValue),r=wc(t.integerValue||t.doubleValue);return nr?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return Dc(e.timestampValue,t.timestampValue);case 4:return Dc(bc(e),bc(t));case 5:return ic(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Tc(e),r=Tc(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let e=0;et.mapValue.fields[e]=Vc(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Vc(e.arrayValue.values[n]);return t}return Object.assign({},e)}class jc{constructor(e){this.value=e}static empty(){return new jc({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=Vc(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Fc(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Cc(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;ne[t]=n));for(const t of n)delete e[t]}clone(){return new jc(Vc(this.value))}}function qc(e){const t=[];return uc(e.fields,((e,n)=>{const r=new pc([e]);if(Fc(n)){const e=qc(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new mc(t)}class Bc{constructor(e,t,n,r,i){this.key=e,this.documentType=t,this.version=n,this.data=r,this.documentState=i}static newInvalidDocument(e){return new Bc(e,0,ac.min(),jc.empty(),0)}static newFoundDocument(e,t,n){return new Bc(e,1,t,n,0)}static newNoDocument(e,t){return new Bc(e,2,t,jc.empty(),0)}static newUnknownDocument(e,t){return new Bc(e,3,t,jc.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=jc.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=jc.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Bc&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}clone(){return new Bc(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class $c{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.R=null}}function Hc(e,t=null,n=[],r=[],i=null,s=null,o=null){return new $c(e,t,n,r,i,s,o)}function Kc(e){const t=Ha(e);if(null===t.R){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>function(e){return e.field.canonicalString()+e.op.toString()+Lc(e.value)}(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),_c(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=iu(t.startAt)),t.endAt&&(e+="|ub:",e+=iu(t.endAt)),t.R=e}return t.R}function zc(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n":return e>0;case">=":return e>=0;default:return Ba()}}V(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}}class Jc extends Wc{constructor(e,t,n){super(e,t,n),this.key=kc.fromName(n.referenceValue)}matches(e){const t=kc.comparator(e.key,this.key);return this.v(t)}}class Xc extends Wc{constructor(e,t){super(e,"in",t),this.keys=Yc(0,t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class Qc extends Wc{constructor(e,t){super(e,"not-in",t),this.keys=Yc(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function Yc(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>kc.fromName(e.referenceValue)))}class Zc extends Wc{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Mc(t)&&Nc(t.arrayValue,this.value)}}class eu extends Wc{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Nc(this.value.arrayValue,t)}}class tu extends Wc{constructor(e,t){super(e,"not-in",t)}matches(e){if(Nc(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Nc(this.value.arrayValue,t)}}class nu extends Wc{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Mc(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Nc(this.value.arrayValue,e)))}}class ru{constructor(e,t){this.position=e,this.before=t}}function iu(e){return`${e.before?"b":"a"}:${e.position.map((e=>Lc(e))).join(",")}`}class su{constructor(e,t="asc"){this.field=e,this.dir=t}}function ou(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}function au(e,t,n){let r=0;for(let i=0;i0?e.explicitOrderBy[0].field:null}function pu(e){for(const t of e.filters)if(t.V())return t.field;return null}function mu(e){const t=Ha(e);if(null===t.S){t.S=[];const e=pu(t),n=fu(t);if(null!==e&&null===n)e.isKeyField()||t.S.push(new su(e)),t.S.push(new su(pc.keyField(),"asc"));else{let e=!1;for(const n of t.explicitOrderBy)t.S.push(n),n.field.isKeyField()&&(e=!0);if(!e){const e=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.S.push(new su(pc.keyField(),e))}}}return t.S}function gu(e){const t=Ha(e);if(!t.D)if("F"===t.limitType)t.D=Hc(t.path,t.collectionGroup,mu(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const n of mu(t)){const t="desc"===n.dir?"asc":"desc";e.push(new su(n.field,t))}const n=t.endAt?new ru(t.endAt.position,!t.endAt.before):null,r=t.startAt?new ru(t.startAt.position,!t.startAt.before):null;t.D=Hc(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.D}function yu(e,t,n){return new uu(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function vu(e,t){return zc(gu(e),gu(t))&&e.limitType===t.limitType}function wu(e){return`${Kc(gu(e))}|lt:${e.limitType}`}function Tu(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>{return`${(t=e).field.canonicalString()} ${t.op} ${Lc(t.value)}`;var t})).join(", ")}]`),_c(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: "+iu(e.startAt)),e.endAt&&(t+=", endAt: "+iu(e.endAt)),`Target(${t})`}(gu(e))}; limitType=${e.limitType})`}function Iu(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):kc.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of e.explicitOrderBy)if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!au(e.startAt,mu(e),t)||e.endAt&&au(e.endAt,mu(e),t))}(e,t)}function Eu(e){return(t,n)=>{let r=!1;for(const i of mu(e)){const e=bu(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function bu(e,t,n){const r=e.field.isKeyField()?kc.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Rc(r,i):Ba()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Ba()}}function _u(e,t){if(e.C){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Sc(t)?"-0":t}}function Su(e){return{integerValue:""+e}}function ku(e,t){return function(e){return"number"==typeof e&&Number.isInteger(e)&&!Sc(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}(t)?Su(t):_u(e,t)}class Au{constructor(){this._=void 0}}function Cu(e,t,n){return e instanceof Du?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof Lu?Ou(e,t):e instanceof Pu?Mu(e,t):function(e,t){const n=Ru(e,t),r=Uu(n)+Uu(e.N);return Pc(n)&&Pc(e.N)?Su(r):_u(e.k,r)}(e,t)}function Nu(e,t,n){return e instanceof Lu?Ou(e,t):e instanceof Pu?Mu(e,t):n}function Ru(e,t){return e instanceof xu?Pc(n=t)||function(e){return!!e&&"doubleValue"in e}(n)?t:{integerValue:0}:null;var n}class Du extends Au{}class Lu extends Au{constructor(e){super(),this.elements=e}}function Ou(e,t){const n=Fu(t);for(const t of e.elements)n.some((e=>Cc(e,t)))||n.push(t);return{arrayValue:{values:n}}}class Pu extends Au{constructor(e){super(),this.elements=e}}function Mu(e,t){let n=Fu(t);for(const t of e.elements)n=n.filter((e=>!Cc(e,t)));return{arrayValue:{values:n}}}class xu extends Au{constructor(e,t){super(),this.k=e,this.N=t}}function Uu(e){return wc(e.integerValue||e.doubleValue)}function Fu(e){return Mc(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Vu{constructor(e,t){this.version=e,this.transformResults=t}}class ju{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new ju}static exists(e){return new ju(void 0,e)}static updateTime(e){return new ju(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function qu(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Bu{}function $u(e,t,n){e instanceof Wu?function(e,t,n){const r=e.value.clone(),i=Qu(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Ju?function(e,t,n){if(!qu(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=Qu(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Xu(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function Hu(e,t,n){e instanceof Wu?function(e,t,n){if(!qu(e.precondition,t))return;const r=e.value.clone(),i=Yu(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(Gu(t),r).setHasLocalMutations()}(e,t,n):e instanceof Ju?function(e,t,n){if(!qu(e.precondition,t))return;const r=Yu(e.fieldTransforms,n,t),i=t.data;i.setAll(Xu(e)),i.setAll(r),t.convertToFoundDocument(Gu(t),i).setHasLocalMutations()}(e,t,n):function(e,t){qu(e.precondition,t)&&t.convertToNoDocument(ac.min())}(e,t)}function Ku(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=Ru(r.transform,e||null);null!=i&&(null==n&&(n=jc.empty()),n.set(r.field,i))}return n||null}function zu(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&sc(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof Lu&&t instanceof Lu||e instanceof Pu&&t instanceof Pu?sc(e.elements,t.elements,Cc):e instanceof xu&&t instanceof xu?Cc(e.N,t.N):e instanceof Du&&t instanceof Du}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}function Gu(e){return e.isFoundDocument()?e.version:ac.min()}class Wu extends Bu{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Ju extends Bu{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}}function Xu(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function Qu(e,t,n){const r=new Map;$a(e.length===n.length);for(let i=0;i0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new ol(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ol(this.root,e,this.comparator,!1)}getReverseIterator(){return new ol(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ol(this.root,e,this.comparator,!0)}}class ol{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class al{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:al.RED,this.left=null!=r?r:al.EMPTY,this.right=null!=i?i:al.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new al(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return al.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return al.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,al.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,al.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Ba();if(this.right.isRed())throw Ba();const e=this.left.check();if(e!==this.right.check())throw Ba();return e+(this.isRed()?0:1)}}al.EMPTY=null,al.RED=!0,al.BLACK=!1,al.EMPTY=new class{constructor(){this.size=0}get key(){throw Ba()}get value(){throw Ba()}get color(){throw Ba()}get left(){throw Ba()}get right(){throw Ba()}copy(e,t,n,r,i){return this}insert(e,t,n){return new al(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class cl{constructor(e){this.comparator=e,this.data=new sl(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ul(this.data.getIterator())}getIteratorFrom(e){return new ul(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size{t=t.add(e)})),t}isEqual(e){if(!(e instanceof cl))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new cl(this.comparator);return t.data=e,t}}class ul{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const ll=new sl(kc.comparator);function hl(){return ll}const dl=new sl(kc.comparator);function fl(){return dl}const pl=new sl(kc.comparator);const ml=new cl(kc.comparator);function gl(...e){let t=ml;for(const n of e)t=t.add(n);return t}const yl=new cl(ic);function vl(){return yl}class wl{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,Tl.createSynthesizedTargetChangeForCurrentChange(e,t)),new wl(ac.min(),n,vl(),hl(),gl())}}class Tl{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t){return new Tl(gc.EMPTY_BYTE_STRING,t,gl(),gl(),gl())}}class Il{constructor(e,t,n,r){this.$=e,this.removedTargetIds=t,this.key=n,this.F=r}}class El{constructor(e,t){this.targetId=e,this.O=t}}class bl{constructor(e,t,n=gc.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class _l{constructor(){this.M=0,this.L=Al(),this.B=gc.EMPTY_BYTE_STRING,this.U=!1,this.q=!0}get current(){return this.U}get resumeToken(){return this.B}get K(){return 0!==this.M}get j(){return this.q}W(e){e.approximateByteSize()>0&&(this.q=!0,this.B=e)}G(){let e=gl(),t=gl(),n=gl();return this.L.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:Ba()}})),new Tl(this.B,this.U,e,t,n)}H(){this.q=!1,this.L=Al()}J(e,t){this.q=!0,this.L=this.L.insert(e,t)}Y(e){this.q=!0,this.L=this.L.remove(e)}X(){this.M+=1}Z(){this.M-=1}tt(){this.q=!0,this.U=!0}}class Sl{constructor(e){this.et=e,this.nt=new Map,this.st=hl(),this.it=kl(),this.rt=new cl(ic)}ot(e){for(const t of e.$)e.F&&e.F.isFoundDocument()?this.at(t,e.F):this.ct(t,e.key,e.F);for(const t of e.removedTargetIds)this.ct(t,e.key,e.F)}ut(e){this.forEachTarget(e,(t=>{const n=this.ht(t);switch(e.state){case 0:this.lt(t)&&n.W(e.resumeToken);break;case 1:n.Z(),n.K||n.H(),n.W(e.resumeToken);break;case 2:n.Z(),n.K||this.removeTarget(t);break;case 3:this.lt(t)&&(n.tt(),n.W(e.resumeToken));break;case 4:this.lt(t)&&(this.ft(t),n.W(e.resumeToken));break;default:Ba()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.nt.forEach(((e,n)=>{this.lt(n)&&t(n)}))}dt(e){const t=e.targetId,n=e.O.count,r=this.wt(t);if(r){const e=r.target;if(Gc(e))if(0===n){const n=new kc(e.path);this.ct(t,n,Bc.newNoDocument(n,ac.min()))}else $a(1===n);else this._t(t)!==n&&(this.ft(t),this.rt=this.rt.add(t))}}gt(e){const t=new Map;this.nt.forEach(((n,r)=>{const i=this.wt(r);if(i){if(n.current&&Gc(i.target)){const t=new kc(i.target.path);null!==this.st.get(t)||this.yt(r,t)||this.ct(r,t,Bc.newNoDocument(t,e))}n.j&&(t.set(r,n.G()),n.H())}}));let n=gl();this.it.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.wt(e);return!t||2===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))}));const r=new wl(e,t,this.rt,this.st,n);return this.st=hl(),this.it=kl(),this.rt=new cl(ic),r}at(e,t){if(!this.lt(e))return;const n=this.yt(e,t.key)?2:0;this.ht(e).J(t.key,n),this.st=this.st.insert(t.key,t),this.it=this.it.insert(t.key,this.Tt(t.key).add(e))}ct(e,t,n){if(!this.lt(e))return;const r=this.ht(e);this.yt(e,t)?r.J(t,1):r.Y(t),this.it=this.it.insert(t,this.Tt(t).delete(e)),n&&(this.st=this.st.insert(t,n))}removeTarget(e){this.nt.delete(e)}_t(e){const t=this.ht(e).G();return this.et.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}X(e){this.ht(e).X()}ht(e){let t=this.nt.get(e);return t||(t=new _l,this.nt.set(e,t)),t}Tt(e){let t=this.it.get(e);return t||(t=new cl(ic),this.it=this.it.insert(e,t)),t}lt(e){const t=null!==this.wt(e);return t||Fa("WatchChangeAggregator","Detected inactive target",e),t}wt(e){const t=this.nt.get(e);return t&&t.K?null:this.et.Et(e)}ft(e){this.nt.set(e,new _l),this.et.getRemoteKeysForTarget(e).forEach((t=>{this.ct(e,t,null)}))}yt(e,t){return this.et.getRemoteKeysForTarget(e).has(t)}}function kl(){return new sl(kc.comparator)}function Al(){return new sl(kc.comparator)}const Cl={asc:"ASCENDING",desc:"DESCENDING"},Nl={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class Rl{constructor(e,t){this.databaseId=e,this.C=t}}function Dl(e,t){return e.C?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Ll(e,t){return e.C?t.toBase64():t.toUint8Array()}function Ol(e,t){return Dl(e,t.toTimestamp())}function Pl(e){return $a(!!e),ac.fromTimestamp(function(e){const t=vc(e);return new oc(t.seconds,t.nanos)}(e))}function Ml(e,t){return function(e){return new dc(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function xl(e){const t=dc.fromString(e);return $a(nh(t)),t}function Ul(e,t){return Ml(e.databaseId,t.path)}function Fl(e,t){const n=xl(t);if(n.get(1)!==e.databaseId.projectId)throw new za(Ka.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new za(Ka.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new kc(ql(n))}function Vl(e,t){return Ml(e.databaseId,t)}function jl(e){return new dc(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function ql(e){return $a(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function Bl(e,t,n){return{name:Ul(e,t),fields:n.value.mapValue.fields}}function $l(e,t){return{documents:[Vl(e,t.path)]}}function Hl(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=Vl(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=Vl(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const i=function(e){if(0===e.length)return;const t=e.map((e=>function(e){if("=="===e.op){if(Uc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NAN"}};if(xc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Uc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NOT_NAN"}};if(xc(e.value))return{unaryFilter:{field:Ql(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Ql(e.field),op:Xl(e.op),value:e.value}}}(e)));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}(t.filters);i&&(n.structuredQuery.where=i);const s=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:Ql(e.field),direction:Jl(e.dir)}}(e)))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);const o=function(e,t){return e.C||_c(t)?t:{value:t}}(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt=Gl(t.startAt)),t.endAt&&(n.structuredQuery.endAt=Gl(t.endAt)),n}function Kl(e){let t=function(e){const t=xl(e);return 4===t.length?dc.emptyPath():ql(t)}(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){$a(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=zl(n.where));let o=[];n.orderBy&&(o=n.orderBy.map((e=>function(e){return new su(Yl(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e))));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,_c(t)?null:t}(n.limit));let c=null;n.startAt&&(c=Wl(n.startAt));let u=null;return n.endAt&&(u=Wl(n.endAt)),function(e,t,n,r,i,s,o,a){return new uu(e,t,n,r,i,s,o,a)}(t,i,o,s,a,"F",c,u)}function zl(e){return e?void 0!==e.unaryFilter?[eh(e)]:void 0!==e.fieldFilter?[Zl(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map((e=>zl(e))).reduce(((e,t)=>e.concat(t))):Ba():[]}function Gl(e){return{before:e.before,values:e.position}}function Wl(e){const t=!!e.before,n=e.values||[];return new ru(n,t)}function Jl(e){return Cl[e]}function Xl(e){return Nl[e]}function Ql(e){return{fieldPath:e.canonicalString()}}function Yl(e){return pc.fromServerFormat(e.fieldPath)}function Zl(e){return Wc.create(Yl(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return Ba()}}(e.fieldFilter.op),e.fieldFilter.value)}function eh(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Yl(e.unaryFilter.field);return Wc.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Yl(e.unaryFilter.field);return Wc.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Yl(e.unaryFilter.field);return Wc.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=Yl(e.unaryFilter.field);return Wc.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Ba()}}function th(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function nh(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function rh(e){let t="";for(let n=0;n0&&(t=sh(t)),t=ih(e.get(n),t);return sh(t)}function ih(e,t){let n=t;const r=e.length;for(let t=0;t{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&Ba(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new wh(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof wh?t:wh.resolve(t)}catch(e){return wh.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):wh.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):wh.reject(t)}static resolve(e){return new wh(((t,n)=>{t(e)}))}static reject(e){return new wh(((t,n)=>{n(e)}))}static waitFor(e){return new wh(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=wh.resolve(!1);for(const n of e)t=t.next((e=>e?wh.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}}function Th(e){return"IndexedDbTransactionError"===e.name}class Ih{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let t=0;t{const n=e.get(t.key),r=n;this.applyToLocalView(r),n.isValidDocument()||r.convertToNoDocument(ac.min())}))}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),gl())}isEqual(e){return this.batchId===e.batchId&&sc(this.mutations,e.mutations,((e,t)=>zu(e,t)))&&sc(this.baseMutations,e.baseMutations,((e,t)=>zu(e,t)))}}class Eh{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){$a(e.mutations.length===n.length);let r=pl;const i=e.mutations;for(let e=0;e{for(const[t,r]of n)e(t,r)}))}isEmpty(){return lc(this.inner)}}class Lh{constructor(e,t,n){this.Je=e,this.An=t,this.Jt=n}Rn(e,t){return this.An.getAllMutationBatchesAffectingDocumentKey(e,t).next((n=>this.Pn(e,t,n)))}Pn(e,t,n){return this.Je.getEntry(e,t).next((e=>{for(const t of n)t.applyToLocalView(e);return e}))}bn(e,t){e.forEach(((e,n)=>{for(const e of t)e.applyToLocalView(n)}))}vn(e,t){return this.Je.getEntries(e,t).next((t=>this.Vn(e,t).next((()=>t))))}Vn(e,t){return this.An.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>this.bn(t,e)))}getDocumentsMatchingQuery(e,t,n){return function(e){return kc.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.Sn(e,t.path):function(e){return null!==e.collectionGroup}(t)?this.Dn(e,t,n):this.Cn(e,t,n)}Sn(e,t){return this.Rn(e,new kc(t)).next((e=>{let t=fl();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}Dn(e,t,n){const r=t.collectionGroup;let i=fl();return this.Jt.getCollectionParents(e,r).next((s=>wh.forEach(s,(s=>{const o=function(e,t){return new uu(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,s.child(r));return this.Cn(e,o,n).next((e=>{e.forEach(((e,t)=>{i=i.insert(e,t)}))}))})).next((()=>i))))}Cn(e,t,n){let r,i;return this.Je.getDocumentsMatchingQuery(e,t,n).next((n=>(r=n,this.An.getAllMutationBatchesAffectingQuery(e,t)))).next((t=>(i=t,this.Nn(e,i,r).next((e=>{r=e;for(const e of i)for(const t of e.mutations){const n=t.key;let i=r.get(n);null==i&&(i=Bc.newInvalidDocument(n),r=r.insert(n,i)),Hu(t,i,e.localWriteTime),i.isFoundDocument()||(r=r.remove(n))}}))))).next((()=>(r.forEach(((e,n)=>{Iu(t,n)||(r=r.remove(e))})),r)))}Nn(e,t,n){let r=gl();for(const e of t)for(const t of e.mutations)t instanceof Ju&&null===n.get(t.key)&&(r=r.add(t.key));let i=n;return this.Je.getEntries(e,r).next((e=>(e.forEach(((e,t)=>{t.isFoundDocument()&&(i=i.insert(e,t))})),i)))}}class Oh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.kn=n,this.xn=r}static $n(e,t){let n=gl(),r=gl();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new Oh(e,t.fromCache,n,r)}}class Ph{Fn(e){this.On=e}getDocumentsMatchingQuery(e,t,n,r){return function(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}(t)||n.isEqual(ac.min())?this.Mn(e,t):this.On.vn(e,r).next((i=>{const s=this.Ln(t,i);return(hu(t)||du(t))&&this.Bn(t.limitType,s,r,n)?this.Mn(e,t):(Ua()<=S.DEBUG&&Fa("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),Tu(t)),this.On.getDocumentsMatchingQuery(e,t,n).next((e=>(s.forEach((t=>{e=e.insert(t.key,t)})),e))))}))}Ln(e,t){let n=new cl(Eu(e));return t.forEach(((t,r)=>{Iu(e,r)&&(n=n.add(r))})),n}Bn(e,t,n,r){if(n.size!==t.size)return!0;const i="F"===e?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}Mn(e,t){return Ua()<=S.DEBUG&&Fa("QueryEngine","Using full collection scan to execute query:",Tu(t)),this.On.getDocumentsMatchingQuery(e,t,ac.min())}}class Mh{constructor(e,t,n,r){this.persistence=e,this.Un=t,this.k=r,this.qn=new sl(ic),this.Kn=new Dh((e=>Kc(e)),zc),this.jn=ac.min(),this.An=e.getMutationQueue(n),this.Qn=e.getRemoteDocumentCache(),this.He=e.getTargetCache(),this.Wn=new Lh(this.Qn,this.An,this.persistence.getIndexManager()),this.Ye=e.getBundleCache(),this.Un.Fn(this.Wn)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.qn)))}}async function xh(e,t){const n=Ha(e);let r=n.An,i=n.Wn;const s=await n.persistence.runTransaction("Handle user change","readonly",(e=>{let s;return n.An.getAllMutationBatches(e).next((o=>(s=o,r=n.persistence.getMutationQueue(t),i=new Lh(n.Qn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(e)))).next((t=>{const n=[],r=[];let o=gl();for(const e of s){n.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){r.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return i.vn(e,o).next((e=>({Gn:e,removedBatchIds:n,addedBatchIds:r})))}))}));return n.An=r,n.Wn=i,n.Un.Fn(n.Wn),s}function Uh(e){const t=Ha(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.He.getLastRemoteSnapshotVersion(e)))}function Fh(e,t){const n=Ha(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.An.getNextMutationBatchAfterBatchId(e,t))))}async function Vh(e,t,n){const r=Ha(e),i=r.qn.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!Th(e))throw e;Fa("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qn=r.qn.remove(t),r.Kn.delete(i.target)}function jh(e,t,n){const r=Ha(e);let i=ac.min(),s=gl();return r.persistence.runTransaction("Execute query","readonly",(e=>function(e,t,n){const r=Ha(e),i=r.Kn.get(n);return void 0!==i?wh.resolve(r.qn.get(i)):r.He.getTargetData(t,n)}(r,e,gu(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.He.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r.Un.getDocumentsMatchingQuery(e,t,n?i:ac.min(),n?s:gl()))).next((e=>({documents:e,zn:s})))))}class qh{constructor(e){this.k=e,this.Xn=new Map,this.Zn=new Map}getBundleMetadata(e,t){return wh.resolve(this.Xn.get(t))}saveBundleMetadata(e,t){var n;return this.Xn.set(t.id,{id:(n=t).id,version:n.version,createTime:Pl(n.createTime)}),wh.resolve()}getNamedQuery(e,t){return wh.resolve(this.Zn.get(t))}saveNamedQuery(e,t){return this.Zn.set(t.name,function(e){return{name:e.name,query:Sh(e.bundledQuery),readTime:Pl(e.readTime)}}(t)),wh.resolve()}}class Bh{constructor(){this.ts=new cl($h.es),this.ns=new cl($h.ss)}isEmpty(){return this.ts.isEmpty()}addReference(e,t){const n=new $h(e,t);this.ts=this.ts.add(n),this.ns=this.ns.add(n)}rs(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.os(new $h(e,t))}cs(e,t){e.forEach((e=>this.removeReference(e,t)))}us(e){const t=new kc(new dc([])),n=new $h(t,e),r=new $h(t,e+1),i=[];return this.ns.forEachInRange([n,r],(e=>{this.os(e),i.push(e.key)})),i}hs(){this.ts.forEach((e=>this.os(e)))}os(e){this.ts=this.ts.delete(e),this.ns=this.ns.delete(e)}ls(e){const t=new kc(new dc([])),n=new $h(t,e),r=new $h(t,e+1);let i=gl();return this.ns.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new $h(e,0),n=this.ts.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class $h{constructor(e,t){this.key=e,this.fs=t}static es(e,t){return kc.comparator(e.key,t.key)||ic(e.fs,t.fs)}static ss(e,t){return ic(e.fs,t.fs)||kc.comparator(e.key,t.key)}}class Hh{constructor(e,t){this.Jt=e,this.referenceDelegate=t,this.An=[],this.ds=1,this.ws=new cl($h.es)}checkEmpty(e){return wh.resolve(0===this.An.length)}addMutationBatch(e,t,n,r){const i=this.ds;this.ds++,this.An.length>0&&this.An[this.An.length-1];const s=new Ih(i,t,n,r);this.An.push(s);for(const t of r)this.ws=this.ws.add(new $h(t.key,i)),this.Jt.addToCollectionParentIndex(e,t.key.path.popLast());return wh.resolve(s)}lookupMutationBatch(e,t){return wh.resolve(this._s(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.gs(n),i=r<0?0:r;return wh.resolve(this.An.length>i?this.An[i]:null)}getHighestUnacknowledgedBatchId(){return wh.resolve(0===this.An.length?-1:this.ds-1)}getAllMutationBatches(e){return wh.resolve(this.An.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new $h(t,0),r=new $h(t,Number.POSITIVE_INFINITY),i=[];return this.ws.forEachInRange([n,r],(e=>{const t=this._s(e.fs);i.push(t)})),wh.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new cl(ic);return t.forEach((e=>{const t=new $h(e,0),r=new $h(e,Number.POSITIVE_INFINITY);this.ws.forEachInRange([t,r],(e=>{n=n.add(e.fs)}))})),wh.resolve(this.ys(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;kc.isDocumentKey(i)||(i=i.child(""));const s=new $h(new kc(i),0);let o=new cl(ic);return this.ws.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.fs)),!0)}),s),wh.resolve(this.ys(o))}ys(e){const t=[];return e.forEach((e=>{const n=this._s(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){$a(0===this.ps(t.batchId,"removed")),this.An.shift();let n=this.ws;return wh.forEach(t.mutations,(r=>{const i=new $h(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.ws=n}))}ee(e){}containsKey(e,t){const n=new $h(t,0),r=this.ws.firstAfterOrEqual(n);return wh.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.An.length,wh.resolve()}ps(e,t){return this.gs(e)}gs(e){return 0===this.An.length?0:e-this.An[0].batchId}_s(e){const t=this.gs(e);return t<0||t>=this.An.length?null:this.An[t]}}class Kh{constructor(e,t){this.Jt=e,this.Ts=t,this.docs=new sl(kc.comparator),this.size=0}addEntry(e,t,n){const r=t.key,i=this.docs.get(r),s=i?i.size:0,o=this.Ts(t);return this.docs=this.docs.insert(r,{document:t.clone(),size:o,readTime:n}),this.size+=o-s,this.Jt.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return wh.resolve(n?n.document.clone():Bc.newInvalidDocument(t))}getEntries(e,t){let n=hl();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.clone():Bc.newInvalidDocument(e))})),wh.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=hl();const i=new kc(t.path.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i,readTime:o}}=s.getNext();if(!t.path.isPrefixOf(e.path))break;o.compareTo(n)<=0||Iu(t,i)&&(r=r.insert(i.key,i.clone()))}return wh.resolve(r)}Es(e,t){return wh.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new zh(this)}getSize(e){return wh.resolve(this.size)}}class zh extends class{constructor(){this.changes=new Dh((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}getReadTime(e){const t=this.changes.get(e);return t?t.readTime:ac.min()}addEntry(e,t){this.assertNotApplied(),this.changes.set(e.key,{document:e,readTime:t})}removeEntry(e,t=null){this.assertNotApplied(),this.changes.set(e,{document:Bc.newInvalidDocument(e),readTime:t})}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?wh.resolve(n.document):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}{constructor(e){super(),this.De=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.document.isValidDocument()?t.push(this.De.addEntry(e,r.document,this.getReadTime(n))):this.De.removeEntry(n)})),wh.waitFor(t)}getFromCache(e,t){return this.De.getEntry(e,t)}getAllFromCache(e,t){return this.De.getEntries(e,t)}}class Gh{constructor(e){this.persistence=e,this.Is=new Dh((e=>Kc(e)),zc),this.lastRemoteSnapshotVersion=ac.min(),this.highestTargetId=0,this.As=0,this.Rs=new Bh,this.targetCount=0,this.Ps=Nh.ie()}forEachTarget(e,t){return this.Is.forEach(((e,n)=>t(n))),wh.resolve()}getLastRemoteSnapshotVersion(e){return wh.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return wh.resolve(this.As)}allocateTargetId(e){return this.highestTargetId=this.Ps.next(),wh.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.As&&(this.As=t),wh.resolve()}ce(e){this.Is.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Ps=new Nh(t),this.highestTargetId=t),e.sequenceNumber>this.As&&(this.As=e.sequenceNumber)}addTargetData(e,t){return this.ce(t),this.targetCount+=1,wh.resolve()}updateTargetData(e,t){return this.ce(t),wh.resolve()}removeTargetData(e,t){return this.Is.delete(t.target),this.Rs.us(t.targetId),this.targetCount-=1,wh.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.Is.forEach(((s,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Is.delete(s),i.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),wh.waitFor(i).next((()=>r))}getTargetCount(e){return wh.resolve(this.targetCount)}getTargetData(e,t){const n=this.Is.get(t)||null;return wh.resolve(n)}addMatchingKeys(e,t,n){return this.Rs.rs(t,n),wh.resolve()}removeMatchingKeys(e,t,n){this.Rs.cs(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),wh.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Rs.us(t),wh.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Rs.ls(t);return wh.resolve(n)}containsKey(e,t){return wh.resolve(this.Rs.containsKey(t))}}class Wh{constructor(e,t){this.bs={},this.Be=new tc(0),this.Ue=!1,this.Ue=!0,this.referenceDelegate=e(this),this.He=new Gh(this),this.Jt=new kh,this.Je=function(e,t){return new Kh(e,t)}(this.Jt,(e=>this.referenceDelegate.vs(e))),this.k=new _h(t),this.Ye=new qh(this.k)}start(){return Promise.resolve()}shutdown(){return this.Ue=!1,Promise.resolve()}get started(){return this.Ue}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Jt}getMutationQueue(e){let t=this.bs[e.toKey()];return t||(t=new Hh(this.Jt,this.referenceDelegate),this.bs[e.toKey()]=t),t}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getBundleCache(){return this.Ye}runTransaction(e,t,n){Fa("MemoryPersistence","Starting transaction:",e);const r=new Jh(this.Be.next());return this.referenceDelegate.Vs(),n(r).next((e=>this.referenceDelegate.Ss(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Ds(e,t){return wh.or(Object.values(this.bs).map((n=>()=>n.containsKey(e,t))))}}class Jh extends class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}{constructor(e){super(),this.currentSequenceNumber=e}}class Xh{constructor(e){this.persistence=e,this.Cs=new Bh,this.Ns=null}static ks(e){return new Xh(e)}get xs(){if(this.Ns)return this.Ns;throw Ba()}addReference(e,t,n){return this.Cs.addReference(n,t),this.xs.delete(n.toString()),wh.resolve()}removeReference(e,t,n){return this.Cs.removeReference(n,t),this.xs.add(n.toString()),wh.resolve()}markPotentiallyOrphaned(e,t){return this.xs.add(t.toString()),wh.resolve()}removeTarget(e,t){this.Cs.us(t.targetId).forEach((e=>this.xs.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.xs.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}Vs(){this.Ns=new Set}Ss(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return wh.forEach(this.xs,(n=>{const r=kc.fromPath(n);return this.$s(e,r).next((e=>{e||t.removeEntry(r)}))})).next((()=>(this.Ns=null,t.apply(e))))}updateLimboDocument(e,t){return this.$s(e,t).next((e=>{e?this.xs.delete(t.toString()):this.xs.add(t.toString())}))}vs(e){return 0}$s(e,t){return wh.or([()=>wh.resolve(this.Cs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ds(e,t)])}}class Qh{constructor(){this.activeTargetIds=vl()}Ms(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ls(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Os(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Yh{constructor(){this.pi=new Qh,this.Ti={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.pi.Ms(e),this.Ti[e]||"not-current"}updateQueryState(e,t,n){this.Ti[e]=t}removeLocalQueryTarget(e){this.pi.Ls(e)}isLocalQueryTarget(e){return this.pi.activeTargetIds.has(e)}clearQueryState(e){delete this.Ti[e]}getAllActiveQueryTargets(){return this.pi.activeTargetIds}isActiveQueryTarget(e){return this.pi.activeTargetIds.has(e)}start(){return this.pi=new Qh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class Zh{Ei(e){}shutdown(){}}class ed{constructor(){this.Ii=()=>this.Ai(),this.Ri=()=>this.Pi(),this.bi=[],this.vi()}Ei(e){this.bi.push(e)}shutdown(){window.removeEventListener("online",this.Ii),window.removeEventListener("offline",this.Ri)}vi(){window.addEventListener("online",this.Ii),window.addEventListener("offline",this.Ri)}Ai(){Fa("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.bi)e(0)}Pi(){Fa("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.bi)e(1)}static bt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const td={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class nd{constructor(e){this.Vi=e.Vi,this.Si=e.Si}Di(e){this.Ci=e}Ni(e){this.ki=e}onMessage(e){this.xi=e}close(){this.Si()}send(e){this.Vi(e)}$i(){this.Ci()}Fi(e){this.ki(e)}Oi(e){this.xi(e)}}class rd extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http";this.Mi=t+"://"+e.host,this.Li="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Bi(e,t,n,r,i){const s=this.Ui(e,t);Fa("RestConnection","Sending: ",s,n);const o={};return this.qi(o,r,i),this.Ki(e,s,o,n).then((e=>(Fa("RestConnection","Received: ",e),e)),(t=>{throw ja("RestConnection",`${e} failed with error: `,t,"url: ",s,"request:",n),t}))}ji(e,t,n,r,i){return this.Bi(e,t,n,r,i)}qi(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+Ma,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}Ui(e,t){const n=td[e];return`${this.Mi}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}Ki(e,t,n,r){return new Promise(((i,s)=>{const o=new La;o.listenOnce(Aa.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case ka.NO_ERROR:const t=o.getResponseJson();Fa("Connection","XHR received:",JSON.stringify(t)),i(t);break;case ka.TIMEOUT:Fa("Connection",'RPC "'+e+'" timed out'),s(new za(Ka.DEADLINE_EXCEEDED,"Request time out"));break;case ka.HTTP_ERROR:const n=o.getStatus();if(Fa("Connection",'RPC "'+e+'" failed with status:',n,"response text:",o.getResponseText()),n>0){const e=o.getResponseJson().error;if(e&&e.status&&e.message){const t=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(Ka).indexOf(t)>=0?t:Ka.UNKNOWN}(e.status);s(new za(t,e.message))}else s(new za(Ka.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new za(Ka.UNAVAILABLE,"Connection failed."));break;default:Ba()}}finally{Fa("Connection",'RPC "'+e+'" completed.')}}));const a=JSON.stringify(r);o.send(t,"POST",a,n,15)}))}Qi(e,t,n){const c=[this.Mi,"/","google.firestore.v1.Firestore","/",e,"/channel"],u=_a(),l=Sa(),h={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(h.xmlHttpFactory=new Ra({})),this.qi(h.initMessageHeaders,t,n),i()||o()||r().indexOf("Electron/")>=0||a()||r().indexOf("MSAppHost/")>=0||s()||(h.httpHeadersOverwriteParam="$httpHeaders");const d=c.join("");Fa("Connection","Creating WebChannel: "+d,h);const f=u.createWebChannel(d,h);let p=!1,m=!1;const g=new nd({Vi:e=>{m?Fa("Connection","Not sending because WebChannel is closed:",e):(p||(Fa("Connection","Opening WebChannel transport."),f.open(),p=!0),Fa("Connection","WebChannel sending:",e),f.send(e))},Si:()=>f.close()}),y=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return y(f,Da.EventType.OPEN,(()=>{m||Fa("Connection","WebChannel transport opened.")})),y(f,Da.EventType.CLOSE,(()=>{m||(m=!0,Fa("Connection","WebChannel transport closed"),g.Fi())})),y(f,Da.EventType.ERROR,(e=>{m||(m=!0,ja("Connection","WebChannel transport errored:",e),g.Fi(new za(Ka.UNAVAILABLE,"The operation could not be completed")))})),y(f,Da.EventType.MESSAGE,(e=>{var t;if(!m){const n=e.data[0];$a(!!n);const r=n,i=r.error||(null===(t=r[0])||void 0===t?void 0:t.error);if(i){Fa("Connection","WebChannel received error:",i);const e=i.status;let t=function(e){const t=nl[e];if(void 0!==t)return il(t)}(e),n=i.message;void 0===t&&(t=Ka.INTERNAL,n="Unknown error status: "+e+" with message "+i.message),m=!0,g.Fi(new za(t,n)),f.close()}else Fa("Connection","WebChannel received:",n),g.Oi(n)}})),y(l,Ca.STAT_EVENT,(e=>{e.stat===Na.PROXY?Fa("Connection","Detected buffering proxy"):e.stat===Na.NOPROXY&&Fa("Connection","Detected no buffering proxy")})),setTimeout((()=>{g.$i()}),0),g}}function id(){return"undefined"!=typeof document?document:null}function sd(e){return new Rl(e,!0)}class od{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Oe=e,this.timerId=t,this.Wi=n,this.Gi=r,this.zi=i,this.Hi=0,this.Ji=null,this.Yi=Date.now(),this.reset()}reset(){this.Hi=0}Xi(){this.Hi=this.zi}Zi(e){this.cancel();const t=Math.floor(this.Hi+this.tr()),n=Math.max(0,Date.now()-this.Yi),r=Math.max(0,t-n);r>0&&Fa("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Hi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Ji=this.Oe.enqueueAfterDelay(this.timerId,r,(()=>(this.Yi=Date.now(),e()))),this.Hi*=this.Gi,this.Hithis.zi&&(this.Hi=this.zi)}er(){null!==this.Ji&&(this.Ji.skipDelay(),this.Ji=null)}cancel(){null!==this.Ji&&(this.Ji.cancel(),this.Ji=null)}tr(){return(Math.random()-.5)*this.Hi}}class ad{constructor(e,t,n,r,i,s,o,a){this.Oe=e,this.nr=n,this.sr=r,this.ir=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.rr=0,this.ar=null,this.cr=null,this.stream=null,this.ur=new od(e,t)}hr(){return 1===this.state||5===this.state||this.lr()}lr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.dr()}async stop(){this.hr()&&await this.close(0)}wr(){this.state=0,this.ur.reset()}_r(){this.lr()&&null===this.ar&&(this.ar=this.Oe.enqueueAfterDelay(this.nr,6e4,(()=>this.mr())))}gr(e){this.yr(),this.stream.send(e)}async mr(){if(this.lr())return this.close(0)}yr(){this.ar&&(this.ar.cancel(),this.ar=null)}pr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(e,t){this.yr(),this.pr(),this.ur.cancel(),this.rr++,4!==e?this.ur.reset():t&&t.code===Ka.RESOURCE_EXHAUSTED?(Va(t.toString()),Va("Using maximum backoff delay to prevent overloading the backend."),this.ur.Xi()):t&&t.code===Ka.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Tr(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ni(t)}Tr(){}auth(){this.state=1;const e=this.Er(this.rr),t=this.rr;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.rr===t&&this.Ir(e,n)}),(t=>{e((()=>{const e=new za(Ka.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ar(e)}))}))}Ir(e,t){const n=this.Er(this.rr);this.stream=this.Rr(e,t),this.stream.Di((()=>{n((()=>(this.state=2,this.cr=this.Oe.enqueueAfterDelay(this.sr,1e4,(()=>(this.lr()&&(this.state=3),Promise.resolve()))),this.listener.Di())))})),this.stream.Ni((e=>{n((()=>this.Ar(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}dr(){this.state=5,this.ur.Zi((async()=>{this.state=0,this.start()}))}Ar(e){return Fa("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Er(e){return t=>{this.Oe.enqueueAndForget((()=>this.rr===e?t():(Fa("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class cd extends ad{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.k=i}Rr(e,t){return this.ir.Qi("Listen",e,t)}onMessage(e){this.ur.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:Ba()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.C?($a(void 0===t||"string"==typeof t),gc.fromBase64String(t||"")):($a(void 0===t||t instanceof Uint8Array),gc.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?Ka.UNKNOWN:il(e.code);return new za(t,e.message||"")}(o);n=new bl(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=Fl(e,r.document.name),s=Pl(r.document.updateTime),o=new jc({mapValue:{fields:r.document.fields}}),a=Bc.newFoundDocument(i,s,o),c=r.targetIds||[],u=r.removedTargetIds||[];n=new Il(c,u,a.key,a)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=Fl(e,r.document),s=r.readTime?Pl(r.readTime):ac.min(),o=Bc.newNoDocument(i,s),a=r.removedTargetIds||[];n=new Il([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=Fl(e,r.document),s=r.removedTargetIds||[];n=new Il([],s,i,null)}else{if(!("filter"in t))return Ba();{t.filter;const e=t.filter;e.targetId;const r=e.count||0,i=new tl(r),s=e.targetId;n=new El(s,i)}}return n}(this.k,e),n=function(e){if(!("targetChange"in e))return ac.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?ac.min():t.readTime?Pl(t.readTime):ac.min()}(e);return this.listener.Pr(t,n)}br(e){const t={};t.database=jl(this.k),t.addTarget=function(e,t){let n;const r=t.target;return n=Gc(r)?{documents:$l(e,r)}:{query:Hl(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0?n.resumeToken=Ll(e,t.resumeToken):t.snapshotVersion.compareTo(ac.min())>0&&(n.readTime=Dl(e,t.snapshotVersion.toTimestamp())),n}(this.k,e);const n=function(e,t){const n=function(e,t){switch(t){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return Ba()}}(0,t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.k,e);n&&(t.labels=n),this.gr(t)}vr(e){const t={};t.database=jl(this.k),t.removeTarget=e,this.gr(t)}}class ud extends ad{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.k=i,this.Vr=!1}get Sr(){return this.Vr}start(){this.Vr=!1,this.lastStreamToken=void 0,super.start()}Tr(){this.Vr&&this.Dr([])}Rr(e,t){return this.ir.Qi("Write",e,t)}onMessage(e){if($a(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Vr){this.ur.reset();const t=function(e,t){return e&&e.length>0?($a(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?Pl(e.updateTime):Pl(t);return n.isEqual(ac.min())&&(n=Pl(t)),new Vu(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=Pl(e.commitTime);return this.listener.Cr(n,t)}return $a(!e.writeResults||0===e.writeResults.length),this.Vr=!0,this.listener.Nr()}kr(){const e={};e.database=jl(this.k),this.gr(e)}Dr(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>function(e,t){let n;if(t instanceof Wu)n={update:Bl(e,t.key,t.value)};else if(t instanceof Zu)n={delete:Ul(e,t.key)};else if(t instanceof Ju)n={update:Bl(e,t.key,t.data),updateMask:th(t.fieldMask)};else{if(!(t instanceof el))return Ba();n={verify:Ul(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof Du)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Lu)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof Pu)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof xu)return{fieldPath:t.field.canonicalString(),increment:n.N};throw Ba()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:Ol(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Ba()}(e,t.precondition)),n}(this.k,e)))};this.gr(t)}}class ld extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.ir=n,this.k=r,this.$r=!1}Fr(){if(this.$r)throw new za(Ka.FAILED_PRECONDITION,"The client has already been terminated.")}Bi(e,t,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,i])=>this.ir.Bi(e,t,n,r,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===Ka.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new za(Ka.UNKNOWN,e.toString())}))}ji(e,t,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,i])=>this.ir.ji(e,t,n,r,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===Ka.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new za(Ka.UNKNOWN,e.toString())}))}terminate(){this.$r=!0}}class hd{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Or=0,this.Mr=null,this.Lr=!0}Br(){0===this.Or&&(this.Ur("Unknown"),this.Mr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.Mr=null,this.qr("Backend didn't respond within 10 seconds."),this.Ur("Offline"),Promise.resolve()))))}Kr(e){"Online"===this.state?this.Ur("Unknown"):(this.Or++,this.Or>=1&&(this.jr(),this.qr(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Ur("Offline")))}set(e){this.jr(),this.Or=0,"Online"===e&&(this.Lr=!1),this.Ur(e)}Ur(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}qr(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.Lr?(Va(t),this.Lr=!1):Fa("OnlineStateTracker",t)}jr(){null!==this.Mr&&(this.Mr.cancel(),this.Mr=null)}}class dd{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Qr=[],this.Wr=new Map,this.Gr=new Set,this.zr=[],this.Hr=i,this.Hr.Ei((e=>{n.enqueueAndForget((async()=>{Id(this)&&(Fa("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=Ha(e);t.Gr.add(4),await pd(t),t.Jr.set("Unknown"),t.Gr.delete(4),await fd(t)}(this))}))})),this.Jr=new hd(n,r)}}async function fd(e){if(Id(e))for(const t of e.zr)await t(!0)}async function pd(e){for(const t of e.zr)await t(!1)}function md(e,t){const n=Ha(e);n.Wr.has(t.targetId)||(n.Wr.set(t.targetId,t),Td(n)?wd(n):Ud(n).lr()&&yd(n,t))}function gd(e,t){const n=Ha(e),r=Ud(n);n.Wr.delete(t),r.lr()&&vd(n,t),0===n.Wr.size&&(r.lr()?r._r():Id(n)&&n.Jr.set("Unknown"))}function yd(e,t){e.Yr.X(t.targetId),Ud(e).br(t)}function vd(e,t){e.Yr.X(t),Ud(e).vr(t)}function wd(e){e.Yr=new Sl({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Et:t=>e.Wr.get(t)||null}),Ud(e).start(),e.Jr.Br()}function Td(e){return Id(e)&&!Ud(e).hr()&&e.Wr.size>0}function Id(e){return 0===Ha(e).Gr.size}function Ed(e){e.Yr=void 0}async function bd(e){e.Wr.forEach(((t,n)=>{yd(e,t)}))}async function _d(e,t){Ed(e),Td(e)?(e.Jr.Kr(t),wd(e)):e.Jr.set("Unknown")}async function Sd(e,t,n){if(e.Jr.set("Online"),t instanceof bl&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.Wr.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Wr.delete(r),e.Yr.removeTarget(r))}(e,t)}catch(n){Fa("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await kd(e,n)}else if(t instanceof Il?e.Yr.ot(t):t instanceof El?e.Yr.dt(t):e.Yr.ut(t),!n.isEqual(ac.min()))try{const t=await Uh(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.Yr.gt(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.Wr.get(r);i&&e.Wr.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach((t=>{const n=e.Wr.get(t);if(!n)return;e.Wr.set(t,n.withResumeToken(gc.EMPTY_BYTE_STRING,n.snapshotVersion)),vd(e,t);const r=new bh(n.target,t,1,n.sequenceNumber);yd(e,r)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){Fa("RemoteStore","Failed to raise snapshot:",t),await kd(e,t)}}async function kd(e,t,n){if(!Th(t))throw t;e.Gr.add(1),await pd(e),e.Jr.set("Offline"),n||(n=()=>Uh(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{Fa("RemoteStore","Retrying IndexedDB access"),await n(),e.Gr.delete(1),await fd(e)}))}function Ad(e,t){return t().catch((n=>kd(e,n,t)))}async function Cd(e){const t=Ha(e),n=Fd(t);let r=t.Qr.length>0?t.Qr[t.Qr.length-1].batchId:-1;for(;Nd(t);)try{const e=await Fh(t.localStore,r);if(null===e){0===t.Qr.length&&n._r();break}r=e.batchId,Rd(t,e)}catch(e){await kd(t,e)}Dd(t)&&Ld(t)}function Nd(e){return Id(e)&&e.Qr.length<10}function Rd(e,t){e.Qr.push(t);const n=Fd(e);n.lr()&&n.Sr&&n.Dr(t.mutations)}function Dd(e){return Id(e)&&!Fd(e).hr()&&e.Qr.length>0}function Ld(e){Fd(e).start()}async function Od(e){Fd(e).kr()}async function Pd(e){const t=Fd(e);for(const n of e.Qr)t.Dr(n.mutations)}async function Md(e,t,n){const r=e.Qr.shift(),i=Eh.from(r,t,n);await Ad(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await Cd(e)}async function xd(e,t){t&&Fd(e).Sr&&await async function(e,t){if(function(e){switch(e){default:return Ba();case Ka.CANCELLED:case Ka.UNKNOWN:case Ka.DEADLINE_EXCEEDED:case Ka.RESOURCE_EXHAUSTED:case Ka.INTERNAL:case Ka.UNAVAILABLE:case Ka.UNAUTHENTICATED:return!1;case Ka.INVALID_ARGUMENT:case Ka.NOT_FOUND:case Ka.ALREADY_EXISTS:case Ka.PERMISSION_DENIED:case Ka.FAILED_PRECONDITION:case Ka.ABORTED:case Ka.OUT_OF_RANGE:case Ka.UNIMPLEMENTED:case Ka.DATA_LOSS:return!0}}(n=t.code)&&n!==Ka.ABORTED){const n=e.Qr.shift();Fd(e).wr(),await Ad(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Cd(e)}var n}(e,t),Dd(e)&&Ld(e)}function Ud(e){return e.Xr||(e.Xr=function(e,t,n){const r=Ha(e);return r.Fr(),new cd(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(e.datastore,e.asyncQueue,{Di:bd.bind(null,e),Ni:_d.bind(null,e),Pr:Sd.bind(null,e)}),e.zr.push((async t=>{t?(e.Xr.wr(),Td(e)?wd(e):e.Jr.set("Unknown")):(await e.Xr.stop(),Ed(e))}))),e.Xr}function Fd(e){return e.Zr||(e.Zr=function(e,t,n){const r=Ha(e);return r.Fr(),new ud(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(e.datastore,e.asyncQueue,{Di:Od.bind(null,e),Ni:xd.bind(null,e),Nr:Pd.bind(null,e),Cr:Md.bind(null,e)}),e.zr.push((async t=>{t?(e.Zr.wr(),await Cd(e)):(await e.Zr.stop(),e.Qr.length>0&&(Fa("RemoteStore",`Stopping write stream with ${e.Qr.length} pending writes`),e.Qr=[]))}))),e.Zr}class Vd{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new Ga,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new Vd(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new za(Ka.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function jd(e,t){if(Va("AsyncQueue",`${t}: ${e}`),Th(e))return new za(Ka.UNAVAILABLE,`${t}: ${e}`);throw e}class qd{constructor(e){this.comparator=e?(t,n)=>e(t,n)||kc.comparator(t.key,n.key):(e,t)=>kc.comparator(e.key,t.key),this.keyedMap=fl(),this.sortedSet=new sl(this.comparator)}static emptySet(e){return new qd(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof qd))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new qd;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Bd{constructor(){this.eo=new sl(kc.comparator)}track(e){const t=e.doc.key,n=this.eo.get(t);n?0!==e.type&&3===n.type?this.eo=this.eo.insert(t,e):3===e.type&&1!==n.type?this.eo=this.eo.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.eo=this.eo.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.eo=this.eo.remove(t):1===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):Ba():this.eo=this.eo.insert(t,e)}no(){const e=[];return this.eo.inorderTraversal(((t,n)=>{e.push(n)})),e}}class $d{constructor(e,t,n,r,i,s,o,a){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(e,t,n,r){const i=[];return t.forEach((e=>{i.push({type:0,doc:e})})),new $d(e,t,qd.emptySet(t),i,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&vu(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;ewu(e)),vu),this.onlineState="Unknown",this.io=new Set}}async function zd(e,t){const n=Ha(e),r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new Hd),i)try{s.so=await n.onListen(r)}catch(e){const n=jd(e,`Initialization of query '${Tu(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.ro(n.onlineState),s.so&&t.oo(s.so)&&Xd(n)}async function Gd(e,t){const n=Ha(e),r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);e>=0&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Wd(e,t){const n=Ha(e);let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.oo(e)&&(r=!0);i.so=e}}r&&Xd(n)}function Jd(e,t,n){const r=Ha(e),i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}function Xd(e){e.io.forEach((e=>{e.next()}))}class Qd{constructor(e,t,n){this.query=e,this.ao=t,this.co=!1,this.uo=null,this.onlineState="Unknown",this.options=n||{}}oo(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new $d(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.co?this.ho(e)&&(this.ao.next(e),t=!0):this.lo(e,this.onlineState)&&(this.fo(e),t=!0),this.uo=e,t}onError(e){this.ao.error(e)}ro(e){this.onlineState=e;let t=!1;return this.uo&&!this.co&&this.lo(this.uo,e)&&(this.fo(this.uo),t=!0),t}lo(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return!(this.options.wo&&n||e.docs.isEmpty()&&"Offline"!==t)}ho(e){if(e.docChanges.length>0)return!0;const t=this.uo&&this.uo.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}fo(e){e=$d.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.co=!0,this.ao.next(e)}}class Yd{constructor(e){this.key=e}}class Zd{constructor(e){this.key=e}}class ef{constructor(e,t){this.query=e,this.To=t,this.Eo=null,this.current=!1,this.Io=gl(),this.mutatedKeys=gl(),this.Ao=Eu(e),this.Ro=new qd(this.Ao)}get Po(){return this.To}bo(e,t){const n=t?t.vo:new Bd,r=t?t.Ro:this.Ro;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,o=!1;const a=hu(this.query)&&r.size===this.query.limit?r.last():null,c=du(this.query)&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const u=r.get(e),l=Iu(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;u&&l?u.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.Vo(u,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.Ao(l,a)>0||c&&this.Ao(l,c)<0)&&(o=!0)):!u&&l?(n.track({type:0,doc:l}),f=!0):u&&!l&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(l?(s=s.add(l),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),hu(this.query)||du(this.query))for(;s.size>this.query.limit;){const e=hu(this.query)?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{Ro:s,vo:n,Bn:o,mutatedKeys:i}}Vo(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.Ro;this.Ro=e.Ro,this.mutatedKeys=e.mutatedKeys;const i=e.vo.no();i.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Ba()}};return n(e)-n(t)}(e.type,t.type)||this.Ao(e.doc,t.doc))),this.So(n);const s=t?this.Do():[],o=0===this.Io.size&&this.current?1:0,a=o!==this.Eo;return this.Eo=o,0!==i.length||a?{snapshot:new $d(this.query,e.Ro,r,i,e.mutatedKeys,0===o,a,!1),Co:s}:{Co:s}}ro(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ro:this.Ro,vo:new Bd,mutatedKeys:this.mutatedKeys,Bn:!1},!1)):{Co:[]}}No(e){return!this.To.has(e)&&!!this.Ro.has(e)&&!this.Ro.get(e).hasLocalMutations}So(e){e&&(e.addedDocuments.forEach((e=>this.To=this.To.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.To=this.To.delete(e))),this.current=e.current)}Do(){if(!this.current)return[];const e=this.Io;this.Io=gl(),this.Ro.forEach((e=>{this.No(e.key)&&(this.Io=this.Io.add(e.key))}));const t=[];return e.forEach((e=>{this.Io.has(e)||t.push(new Zd(e))})),this.Io.forEach((n=>{e.has(n)||t.push(new Yd(n))})),t}ko(e){this.To=e.zn,this.Io=gl();const t=this.bo(e.documents);return this.applyChanges(t,!0)}xo(){return $d.fromInitialDocuments(this.query,this.Ro,this.mutatedKeys,0===this.Eo)}}class tf{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class nf{constructor(e){this.key=e,this.$o=!1}}class rf{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Fo={},this.Oo=new Dh((e=>wu(e)),vu),this.Mo=new Map,this.Lo=new Set,this.Bo=new sl(kc.comparator),this.Uo=new Map,this.qo=new Bh,this.Ko={},this.jo=new Map,this.Qo=Nh.re(),this.onlineState="Unknown",this.Wo=void 0}get isPrimaryClient(){return!0===this.Wo}}async function sf(e,t){const n=function(e){const t=Ha(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=af.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=If.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=uf.bind(null,t),t.Fo.Pr=Wd.bind(null,t.eventManager),t.Fo.zo=Jd.bind(null,t.eventManager),t}(e);let r,i;const s=n.Oo.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.xo();else{const e=await function(e,t){const n=Ha(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.He.getTargetData(e,t).next((i=>i?(r=i,wh.resolve(r)):n.He.allocateTargetId(e).next((i=>(r=new bh(t,i,0,e.currentSequenceNumber),n.He.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.qn.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.qn=n.qn.insert(e.targetId,e),n.Kn.set(t,e.targetId)),e}))}(n.localStore,gu(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await async function(e,t,n,r){e.Go=(t,n,r)=>async function(e,t,n,r){let i=t.view.bo(n);i.Bn&&(i=await jh(e.localStore,t.query,!1).then((({documents:e})=>t.view.bo(e,i))));const s=r&&r.targetChanges.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s);return gf(e,t.targetId,o.Co),o.snapshot}(e,t,n,r);const i=await jh(e.localStore,t,!0),s=new ef(t,i.zn),o=s.bo(i.documents),a=Tl.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState),c=s.applyChanges(o,e.isPrimaryClient,a);gf(e,n,c.Co);const u=new tf(t,n,s);return e.Oo.set(t,u),e.Mo.has(n)?e.Mo.get(n).push(t):e.Mo.set(n,[t]),c.snapshot}(n,t,r,"current"===s),n.isPrimaryClient&&md(n.remoteStore,e)}return i}async function of(e,t){const n=Ha(e),r=n.Oo.get(t),i=n.Mo.get(r.targetId);if(i.length>1)return n.Mo.set(r.targetId,i.filter((e=>!vu(e,t)))),void n.Oo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Vh(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),gd(n.remoteStore,r.targetId),pf(n,r.targetId)})).catch(Rh)):(pf(n,r.targetId),await Vh(n.localStore,r.targetId,!0))}async function af(e,t){const n=Ha(e);try{const e=await function(e,t){const n=Ha(e),r=t.snapshotVersion;let i=n.qn;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.Qn.newChangeBuffer({trackRemovals:!0});i=n.qn;const o=[];t.targetChanges.forEach(((t,s)=>{const a=i.get(s);if(!a)return;o.push(n.He.removeMatchingKeys(e,t.removedDocuments,s).next((()=>n.He.addMatchingKeys(e,t.addedDocuments,s))));const c=t.resumeToken;if(c.approximateByteSize()>0){const u=a.withResumeToken(c,r).withSequenceNumber(e.currentSequenceNumber);i=i.insert(s,u),function(e,t,n){return $a(t.resumeToken.approximateByteSize()>0),0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(a,u,t)&&o.push(n.He.updateTargetData(e,u))}}));let a=hl();if(t.documentUpdates.forEach(((r,i)=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(function(e,t,n,r,i){let s=gl();return n.forEach((e=>s=s.add(e))),t.getEntries(e,s).next((e=>{let s=hl();return n.forEach(((n,o)=>{const a=e.get(n),c=(null==i?void 0:i.get(n))||r;o.isNoDocument()&&o.version.isEqual(ac.min())?(t.removeEntry(n,c),s=s.insert(n,o)):!a.isValidDocument()||o.version.compareTo(a.version)>0||0===o.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(o,c),s=s.insert(n,o)):Fa("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",o.version)})),s}))}(e,s,t.documentUpdates,r,void 0).next((e=>{a=e}))),!r.isEqual(ac.min())){const t=n.He.getLastRemoteSnapshotVersion(e).next((t=>n.He.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return wh.waitFor(o).next((()=>s.apply(e))).next((()=>n.Wn.Vn(e,a))).next((()=>a))})).then((e=>(n.qn=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.Uo.get(t);r&&($a(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.$o=!0:e.modifiedDocuments.size>0?$a(r.$o):e.removedDocuments.size>0&&($a(r.$o),r.$o=!1))})),await wf(n,e,t)}catch(e){await Rh(e)}}function cf(e,t,n){const r=Ha(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.Oo.forEach(((n,r)=>{const i=r.view.ro(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=Ha(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const e of n.listeners)e.ro(t)&&(r=!0)})),r&&Xd(n)}(r.eventManager,t),e.length&&r.Fo.Pr(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function uf(e,t,n){const r=Ha(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Uo.get(t),s=i&&i.key;if(s){let e=new sl(kc.comparator);e=e.insert(s,Bc.newNoDocument(s,ac.min()));const n=gl().add(s),i=new wl(ac.min(),new Map,new cl(ic),e,n);await af(r,i),r.Bo=r.Bo.remove(s),r.Uo.delete(t),vf(r)}else await Vh(r.localStore,t,!1).then((()=>pf(r,t,n))).catch(Rh)}async function lf(e,t){const n=Ha(e),r=t.batch.batchId;try{const e=await function(e,t){const n=Ha(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.Qn.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let o=wh.resolve();return s.forEach((e=>{o=o.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);$a(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&r.addEntry(t,n.commitVersion))}))})),o.next((()=>e.An.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.An.performConsistencyCheck(e))).next((()=>n.Wn.vn(e,r)))}))}(n.localStore,t);ff(n,r,null),df(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await wf(n,e)}catch(e){await Rh(e)}}async function hf(e,t,n){const r=Ha(e);try{const e=await function(e,t){const n=Ha(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.An.lookupMutationBatch(e,t).next((t=>($a(null!==t),r=t.keys(),n.An.removeMutationBatch(e,t)))).next((()=>n.An.performConsistencyCheck(e))).next((()=>n.Wn.vn(e,r)))}))}(r.localStore,t);ff(r,t,n),df(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await wf(r,e)}catch(n){await Rh(n)}}function df(e,t){(e.jo.get(t)||[]).forEach((e=>{e.resolve()})),e.jo.delete(t)}function ff(e,t,n){const r=Ha(e);let i=r.Ko[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Ko[r.currentUser.toKey()]=i}}function pf(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.Mo.get(t))e.Oo.delete(r),n&&e.Fo.zo(r,n);e.Mo.delete(t),e.isPrimaryClient&&e.qo.us(t).forEach((t=>{e.qo.containsKey(t)||mf(e,t)}))}function mf(e,t){e.Lo.delete(t.path.canonicalString());const n=e.Bo.get(t);null!==n&&(gd(e.remoteStore,n),e.Bo=e.Bo.remove(t),e.Uo.delete(n),vf(e))}function gf(e,t,n){for(const r of n)r instanceof Yd?(e.qo.addReference(r.key,t),yf(e,r)):r instanceof Zd?(Fa("SyncEngine","Document no longer in limbo: "+r.key),e.qo.removeReference(r.key,t),e.qo.containsKey(r.key)||mf(e,r.key)):Ba()}function yf(e,t){const n=t.key,r=n.path.canonicalString();e.Bo.get(n)||e.Lo.has(r)||(Fa("SyncEngine","New document in limbo: "+n),e.Lo.add(r),vf(e))}function vf(e){for(;e.Lo.size>0&&e.Bo.size{o.push(r.Go(a,t,n).then((e=>{if(e){r.isPrimaryClient&&r.sharedClientState.updateQueryState(a.targetId,e.fromCache?"not-current":"current"),i.push(e);const t=Oh.$n(a.targetId,e);s.push(t)}})))})),await Promise.all(o),r.Fo.Pr(i),await async function(e,t){const n=Ha(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>wh.forEach(t,(t=>wh.forEach(t.kn,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>wh.forEach(t.xn,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!Th(e))throw e;Fa("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=n.qn.get(t),r=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(r);n.qn=n.qn.insert(t,i)}}}(r.localStore,s))}async function Tf(e,t){const n=Ha(e);if(!n.currentUser.isEqual(t)){Fa("SyncEngine","User change. New user:",t.toKey());const e=await xh(n.localStore,t);n.currentUser=t,function(e,t){e.jo.forEach((e=>{e.forEach((e=>{e.reject(new za(Ka.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.jo.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await wf(n,e.Gn)}}function If(e,t){const n=Ha(e),r=n.Uo.get(t);if(r&&r.$o)return gl().add(r.key);{let e=gl();const r=n.Mo.get(t);if(!r)return e;for(const t of r){const r=n.Oo.get(t);e=e.unionWith(r.view.Po)}return e}}function Ef(e){const t=Ha(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=lf.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=hf.bind(null,t),t}class bf{constructor(){this.synchronizeTabs=!1}async initialize(e){this.k=sd(e.databaseInfo.databaseId),this.sharedClientState=this.Jo(e),this.persistence=this.Yo(e),await this.persistence.start(),this.gcScheduler=this.Xo(e),this.localStore=this.Zo(e)}Xo(e){return null}Zo(e){return function(e,t,n,r){return new Mh(e,t,n,r)}(this.persistence,new Ph,e.initialUser,this.k)}Yo(e){return new Wh(Xh.ks,this.k)}Jo(e){return new Yh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class _f{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>cf(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Tf.bind(null,this.syncEngine),await async function(e,t){const n=Ha(e);t?(n.Gr.delete(2),await fd(n)):t||(n.Gr.add(2),await pd(n),n.Jr.set("Unknown"))}(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Kd}createDatastore(e){const t=sd(e.databaseInfo.databaseId),n=(r=e.databaseInfo,new rd(r));var r;return function(e,t,n,r){return new ld(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>cf(this.syncEngine,e,0),s=ed.bt()?new ed:new Zh,new dd(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new rf(e,t,n,r,i,s);return o&&(a.Wo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=Ha(e);Fa("RemoteStore","RemoteStore shutting down."),t.Gr.add(5),await pd(t),t.Hr.shutdown(),t.Jr.set("Unknown")}(this.remoteStore)}}class Sf{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.ea(this.observer.next,e)}error(e){this.observer.error?this.ea(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}na(){this.muted=!0}ea(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class kf{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Pa.UNAUTHENTICATED,this.clientId=rc.A(),this.authCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{Fa("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(()=>Promise.resolve()))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new za(Ka.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new Ga;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=jd(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function Af(e,t){e.asyncQueue.verifyOperationInProgress();const n=await async function(e){return e.offlineComponents||(Fa("FirestoreClient","Using default OfflineComponentProvider"),await async function(e,t){e.asyncQueue.verifyOperationInProgress(),Fa("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await xh(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e.offlineComponents=t}(e,new bf)),e.offlineComponents}(e);Fa("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>async function(e,t){const n=Ha(e);n.asyncQueue.verifyOperationInProgress(),Fa("RemoteStore","RemoteStore received new credentials");const r=Id(n);n.Gr.add(3),await pd(n),r&&n.Jr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Gr.delete(3),await fd(n)}(t.remoteStore,e))),e.onlineComponents=t}async function Cf(e){return e.onlineComponents||(Fa("FirestoreClient","Using default OnlineComponentProvider"),await Af(e,new _f)),e.onlineComponents}async function Nf(e){const t=await Cf(e),n=t.eventManager;return n.onListen=sf.bind(null,t.syncEngine),n.onUnlisten=of.bind(null,t.syncEngine),n}class Rf{constructor(e,t,n,r,i,s,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class Df{constructor(e,t){this.projectId=e,this.database=t||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Df&&e.projectId===this.projectId&&e.database===this.database}}const Lf=new Map;function Of(e,t,n){if(!n)throw new za(Ka.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Pf(e){if(!kc.isDocumentKey(e))throw new za(Ka.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Mf(e){if(kc.isDocumentKey(e))throw new za(Ka.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function xf(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":Ba()}function Uf(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new za(Ka.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=xf(e);throw new za(Ka.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}class Ff{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new za(Ka.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new za(Ka.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,function(e,t,n,r){if(!0===t&&!0===r)throw new za(Ka.INVALID_ARGUMENT,"experimentalForceLongPolling and experimentalAutoDetectLongPolling cannot be used together.")}(0,e.experimentalForceLongPolling,0,e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Vf{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Ff({}),this._settingsFrozen=!1,e instanceof Df?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new za(Ka.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Df(e.options.projectId)}(e))}get app(){if(!this._app)throw new za(Ka.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new za(Ka.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Ff(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Ja;switch(e.type){case"gapi":const t=e.client;return $a(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new Ya(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new za(Ka.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Lf.get(e);t&&(Fa("ComponentProvider","Removing Datastore"),Lf.delete(e),t.terminate())}(this),Promise.resolve()}}class jf{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Bf(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new jf(this.firestore,e,this._key)}}class qf{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new qf(this.firestore,e,this._query)}}class Bf extends qf{constructor(e,t,n){super(e,t,lu(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new jf(this.firestore,null,new kc(e))}withConverter(e){return new Bf(this.firestore,e,this._path)}}function $f(e,t,...n){if(e=w(e),1===arguments.length&&(t=rc.A()),Of("doc","path",t),e instanceof Vf){const r=dc.fromString(t,...n);return Pf(r),new jf(e,null,new kc(r))}{if(!(e instanceof jf||e instanceof Bf))throw new za(Ka.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(dc.fromString(t,...n));return Pf(r),new jf(e.firestore,e instanceof Bf?e.converter:null,new kc(r))}}class Hf{constructor(){this.ma=Promise.resolve(),this.ga=[],this.ya=!1,this.pa=[],this.Ta=null,this.Ea=!1,this.Ia=!1,this.Aa=[],this.ur=new od(this,"async_queue_retry"),this.Ra=()=>{const e=id();e&&Fa("AsyncQueue","Visibility state changed to "+e.visibilityState),this.ur.er()};const e=id();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Ra)}get isShuttingDown(){return this.ya}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Pa(),this.ba(e)}enterRestrictedMode(e){if(!this.ya){this.ya=!0,this.Ia=e||!1;const t=id();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Ra)}}enqueue(e){if(this.Pa(),this.ya)return new Promise((()=>{}));const t=new Ga;return this.ba((()=>this.ya&&this.Ia?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.ga.push(e),this.va())))}async va(){if(0!==this.ga.length){try{await this.ga[0](),this.ga.shift(),this.ur.reset()}catch(e){if(!Th(e))throw e;Fa("AsyncQueue","Operation failed with retryable error: "+e)}this.ga.length>0&&this.ur.Zi((()=>this.va()))}}ba(e){const t=this.ma.then((()=>(this.Ea=!0,e().catch((e=>{this.Ta=e,this.Ea=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw Va("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.Ea=!1,e))))));return this.ma=t,t}enqueueAfterDelay(e,t,n){this.Pa(),this.Aa.indexOf(e)>-1&&(t=0);const r=Vd.createAndSchedule(this,e,t,n,(e=>this.Va(e)));return this.pa.push(r),r}Pa(){this.Ta&&Ba()}verifyOperationInProgress(){}async Sa(){let e;do{e=this.ma,await e}while(e!==this.ma)}Da(e){for(const t of this.pa)if(t.timerId===e)return!0;return!1}Ca(e){return this.Sa().then((()=>{this.pa.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.pa)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Sa()}))}Na(e){this.Aa.push(e)}Va(e){const t=this.pa.indexOf(e);this.pa.splice(t,1)}}function Kf(e){return function(e,t){if("object"!=typeof e||null===e)return!1;const n=e;for(const e of["next","error","complete"])if(e in n&&"function"==typeof n[e])return!0;return!1}(e)}class zf extends Vf{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new Hf,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||Wf(this),this._firestoreClient.terminate()}}function Gf(e){return e._firestoreClient||Wf(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Wf(e){var t;const n=e._freezeSettings(),r=function(e,t,n,r){return new Rf(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,n);e._firestoreClient=new kf(e._authCredentials,e._appCheckCredentials,e._queue,r)}class Jf{constructor(...e){for(let t=0;t90)throw new za(Ka.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new za(Ka.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return ic(this._lat,e._lat)||ic(this._long,e._long)}}const Zf=/^__.*__$/;class ep{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Ju(e,this.data,this.fieldMask,t,this.fieldTransforms):new Wu(e,this.data,t,this.fieldTransforms)}}function tp(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Ba()}}class np{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.k=n,this.ignoreUndefinedProperties=r,void 0===i&&this.ka(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get xa(){return this.settings.xa}$a(e){return new np(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.k,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Fa(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$a({path:n,Oa:!1});return r.Ma(e),r}La(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$a({path:n,Oa:!1});return r.ka(),r}Ba(e){return this.$a({path:void 0,Oa:!0})}Ua(e){return fp(e,this.settings.methodName,this.settings.qa||!1,this.path,this.settings.Ka)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}ka(){if(this.path)for(let e=0;ec.covers(e.field)))}else c=null,u=o.fieldTransforms;return new ep(new jc(a),c,u)}function op(e,t){if(cp(e=w(e)))return up("Unsupported field value:",t,e),ap(e,t);if(e instanceof Qf)return function(e,t){if(!tp(t.xa))throw t.Ua(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Ua(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Oa&&4!==t.xa)throw t.Ua("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=op(i,t.Ba(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=w(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ku(t.k,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=oc.fromDate(e);return{timestampValue:Dl(t.k,n)}}if(e instanceof oc){const n=new oc(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Dl(t.k,n)}}if(e instanceof Yf)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Xf)return{bytesValue:Ll(t.k,e._byteString)};if(e instanceof jf){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.Ua(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:Ml(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Ua(`Unsupported field value: ${xf(e)}`)}(e,t)}function ap(e,t){const n={};return lc(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):uc(e,((e,r)=>{const i=op(r,t.Fa(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function cp(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof oc||e instanceof Yf||e instanceof Xf||e instanceof jf||e instanceof Qf)}function up(e,t,n){if(!cp(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=xf(n);throw"an object"===r?t.Ua(e+" a custom object"):t.Ua(e+" "+r)}}function lp(e,t,n){if((t=w(t))instanceof Jf)return t._internalPath;if("string"==typeof t)return dp(e,t);throw fp("Field path arguments must be of type string or FieldPath.",e,!1,void 0,n)}const hp=new RegExp("[~\\*/\\[\\]]");function dp(e,t,n){if(t.search(hp)>=0)throw fp(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new Jf(...t.split("."))._internalPath}catch(r){throw fp(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function fp(e,t,n,r,i){const s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new za(Ka.INVALID_ARGUMENT,a+e+c)}function pp(e,t){return e.some((e=>e.isEqual(t)))}class mp{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new jf(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new gp(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(yp("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class gp extends mp{data(){return super.data()}}function yp(e,t){return"string"==typeof t?dp(e,t):t instanceof Jf?t._internalPath:t._delegate._internalPath}class vp{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class wp extends mp{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new Tp(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){const n=this._document.data.field(yp("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Tp extends wp{data(e={}){return super.data(e)}}class Ip{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new vp(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Tp(this._firestore,this._userDataWriter,n.key,n,new vp(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new za(Ka.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>({type:"added",doc:new Tp(e._firestore,e._userDataWriter,n.doc.key,n.doc,new vp(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter),oldIndex:-1,newIndex:t++})))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Tp(e._firestore,e._userDataWriter,t.doc.key,t.doc,new vp(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:Ep(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Ep(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Ba()}}class bp{}class _p extends bp{constructor(e,t){super(),this.Ga=e,this.Ja=t,this.type="orderBy"}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new za(Ka.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new za(Ka.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const r=new su(t,n);return function(e,t){if(null===fu(e)){const n=pu(e);null!==n&&function(e,t,n){if(!n.isEqual(t))throw new za(Ka.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}(0,n,t.field)}}(e,r),r}(e._query,this.Ga,this.Ja);return new qf(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new uu(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class Sp extends bp{constructor(e,t,n){super(),this.type=e,this.Ya=t,this.Xa=n}_apply(e){return new qf(e.firestore,e.converter,yu(e._query,this.Ya,this.Xa))}}class kp extends class{convertValue(e,t="none"){switch(Ac(e)){case 0:return null;case 1:return e.booleanValue;case 2:return wc(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Tc(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw Ba()}}convertObject(e,t){const n={};return uc(e.fields,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new Yf(wc(e.latitude),wc(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=Ec(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(bc(e));default:return null}}convertTimestamp(e){const t=vc(e);return new oc(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=dc.fromString(e);$a(nh(n));const r=new Df(n.get(1),n.get(3)),i=new kc(n.popFirst(5));return r.isEqual(t)||Va(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}{constructor(e){super(),this.firestore=e}convertBytes(e){return new Xf(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new jf(this.firestore,null,t)}}function Ap(e,t){return function(e,t){const n=new Ga;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=Ef(e);try{const e=await function(e,t){const n=Ha(e),r=oc.now(),i=t.reduce(((e,t)=>e.add(t.key)),gl());let s;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>n.Wn.vn(e,i).next((i=>{s=i;const o=[];for(const e of t){const t=Ku(e,s.get(e.key));null!=t&&o.push(new Ju(e.key,t,qc(t.value.mapValue),ju.exists(!0)))}return n.An.addMutationBatch(e,r,o,t)})))).then((e=>(e.applyToLocalDocumentSet(s),{batchId:e.batchId,changes:s})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Ko[e.currentUser.toKey()];r||(r=new sl(ic)),r=r.insert(t,n),e.Ko[e.currentUser.toKey()]=r}(r,e.batchId,n),await wf(r,e.changes),await Cd(r.remoteStore)}catch(e){const t=jd(e,"Failed to persist write");n.reject(t)}}(await function(e){return Cf(e).then((e=>e.syncEngine))}(e),t,n))),n.promise}(Gf(e),t)}function Cp(e,t,n){const r=n.docs.get(t._key),i=new kp(e);return new wp(e,i,t._key,r,new vp(n.hasPendingWrites,n.fromCache),t.converter)}!function(e,t=!0){Ma="9.6.1",j(new T("firestore",((e,{options:n})=>{const r=e.getProvider("app").getImmediate(),i=new zf(r,new Xa(e.getProvider("auth-internal")),new ec(e.getProvider("app-check-internal")));return n=Object.assign({useFetchStreams:t},n),i._setSettings(n),i}),"PUBLIC")),z(Oa,"3.4.1",e),z(Oa,"3.4.1","esm2017")}();const Np=document.querySelector("body"),Rp=document.querySelector(".saveStats"),Dp=document.querySelector(".profile>.routs>.signUp"),Lp=document.querySelector(".windowTop>.options>.signupBtn"),Op=document.querySelector(".profileBtn"),Pp=document.querySelector(".profile"),Mp=document.querySelectorAll(".options>.close"),xp=document.querySelectorAll(".windowTop>.move"),Up=document.querySelector(".settingsBtn"),Fp=document.querySelector(".settings"),Vp=document.querySelector(".themeSelector"),jp=document.querySelector(".profile>.routs"),qp=document.querySelector(".text"),Bp=document.querySelector(".stats"),$p=document.querySelector(".containerStats>.speed"),Hp=document.querySelector(".loginBtn"),Kp=document.querySelector(".profile>.routs>.signIn"),zp=document.querySelector(".updateBtn"),Gp=document.querySelector(".profile>.routs>.update"),Wp=document.querySelector(".logoutBtn"),Jp=document.querySelector(".info"),Xp=document.querySelector(".loader"),Qp=(document.querySelector(".options"),document.querySelector(".leaderBoard")),Yp=document.querySelector(".leaderBoard>.content"),Zp=document.querySelector(".leaderBoardBtn"),em=document.querySelector(".container>.info"),tm=document.querySelector(".username"),nm=document.querySelector(".textOptions"),rm=document.querySelector(".nextBtn"),im=document.querySelector(".infoPopup");function sm(e,t){if(t){let n=`${e}${t.userName}${t.speed}`,r=document.createElement("li");r.innerHTML=n,r.classList.add("leaderBoardListItem"),Yp.appendChild(r)}}const om=function(e=K()){return q(e,"firestore").getImmediate()}(Xe),am=async()=>{let e=Ir(),t=e.currentUser&&e.currentUser.uid;if(t){const e=$f(om,`scores/${t}`);let n=e&&await function(e){e=Uf(e,jf);const t=Uf(e.firestore,zf);return function(e,t,n={}){const r=new Ga;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new Sf({next:s=>{t.enqueueAndForget((()=>Gd(e,o)));const a=s.docs.has(n);!a&&s.fromCache?i.reject(new za(Ka.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&s.fromCache&&r&&"server"===r.source?i.reject(new za(Ka.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):i.resolve(s)},error:e=>i.reject(e)}),o=new Qd(lu(n.path),s,{includeMetadataChanges:!0,wo:!0});return zd(e,o)}(await Nf(e),e.asyncQueue,t,n,r))),r.promise}(Gf(t),e._key).then((n=>Cp(t,e,n)))}(e);return n.exists()?n.data():null}return null},cm=e=>{(function(e,t,n){e=Uf(e,jf);const r=Uf(e.firestore,zf),i=function(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}(e.converter,t,n);return Ap(r,[sp(ip(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,ju.none())])})($f(om,`scores/${e.uId}`),e,{merge:!0}).then(console.log("added successfully")).catch((e=>console.error("I got an error",e)))};let um;const lm="user.data";async function hm(){return navigator.onLine?await am():JSON.parse(localStorage.getItem(lm))}function dm(){return JSON.parse(localStorage.getItem(lm))}function fm(e){return localStorage.setItem(lm,JSON.stringify(e)),e}function pm(e){return localStorage.setItem(lm,JSON.stringify(e)),cm(e),e}var mm;function gm(e,t){im.classList.toggle("hide"),im.classList.remove("fadeOut"),im.innerHTML=e,setTimeout((()=>{im.classList.add("fadeOut"),setTimeout((()=>{im.classList.add("hide")}),200)}),t),document.addEventListener("click",(()=>{im.classList.contains("hide")||(im.classList.add("fadeOut"),setTimeout((()=>{im.classList.add("hide")}),200))}))}var ym;let vm=0;const wm=async()=>{await hm()||(vm++,5!=vm&&15!=vm||gm("Login to save data 🙂",1e4));let e=await fetch("https://api.quotable.io/random").then((e=>e.json())).then((e=>e.content)).catch((e=>{console.error(e.message),qp.innerText="check your network connection"})),t=dm();t.punctuationMode||(e=e.replace(/[^ \w]/g,"")),t.smallCaseMode&&(e=e.toLowerCase()),ym=qp.innerText=e,Om(),Nm(qp),(e=>{let t,n,r=!0,i=e,s=0,o=0,a=document.querySelectorAll(".text>span");a[s].classList.add("blink"),document.addEventListener("keypress",(c=>{c.key===i[0]?(r&&(t=(new Date).getTime(),r=!1),i=i.substr(1),a[s].classList.add("correctWord"),a[s].classList.remove("blink"),s{let n=e/(t.toPrecision(2)/60);mm=Math.floor(n.toPrecision(3)),$p.innerText=mm;let r=await hm();r&&mm>r.topSpeed?(r={...r,topSpeed:mm},console.log("setUserData called"),pm(r)):r&&fm({...r,lastSpeed:mm}),em.classList.toggle("hide"),em.classList.toggle("fadeOut"),setTimeout((()=>{wm(),em.classList.toggle("fadeOut"),setTimeout((()=>{em.classList.toggle("hide")}),500)}),500)})(Am,(n-t)/1e3)),s++):null!=a[s]&&a[s].classList.add("wrongWord")}))})(ym)};function Tm(e){e?(Wp.classList.remove("hide"),zp.classList.remove("hide"),Lp.classList.add("hide"),Hp.classList.add("hide")):(Wp.classList.add("hide"),zp.classList.add("hide"),Lp.classList.remove("hide"),Hp.classList.remove("hide"))}Tm();const Im=(e,t)=>{jp.childNodes.forEach((n=>{n.classList&&(n==e?(n.classList.remove("hide"),n.classList.contains("stats")&&t?Rp.classList.remove("hide"):Rp.classList.add("hide")):!n.classList.contains("hide")&&n.classList.add("hide"))}))};n(162);var Em=n(306),bm=n.n(Em);let _m=!1,Sm=!0,km="dark";var Am;const Cm=document.querySelector(".words"),Nm=e=>{let t=[];for(let e=0;e${ym[e]}`);let n=t.join("");e.innerHTML=n};Op.addEventListener("click",(async()=>{if(Pp.classList.contains("hide")){Pp.classList.toggle("hide");let e=await hm();Tm(e),!e||0===Object.entries(e).length&&e.constructor===Object?Im(Jp):(Dm(e),zp.classList.remove("hide"),Lp.classList.add("hide"))}else Pp.classList.add("hide")})),Mp.forEach((e=>{e.addEventListener("click",(e=>{let t=e.target.parentElement.parentElement.parentElement;Im(Xp),t.classList.toggle("hide")}))})),xp.forEach((e=>{e.addEventListener("drag",(e=>{e.target.parentElement.parentElement.style.filter="brightness(.7)"}))})),xp.forEach((e=>{e.addEventListener("dragend",(e=>{let t=e.target.parentElement.parentElement;t.style.filter="brightness(1)",Rm(e,t)}))}));const Rm=(e,t)=>{t.style.left=e.pageX-20+"px",t.style.top=e.pageY-20+"px"},Dm=async e=>(!e||0===Object.entries(e).length&&e.constructor===Object?Im(Jp):(Bp.lastElementChild.lastElementChild.childNodes.forEach((t=>{t.classList&&(t.classList.contains("name")?(e.userName.length>10?t.style.fontSize=20:e.userName.length>20&&(t.style.fontSize=15),t.innerHTML=e.userName):t.classList.contains("speed")&&(e.userName.length>10&&(t.style.fontSize=30),t.innerHTML=e.topSpeed))})),Im(Bp,e)),e);Up.addEventListener("click",(()=>{Fp.classList.toggle("hide")})),Vp.addEventListener("change",(async e=>{let t=await hm();if(e.target.options.light.selected){if(Np.classList.contains("light"))return;Np.classList.remove("dark"),Np.classList.add("light"),t?pm({...t,theme:"light"}):(t=dm(),fm({...t,theme:"light"}))}else if(e.target.options.dark.selected){if(Np.classList.contains("dark"))return;Np.classList.remove("light"),Np.classList.add("dark"),t?pm({...t,theme:"dark"}):(t=dm(),fm({...t,theme:"dark"}))}})),Rp.addEventListener("click",(()=>{bm().toBlob(Bp).then((e=>{window.saveAs(e,"stats.png")}))})),Dp.addEventListener("submit",(e=>{e.preventDefault(),xm({email:e.target.email.value,username:e.target.username.value,password:e.target.password.value}),Im(Xp)})),Kp.addEventListener("submit",(e=>{e.preventDefault(),Mm({email:e.target.email.value,password:e.target.password.value}),Im(Xp)})),Lp.addEventListener("click",(()=>{Im(Dp)})),Hp.addEventListener("click",(()=>{Im(Kp)})),Wp.addEventListener("click",(()=>{Um()})),zp.addEventListener("click",(()=>{Im(Gp)})),Gp.addEventListener("submit",(e=>{e.preventDefault();let t=e.target.username.value;t&&" "!=t[0]&&t.length>0?Fm(t):console.log("enter username",t)})),Zp.addEventListener("click",(()=>{Yp.parentElement.classList.contains("hide")?(Yp.parentElement.classList.toggle("hide"),setTimeout((()=>{Yp.parentElement.classList.toggle("fadeOut")}),200)):(Yp.parentElement.classList.toggle("fadeOut"),setTimeout((()=>{Yp.parentElement.classList.toggle("hide")}),500))})),Qp.addEventListener("click",(e=>{e.target.classList.contains("leaderBoard")&&(Qp.classList.toggle("fadeOut"),setTimeout((()=>{Qp.classList.toggle("hide")}),200))})),nm.addEventListener("click",(async e=>{let t=await hm();e.target.classList.contains("smallCase")?(e.target.classList.contains("active")?(_m=!1,e.target.classList.remove("active")):(_m=!0,e.target.classList.add("active")),t?pm({...t,smallCaseMode:_m}):(t=dm(),fm({...t,smallCaseMode:_m}))):e.target.classList.contains("punctuation")&&(e.target.classList.contains("active")?(Sm=!1,e.target.classList.remove("active")):(Sm=!0,e.target.classList.add("active")),t?pm({...t,punctuationMode:Sm}):(t=dm(),fm({...t,punctuationMode:Sm})))})),rm.addEventListener("click",(()=>{wm()}));let Lm=!0;document.addEventListener("keypress",(e=>{e.getModifierState("CapsLock")&&Lm&&gm("CapsLock",2e3),Lm=!1}));const Om=(e=0)=>{let t,n=/ /g,r=[];for(;t=n.exec(ym);)r.push(t.index);Am=r.length+1,Cm.innerText=`${Am}/${e}`},Pm=Ir(Xe),Mm=async({email:e,password:t})=>{try{await function(e,t,n){return async function(e,t){return yn(Xt(e),t)}(w(e),on.credential(t,n))}(Pm,e,t)}catch(e){alert(e.code)}},xm=async({email:e,password:t,username:n})=>{try{const r=await async function(e,t,n){const r=Xt(e),i=await async function(e,t){return Tt(e,"POST","/v1/accounts:signUp",yt(e,t))}(r,{returnSecureToken:!0,email:t,password:n}),s=await fn._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(s.user),s}(Pm,e,t);await vn(r.user,{displayName:n||r.email.split("@")[0]}).then((()=>{console.log("updated the name"),pm({uId:r.user.uid,userName:r.user.displayName,topSpeed:0,theme:km,punctuationMode:Sm,smallCaseMode:_m,lastSpeed:0})}))}catch(e){alert(e.code)}},Um=()=>{try{!function(e){w(e).signOut()}(Pm),console.log("user logged out")}catch(e){alert(e.code)}},Fm=async e=>{try{let t=Pm.currentUser;Im(Xp),await vn(t,{displayName:e}).then((()=>{console.log("updated the name"),function(e){cm(e);let t=getUserTheme();localStorage.setItem(lm,JSON.stringify({...t,userName:e.username}))}({uId:t.uid,userName:t.displayName}),hm().then((e=>{Dm(e)}))}))}catch(e){alert("check your network")}};window.onload=()=>{if(dm()){let e=dm().theme;"dark"!=e&&(Np.classList.remove("dark"),Np.classList.add(e)),Vp.options[e].selected=!0,dm().punctuationMode?nm.children[0].classList.add("active"):nm.children[0].classList.remove("active"),dm().smallCaseMode?nm.children[1].classList.add("active"):nm.children[1].classList.remove("active"),function(e){e&&($p.innerText=e)}(dm().lastSpeed)}else fm({punctuationMode:Sm,smallCaseMode:_m,theme:km})},wm(),function(e,t,n,r){w(e).onAuthStateChanged((async e=>{e?(Tm(e=await hm()),Dm(e),tm.innerText=e.userName):(Tm(e),Dm(e),tm.innerText=" ")}),void 0,void 0)}(Pm),function(){const e=function(e,t,...n){if(e=w(e),Of("collection","path",t),e instanceof Vf){const r=dc.fromString(t,...n);return Mf(r),new Bf(e,null,r)}{if(!(e instanceof jf||e instanceof Bf))throw new za(Ka.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(dc.fromString(t,...n));return Mf(r),new Bf(e.firestore,null,r)}}(om,"scores"),t=function(e,...t){for(const n of t)e=n._apply(e);return e}(e,function(e,t="asc"){const n=t,r=yp("orderBy","topSpeed");return new _p(r,n)}(0,"desc"),(function(e,t){if(t<=0)throw new za(Ka.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}("limit",10),new Sp("limit",10,"F")));um=function(e,...t){var n,r,i;e=w(e);let s={includeMetadataChanges:!1},o=0;"object"!=typeof t[o]||Kf(t[o])||(s=t[o],o++);const a={includeMetadataChanges:s.includeMetadataChanges};if(Kf(t[o])){const e=t[o];t[o]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[o+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[o+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}let c,u,l;if(e instanceof jf)u=Uf(e.firestore,zf),l=lu(e._key.path),c={next:n=>{t[o]&&t[o](Cp(u,e,n))},error:t[o+1],complete:t[o+2]};else{const n=Uf(e,qf);u=Uf(n.firestore,zf),l=n._query;const r=new kp(u);c={next:e=>{t[o]&&t[o](new Ip(u,r,n,e))},error:t[o+1],complete:t[o+2]},function(e){if(du(e)&&0===e.explicitOrderBy.length)throw new za(Ka.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query)}return function(e,t,n,r){const i=new Sf(r),s=new Qd(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>zd(await Nf(e),s))),()=>{i.na(),e.asyncQueue.enqueueAndForget((async()=>Gd(await Nf(e),s)))}}(Gf(u),l,a,c)}(t,e,(e=>{if(e){const t=[];!function(){for(;Yp.firstChild;)Yp.firstChild.remove()}(),function(){let e=document.createElement("li");e.classList.add("leaderBoardHeader"),e.innerText="leaderboard";let t=document.createElement("li");t.classList.add("leaderBoardInfo"),t.innerHTML='RankUsernameTop Speed',Yp.appendChild(e),Yp.appendChild(t)}(),e.forEach((e=>{let n=e.data();n.topSpeed>0&&t.push({userName:n.userName,speed:n.topSpeed})}));for(let e=0;eTHEME +