@neurosity/sdk 6.5.4-next.0 → 6.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/neurosity.iife.js +4204 -4098
- package/dist/browser/neurosity.js +16 -16
- package/dist/browser/neurosity.js.map +1 -1
- package/dist/cjs/api/firebase/FirebaseUser.d.ts +6 -0
- package/dist/cjs/api/firebase/FirebaseUser.js +20 -7
- package/dist/cjs/api/firebase/deviceStore.js +7 -2
- package/dist/cjs/api/index.d.ts +2 -41
- package/dist/cjs/api/index.js +4 -1
- package/dist/electron/index.js +1 -1
- package/dist/electron/index.js.map +1 -1
- package/dist/esm/api/firebase/FirebaseUser.d.ts +6 -0
- package/dist/esm/api/firebase/FirebaseUser.js +20 -7
- package/dist/esm/api/firebase/deviceStore.js +7 -2
- package/dist/esm/api/index.d.ts +2 -41
- package/dist/esm/api/index.js +4 -1
- package/dist/esm/neurosity.mjs +4204 -4098
- package/dist/examples/neurosity.iife.js +4204 -4098
- package/dist/examples/neurosity.js +16 -16
- package/dist/examples/neurosity.mjs +4204 -4098
- package/package.json +2 -2
|
@@ -461,7 +461,7 @@ var t,e,n=module.exports={};function r(){throw new Error("setTimeout has not bee
|
|
|
461
461
|
},{}],"chA2":[function(require,module,exports) {
|
|
462
462
|
var global = arguments[3];
|
|
463
463
|
var process = require("process");
|
|
464
|
-
var t=arguments[3],e=require("process");Object.defineProperty(exports,"__esModule",{value:!0}),exports.Sha1=exports.RANDOM_FACTOR=exports.MAX_VALUE_MILLIS=exports.FirebaseError=exports.ErrorFactory=exports.Deferred=exports.CONSTANTS=void 0,exports.areCookiesEnabled=R,exports.assertionError=exports.assert=void 0,exports.async=ut,exports.base64urlEncodeWithoutPadding=exports.base64Encode=exports.base64Decode=exports.base64=void 0,exports.calculateBackoffMillis=Ot,exports.contains=Q,exports.createMockUserToken=S,exports.createSubscribe=ct,exports.decode=void 0,exports.deepCopy=f,exports.deepEqual=et,exports.deepExtend=l,exports.errorPrefix=dt,exports.extractQuerystring=it,exports.getExperimentalSetting=exports.getDefaults=exports.getDefaultEmulatorHostnameAndPort=exports.getDefaultEmulatorHost=exports.getDefaultAppConfig=void 0,exports.getGlobal=d,exports.getModularInstance=Dt,exports.getUA=O,exports.isAdmin=void 0,exports.isBrowser=D,exports.isBrowserExtension=T,exports.isElectron=M,exports.isEmpty=Z,exports.isIE=j,exports.isIndexedDBAvailable=P,exports.isMobileCordova=C,exports.isNode=w,exports.isNodeSdk=B,exports.isReactNative=N,exports.isSafari=I,exports.isUWP=k,exports.issuedAtTime=exports.isValidTimestamp=exports.isValidFormat=void 0,exports.jsonEval=z,exports.map=tt,exports.ordinal=Ct,exports.promiseWithTimeout=ot,exports.querystring=nt,exports.querystringDecode=st,exports.safeGet=Y,exports.stringToByteArray=exports.stringLength=void 0,exports.stringify=H,exports.validateArgCount=exports.uuidv4=void 0,exports.validateCallback=xt,exports.validateContextObject=_t,exports.validateIndexedDBOpenable=L,exports.validateNamespace=bt;const r={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};exports.CONSTANTS=r;const o=function(t,e){if(!t)throw n(e)};exports.assert=o;const n=function(t){return new Error("Firebase Database ("+r.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};exports.assertionError=n;const s=function(t){const e=[];let r=0;for(let o=0;o<t.length;o++){let n=t.charCodeAt(o);n<128?e[r++]=n:n<2048?(e[r++]=n>>6|192,e[r++]=63&n|128):55296==(64512&n)&&o+1<t.length&&56320==(64512&t.charCodeAt(o+1))?(n=65536+((1023&n)<<10)+(1023&t.charCodeAt(++o)),e[r++]=n>>18|240,e[r++]=n>>12&63|128,e[r++]=n>>6&63|128,e[r++]=63&n|128):(e[r++]=n>>12|224,e[r++]=n>>6&63|128,e[r++]=63&n|128)}return e},i=function(t){const e=[];let r=0,o=0;for(;r<t.length;){const n=t[r++];if(n<128)e[o++]=String.fromCharCode(n);else if(n>191&&n<224){const s=t[r++];e[o++]=String.fromCharCode((31&n)<<6|63&s)}else if(n>239&&n<365){const s=((7&n)<<18|(63&t[r++])<<12|(63&t[r++])<<6|63&t[r++])-65536;e[o++]=String.fromCharCode(55296+(s>>10)),e[o++]=String.fromCharCode(56320+(1023&s))}else{const s=t[r++],i=t[r++];e[o++]=String.fromCharCode((15&n)<<12|(63&s)<<6|63&i)}}return e.join("")},a={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(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,o=[];for(let n=0;n<t.length;n+=3){const e=t[n],s=n+1<t.length,i=s?t[n+1]:0,a=n+2<t.length,c=a?t[n+2]:0,h=e>>2,u=(3&e)<<4|i>>4;let f=(15&i)<<2|c>>6,l=63&c;a||(l=64,s||(f=64)),o.push(r[h],r[u],r[f],r[l])}return o.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(s(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):i(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const r=e?this.charToByteMapWebSafe_:this.charToByteMap_,o=[];for(let n=0;n<t.length;){const e=r[t.charAt(n++)],s=n<t.length?r[t.charAt(n)]:0,i=++n<t.length?r[t.charAt(n)]:64,a=++n<t.length?r[t.charAt(n)]:64;if(++n,null==e||null==s||null==i||null==a)throw Error();const c=e<<2|s>>4;if(o.push(c),64!==i){const t=s<<4&240|i>>2;if(o.push(t),64!==a){const t=i<<6&192|a;o.push(t)}}}return o},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};exports.base64=a;const c=function(t){const e=s(t);return a.encodeByteArray(e,!0)};exports.base64Encode=c;const h=function(t){return c(t).replace(/\./g,"")};exports.base64urlEncodeWithoutPadding=h;const u=function(t){try{return a.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function f(t){return l(void 0,t)}function l(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return e}for(const r in e)e.hasOwnProperty(r)&&p(r)&&(t[r]=l(t[r],e[r]));return t}function p(t){return"__proto__"!==t}function d(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t)return t;throw new Error("Unable to locate global object.")}exports.base64Decode=u;const b=()=>d().__FIREBASE_DEFAULTS__,x=()=>{if(void 0===e||void 0===e.env)return},_=()=>{if("undefined"==typeof document)return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(r){return}const e=t&&u(t[1]);return e&&JSON.parse(e)},g=()=>{try{return b()||x()||_()}catch(t){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`)}};exports.getDefaults=g;const y=t=>{var e,r;return null===(r=null===(e=g())||void 0===e?void 0:e.emulatorHosts)||void 0===r?void 0:r[t]};exports.getDefaultEmulatorHost=y;const v=t=>{const e=y(t);if(!e)return;const r=e.lastIndexOf(":");if(r<=0||r+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const o=parseInt(e.substring(r+1),10);return"["===e[0]?[e.substring(1,r-1),o]:[e.substring(0,r),o]};exports.getDefaultEmulatorHostnameAndPort=v;const E=()=>{var t;return null===(t=g())||void 0===t?void 0:t.config};exports.getDefaultAppConfig=E;const m=t=>{var e;return null===(e=g())||void 0===e?void 0:e[`_${t}`]};exports.getExperimentalSetting=m;class A{constructor(){this.reject=(()=>{}),this.resolve=(()=>{}),this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}wrapCallback(t){return(e,r)=>{e?this.reject(e):this.resolve(r),"function"==typeof t&&(this.promise.catch(()=>{}),1===t.length?t(e):t(e,r))}}}function S(t,e){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const r=e||"demo-project",o=t.iat||0,n=t.sub||t.user_id;if(!n)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:o,exp:o+3600,auth_time:o,sub:n,user_id:n,firebase:{sign_in_provider:"custom",identities:{}}},t);return[h(JSON.stringify({alg:"none",type:"JWT"})),h(JSON.stringify(s)),""].join(".")}function O(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function C(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(O())}function w(){var e;const r=null===(e=g())||void 0===e?void 0:e.forceEnvironment;if("node"===r)return!0;if("browser"===r)return!1;try{return"[object process]"===Object.prototype.toString.call(t.process)}catch(o){return!1}}function D(){return"object"==typeof self&&self.self===self}function T(){const t="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof t&&void 0!==t.id}function N(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function M(){return O().indexOf("Electron/")>=0}function j(){const t=O();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}function k(){return O().indexOf("MSAppHost/")>=0}function B(){return!0===r.NODE_CLIENT||!0===r.NODE_ADMIN}function I(){return!w()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function P(){try{return"object"==typeof indexedDB}catch(t){return!1}}function L(){return new Promise((t,e)=>{try{let o=!0;const n="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(n);s.onsuccess=(()=>{s.result.close(),o||self.indexedDB.deleteDatabase(n),t(!0)}),s.onupgradeneeded=(()=>{o=!1}),s.onerror=(()=>{var t;e((null===(t=s.error)||void 0===t?void 0:t.message)||"")})}catch(r){e(r)}})}function R(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}exports.Deferred=A;const V="FirebaseError";class F extends Error{constructor(t,e,r){super(e),this.code=t,this.customData=r,this.name=V,Object.setPrototypeOf(this,F.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,U.prototype.create)}}exports.FirebaseError=F;class U{constructor(t,e,r){this.service=t,this.serviceName=e,this.errors=r}create(t,...e){const r=e[0]||{},o=`${this.service}/${t}`,n=this.errors[t],s=n?W(n,r):"Error",i=`${this.serviceName}: ${s} (${o}).`;return new F(o,i,r)}}function W(t,e){return t.replace($,(t,r)=>{const o=e[r];return null!=o?String(o):`<${r}?>`})}exports.ErrorFactory=U;const $=/\{\$([^}]+)}/g;function z(t){return JSON.parse(t)}function H(t){return JSON.stringify(t)}const J=function(t){let e={},r={},o={},n="";try{const i=t.split(".");e=z(u(i[0])||""),r=z(u(i[1])||""),n=i[2],o=r.d||{},delete r.d}catch(s){}return{header:e,claims:r,data:o,signature:n}};exports.decode=J;const q=function(t){const e=J(t).claims,r=Math.floor((new Date).getTime()/1e3);let o=0,n=0;return"object"==typeof e&&(e.hasOwnProperty("nbf")?o=e.nbf:e.hasOwnProperty("iat")&&(o=e.iat),n=e.hasOwnProperty("exp")?e.exp:o+86400),!!r&&!!o&&!!n&&r>=o&&r<=n};exports.isValidTimestamp=q;const G=function(t){const e=J(t).claims;return"object"==typeof e&&e.hasOwnProperty("iat")?e.iat:null};exports.issuedAtTime=G;const K=function(t){const e=J(t).claims;return!!e&&"object"==typeof e&&e.hasOwnProperty("iat")};exports.isValidFormat=K;const X=function(t){const e=J(t).claims;return"object"==typeof e&&!0===e.admin};function Q(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Y(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function Z(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function tt(t,e,r){const o={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(o[n]=e.call(r,t[n],n,t));return o}function et(t,e){if(t===e)return!0;const r=Object.keys(t),o=Object.keys(e);for(const n of r){if(!o.includes(n))return!1;const r=t[n],s=e[n];if(rt(r)&&rt(s)){if(!et(r,s))return!1}else if(r!==s)return!1}for(const n of o)if(!r.includes(n))return!1;return!0}function rt(t){return null!==t&&"object"==typeof t}function ot(t,e=2e3){const r=new A;return setTimeout(()=>r.reject("timeout!"),e),t.then(r.resolve,r.reject),r.promise}function nt(t){const e=[];for(const[r,o]of Object.entries(t))Array.isArray(o)?o.forEach(t=>{e.push(encodeURIComponent(r)+"="+encodeURIComponent(t))}):e.push(encodeURIComponent(r)+"="+encodeURIComponent(o));return e.length?"&"+e.join("&"):""}function st(t){const e={};return t.replace(/^\?/,"").split("&").forEach(t=>{if(t){const[r,o]=t.split("=");e[decodeURIComponent(r)]=decodeURIComponent(o)}}),e}function it(t){const e=t.indexOf("?");if(!e)return"";const r=t.indexOf("#",e);return t.substring(e,r>0?r:void 0)}exports.isAdmin=X;class at{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let t=1;t<this.blockSize;++t)this.pad_[t]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(t,e){e||(e=0);const r=this.W_;if("string"==typeof t)for(let u=0;u<16;u++)r[u]=t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|t.charCodeAt(e+3),e+=4;else for(let u=0;u<16;u++)r[u]=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],e+=4;for(let u=16;u<80;u++){const t=r[u-3]^r[u-8]^r[u-14]^r[u-16];r[u]=4294967295&(t<<1|t>>>31)}let o,n,s=this.chain_[0],i=this.chain_[1],a=this.chain_[2],c=this.chain_[3],h=this.chain_[4];for(let u=0;u<80;u++){u<40?u<20?(o=c^i&(a^c),n=1518500249):(o=i^a^c,n=1859775393):u<60?(o=i&a|c&(i|a),n=2400959708):(o=i^a^c,n=3395469782);const t=(s<<5|s>>>27)+o+h+n+r[u]&4294967295;h=c,c=a,a=4294967295&(i<<30|i>>>2),i=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+i&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+h&4294967295}update(t,e){if(null==t)return;void 0===e&&(e=t.length);const r=e-this.blockSize;let o=0;const n=this.buf_;let s=this.inbuf_;for(;o<e;){if(0===s)for(;o<=r;)this.compress_(t,o),o+=this.blockSize;if("string"==typeof t){for(;o<e;)if(n[s]=t.charCodeAt(o),++o,++s===this.blockSize){this.compress_(n),s=0;break}}else for(;o<e;)if(n[s]=t[o],++o,++s===this.blockSize){this.compress_(n),s=0;break}}this.inbuf_=s,this.total_+=e}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let o=this.blockSize-1;o>=56;o--)this.buf_[o]=255&e,e/=256;this.compress_(this.buf_);let r=0;for(let o=0;o<5;o++)for(let e=24;e>=0;e-=8)t[r]=this.chain_[o]>>e&255,++r;return t}}function ct(t,e){const r=new ht(t,e);return r.subscribe.bind(r)}exports.Sha1=at;class ht{constructor(t,e){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then(()=>{t(this)}).catch(t=>{this.error(t)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,r){let o;if(void 0===t&&void 0===e&&void 0===r)throw new Error("Missing Observer.");void 0===(o=ft(t,["next","error","complete"])?t:{next:t,error:e,complete:r}).next&&(o.next=lt),void 0===o.error&&(o.error=lt),void 0===o.complete&&(o.complete=lt);const n=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?o.error(this.finalError):o.complete()}catch(t){}}),this.observers.push(o),n}unsubscribeOne(t){void 0!==this.observers&&void 0!==this.observers[t]&&(delete this.observers[t],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(t,e){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[t])try{e(this.observers[t])}catch(r){"undefined"!=typeof console&&console.error&&console.error(r)}})}close(t){this.finalized||(this.finalized=!0,void 0!==t&&(this.finalError=t),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function ut(t,e){return(...r)=>{Promise.resolve(!0).then(()=>{t(...r)}).catch(t=>{e&&e(t)})}}function ft(t,e){if("object"!=typeof t||null===t)return!1;for(const r of e)if(r in t&&"function"==typeof t[r])return!0;return!1}function lt(){}const pt=function(t,e,r,o){let n;if(o<e?n="at least "+e:o>r&&(n=0===r?"none":"no more than "+r),n){throw new Error(t+" failed: Was called with "+o+(1===o?" argument.":" arguments.")+" Expects "+n+".")}};function dt(t,e){return`${t} failed: ${e} argument `}function bt(t,e,r){if((!r||e)&&"string"!=typeof e)throw new Error(dt(t,"namespace")+"must be a valid firebase namespace.")}function xt(t,e,r,o){if((!o||r)&&"function"!=typeof r)throw new Error(dt(t,e)+"must be a valid function.")}function _t(t,e,r,o){if((!o||r)&&("object"!=typeof r||null===r))throw new Error(dt(t,e)+"must be a valid context object.")}exports.validateArgCount=pt;const gt=function(t){const e=[];let r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);if(s>=55296&&s<=56319){const e=s-55296;o(++n<t.length,"Surrogate pair missing trail surrogate."),s=65536+(e<<10)+(t.charCodeAt(n)-56320)}s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=63&s|128):s<65536?(e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=63&s|128):(e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=63&s|128)}return e};exports.stringToByteArray=gt;const yt=function(t){let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);o<128?e++:o<2048?e+=2:o>=55296&&o<=56319?(e+=4,r++):e+=3}return e};exports.stringLength=yt;const vt=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})};exports.uuidv4=vt;const Et=1e3,mt=2,At=144e5;exports.MAX_VALUE_MILLIS=At;const St=.5;function Ot(t,e=Et,r=mt){const o=e*Math.pow(r,t),n=Math.round(St*o*(Math.random()-.5)*2);return Math.min(At,o+n)}function Ct(t){return Number.isFinite(t)?t+wt(t):`${t}`}function wt(t){const e=(t=Math.abs(t))%100;if(e>=10&&e<=20)return"th";const r=t%10;return 1===r?"st":2===r?"nd":3===r?"rd":"th"}function Dt(t){return t&&t._delegate?t._delegate:t}exports.RANDOM_FACTOR=St;
|
|
464
|
+
var t=arguments[3],e=require("process");Object.defineProperty(exports,"__esModule",{value:!0}),exports.Sha1=exports.RANDOM_FACTOR=exports.MAX_VALUE_MILLIS=exports.FirebaseError=exports.ErrorFactory=exports.Deferred=exports.DecodeBase64StringError=exports.CONSTANTS=void 0,exports.areCookiesEnabled=V,exports.assertionError=exports.assert=void 0,exports.async=ft,exports.base64urlEncodeWithoutPadding=exports.base64Encode=exports.base64Decode=exports.base64=void 0,exports.calculateBackoffMillis=Ct,exports.contains=Y,exports.createMockUserToken=O,exports.createSubscribe=ht,exports.decode=void 0,exports.deepCopy=l,exports.deepEqual=rt,exports.deepExtend=p,exports.errorPrefix=bt,exports.extractQuerystring=at,exports.getExperimentalSetting=exports.getDefaults=exports.getDefaultEmulatorHostnameAndPort=exports.getDefaultEmulatorHost=exports.getDefaultAppConfig=void 0,exports.getGlobal=b,exports.getModularInstance=Tt,exports.getUA=C,exports.isAdmin=void 0,exports.isBrowser=T,exports.isBrowserExtension=N,exports.isElectron=j,exports.isEmpty=tt,exports.isIE=B,exports.isIndexedDBAvailable=L,exports.isMobileCordova=D,exports.isNode=w,exports.isNodeSdk=I,exports.isReactNative=M,exports.isSafari=P,exports.isUWP=k,exports.issuedAtTime=exports.isValidTimestamp=exports.isValidFormat=void 0,exports.jsonEval=H,exports.map=et,exports.ordinal=Dt,exports.promiseWithTimeout=nt,exports.querystring=st,exports.querystringDecode=it,exports.safeGet=Z,exports.stringToByteArray=exports.stringLength=void 0,exports.stringify=J,exports.validateArgCount=exports.uuidv4=void 0,exports.validateCallback=_t,exports.validateContextObject=gt,exports.validateIndexedDBOpenable=R,exports.validateNamespace=xt;const r={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};exports.CONSTANTS=r;const o=function(t,e){if(!t)throw n(e)};exports.assert=o;const n=function(t){return new Error("Firebase Database ("+r.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};exports.assertionError=n;const s=function(t){const e=[];let r=0;for(let o=0;o<t.length;o++){let n=t.charCodeAt(o);n<128?e[r++]=n:n<2048?(e[r++]=n>>6|192,e[r++]=63&n|128):55296==(64512&n)&&o+1<t.length&&56320==(64512&t.charCodeAt(o+1))?(n=65536+((1023&n)<<10)+(1023&t.charCodeAt(++o)),e[r++]=n>>18|240,e[r++]=n>>12&63|128,e[r++]=n>>6&63|128,e[r++]=63&n|128):(e[r++]=n>>12|224,e[r++]=n>>6&63|128,e[r++]=63&n|128)}return e},i=function(t){const e=[];let r=0,o=0;for(;r<t.length;){const n=t[r++];if(n<128)e[o++]=String.fromCharCode(n);else if(n>191&&n<224){const s=t[r++];e[o++]=String.fromCharCode((31&n)<<6|63&s)}else if(n>239&&n<365){const s=((7&n)<<18|(63&t[r++])<<12|(63&t[r++])<<6|63&t[r++])-65536;e[o++]=String.fromCharCode(55296+(s>>10)),e[o++]=String.fromCharCode(56320+(1023&s))}else{const s=t[r++],i=t[r++];e[o++]=String.fromCharCode((15&n)<<12|(63&s)<<6|63&i)}}return e.join("")},a={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(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,o=[];for(let n=0;n<t.length;n+=3){const e=t[n],s=n+1<t.length,i=s?t[n+1]:0,a=n+2<t.length,c=a?t[n+2]:0,h=e>>2,u=(3&e)<<4|i>>4;let f=(15&i)<<2|c>>6,l=63&c;a||(l=64,s||(f=64)),o.push(r[h],r[u],r[f],r[l])}return o.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(s(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):i(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const r=e?this.charToByteMapWebSafe_:this.charToByteMap_,o=[];for(let n=0;n<t.length;){const e=r[t.charAt(n++)],s=n<t.length?r[t.charAt(n)]:0,i=++n<t.length?r[t.charAt(n)]:64,a=++n<t.length?r[t.charAt(n)]:64;if(++n,null==e||null==s||null==i||null==a)throw new c;const h=e<<2|s>>4;if(o.push(h),64!==i){const t=s<<4&240|i>>2;if(o.push(t),64!==a){const t=i<<6&192|a;o.push(t)}}}return o},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};exports.base64=a;class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}exports.DecodeBase64StringError=c;const h=function(t){const e=s(t);return a.encodeByteArray(e,!0)};exports.base64Encode=h;const u=function(t){return h(t).replace(/\./g,"")};exports.base64urlEncodeWithoutPadding=u;const f=function(t){try{return a.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function l(t){return p(void 0,t)}function p(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return e}for(const r in e)e.hasOwnProperty(r)&&d(r)&&(t[r]=p(t[r],e[r]));return t}function d(t){return"__proto__"!==t}function b(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t)return t;throw new Error("Unable to locate global object.")}exports.base64Decode=f;const x=()=>b().__FIREBASE_DEFAULTS__,_=()=>{if(void 0===e||void 0===e.env)return},g=()=>{if("undefined"==typeof document)return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(r){return}const e=t&&f(t[1]);return e&&JSON.parse(e)},y=()=>{try{return x()||_()||g()}catch(t){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`)}};exports.getDefaults=y;const v=t=>{var e,r;return null===(r=null===(e=y())||void 0===e?void 0:e.emulatorHosts)||void 0===r?void 0:r[t]};exports.getDefaultEmulatorHost=v;const E=t=>{const e=v(t);if(!e)return;const r=e.lastIndexOf(":");if(r<=0||r+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const o=parseInt(e.substring(r+1),10);return"["===e[0]?[e.substring(1,r-1),o]:[e.substring(0,r),o]};exports.getDefaultEmulatorHostnameAndPort=E;const m=()=>{var t;return null===(t=y())||void 0===t?void 0:t.config};exports.getDefaultAppConfig=m;const S=t=>{var e;return null===(e=y())||void 0===e?void 0:e[`_${t}`]};exports.getExperimentalSetting=S;class A{constructor(){this.reject=(()=>{}),this.resolve=(()=>{}),this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}wrapCallback(t){return(e,r)=>{e?this.reject(e):this.resolve(r),"function"==typeof t&&(this.promise.catch(()=>{}),1===t.length?t(e):t(e,r))}}}function O(t,e){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const r=e||"demo-project",o=t.iat||0,n=t.sub||t.user_id;if(!n)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:o,exp:o+3600,auth_time:o,sub:n,user_id:n,firebase:{sign_in_provider:"custom",identities:{}}},t);return[u(JSON.stringify({alg:"none",type:"JWT"})),u(JSON.stringify(s)),""].join(".")}function C(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function D(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(C())}function w(){var e;const r=null===(e=y())||void 0===e?void 0:e.forceEnvironment;if("node"===r)return!0;if("browser"===r)return!1;try{return"[object process]"===Object.prototype.toString.call(t.process)}catch(o){return!1}}function T(){return"object"==typeof self&&self.self===self}function N(){const t="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof t&&void 0!==t.id}function M(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function j(){return C().indexOf("Electron/")>=0}function B(){const t=C();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}function k(){return C().indexOf("MSAppHost/")>=0}function I(){return!0===r.NODE_CLIENT||!0===r.NODE_ADMIN}function P(){return!w()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function L(){try{return"object"==typeof indexedDB}catch(t){return!1}}function R(){return new Promise((t,e)=>{try{let o=!0;const n="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(n);s.onsuccess=(()=>{s.result.close(),o||self.indexedDB.deleteDatabase(n),t(!0)}),s.onupgradeneeded=(()=>{o=!1}),s.onerror=(()=>{var t;e((null===(t=s.error)||void 0===t?void 0:t.message)||"")})}catch(r){e(r)}})}function V(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}exports.Deferred=A;const F="FirebaseError";class U extends Error{constructor(t,e,r){super(e),this.code=t,this.customData=r,this.name=F,Object.setPrototypeOf(this,U.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,W.prototype.create)}}exports.FirebaseError=U;class W{constructor(t,e,r){this.service=t,this.serviceName=e,this.errors=r}create(t,...e){const r=e[0]||{},o=`${this.service}/${t}`,n=this.errors[t],s=n?$(n,r):"Error",i=`${this.serviceName}: ${s} (${o}).`;return new U(o,i,r)}}function $(t,e){return t.replace(z,(t,r)=>{const o=e[r];return null!=o?String(o):`<${r}?>`})}exports.ErrorFactory=W;const z=/\{\$([^}]+)}/g;function H(t){return JSON.parse(t)}function J(t){return JSON.stringify(t)}const q=function(t){let e={},r={},o={},n="";try{const i=t.split(".");e=H(f(i[0])||""),r=H(f(i[1])||""),n=i[2],o=r.d||{},delete r.d}catch(s){}return{header:e,claims:r,data:o,signature:n}};exports.decode=q;const G=function(t){const e=q(t).claims,r=Math.floor((new Date).getTime()/1e3);let o=0,n=0;return"object"==typeof e&&(e.hasOwnProperty("nbf")?o=e.nbf:e.hasOwnProperty("iat")&&(o=e.iat),n=e.hasOwnProperty("exp")?e.exp:o+86400),!!r&&!!o&&!!n&&r>=o&&r<=n};exports.isValidTimestamp=G;const K=function(t){const e=q(t).claims;return"object"==typeof e&&e.hasOwnProperty("iat")?e.iat:null};exports.issuedAtTime=K;const X=function(t){const e=q(t).claims;return!!e&&"object"==typeof e&&e.hasOwnProperty("iat")};exports.isValidFormat=X;const Q=function(t){const e=q(t).claims;return"object"==typeof e&&!0===e.admin};function Y(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Z(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function tt(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function et(t,e,r){const o={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(o[n]=e.call(r,t[n],n,t));return o}function rt(t,e){if(t===e)return!0;const r=Object.keys(t),o=Object.keys(e);for(const n of r){if(!o.includes(n))return!1;const r=t[n],s=e[n];if(ot(r)&&ot(s)){if(!rt(r,s))return!1}else if(r!==s)return!1}for(const n of o)if(!r.includes(n))return!1;return!0}function ot(t){return null!==t&&"object"==typeof t}function nt(t,e=2e3){const r=new A;return setTimeout(()=>r.reject("timeout!"),e),t.then(r.resolve,r.reject),r.promise}function st(t){const e=[];for(const[r,o]of Object.entries(t))Array.isArray(o)?o.forEach(t=>{e.push(encodeURIComponent(r)+"="+encodeURIComponent(t))}):e.push(encodeURIComponent(r)+"="+encodeURIComponent(o));return e.length?"&"+e.join("&"):""}function it(t){const e={};return t.replace(/^\?/,"").split("&").forEach(t=>{if(t){const[r,o]=t.split("=");e[decodeURIComponent(r)]=decodeURIComponent(o)}}),e}function at(t){const e=t.indexOf("?");if(!e)return"";const r=t.indexOf("#",e);return t.substring(e,r>0?r:void 0)}exports.isAdmin=Q;class ct{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let t=1;t<this.blockSize;++t)this.pad_[t]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(t,e){e||(e=0);const r=this.W_;if("string"==typeof t)for(let u=0;u<16;u++)r[u]=t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|t.charCodeAt(e+3),e+=4;else for(let u=0;u<16;u++)r[u]=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],e+=4;for(let u=16;u<80;u++){const t=r[u-3]^r[u-8]^r[u-14]^r[u-16];r[u]=4294967295&(t<<1|t>>>31)}let o,n,s=this.chain_[0],i=this.chain_[1],a=this.chain_[2],c=this.chain_[3],h=this.chain_[4];for(let u=0;u<80;u++){u<40?u<20?(o=c^i&(a^c),n=1518500249):(o=i^a^c,n=1859775393):u<60?(o=i&a|c&(i|a),n=2400959708):(o=i^a^c,n=3395469782);const t=(s<<5|s>>>27)+o+h+n+r[u]&4294967295;h=c,c=a,a=4294967295&(i<<30|i>>>2),i=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+i&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+h&4294967295}update(t,e){if(null==t)return;void 0===e&&(e=t.length);const r=e-this.blockSize;let o=0;const n=this.buf_;let s=this.inbuf_;for(;o<e;){if(0===s)for(;o<=r;)this.compress_(t,o),o+=this.blockSize;if("string"==typeof t){for(;o<e;)if(n[s]=t.charCodeAt(o),++o,++s===this.blockSize){this.compress_(n),s=0;break}}else for(;o<e;)if(n[s]=t[o],++o,++s===this.blockSize){this.compress_(n),s=0;break}}this.inbuf_=s,this.total_+=e}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let o=this.blockSize-1;o>=56;o--)this.buf_[o]=255&e,e/=256;this.compress_(this.buf_);let r=0;for(let o=0;o<5;o++)for(let e=24;e>=0;e-=8)t[r]=this.chain_[o]>>e&255,++r;return t}}function ht(t,e){const r=new ut(t,e);return r.subscribe.bind(r)}exports.Sha1=ct;class ut{constructor(t,e){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then(()=>{t(this)}).catch(t=>{this.error(t)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,r){let o;if(void 0===t&&void 0===e&&void 0===r)throw new Error("Missing Observer.");void 0===(o=lt(t,["next","error","complete"])?t:{next:t,error:e,complete:r}).next&&(o.next=pt),void 0===o.error&&(o.error=pt),void 0===o.complete&&(o.complete=pt);const n=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?o.error(this.finalError):o.complete()}catch(t){}}),this.observers.push(o),n}unsubscribeOne(t){void 0!==this.observers&&void 0!==this.observers[t]&&(delete this.observers[t],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(t,e){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[t])try{e(this.observers[t])}catch(r){"undefined"!=typeof console&&console.error&&console.error(r)}})}close(t){this.finalized||(this.finalized=!0,void 0!==t&&(this.finalError=t),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function ft(t,e){return(...r)=>{Promise.resolve(!0).then(()=>{t(...r)}).catch(t=>{e&&e(t)})}}function lt(t,e){if("object"!=typeof t||null===t)return!1;for(const r of e)if(r in t&&"function"==typeof t[r])return!0;return!1}function pt(){}const dt=function(t,e,r,o){let n;if(o<e?n="at least "+e:o>r&&(n=0===r?"none":"no more than "+r),n){throw new Error(t+" failed: Was called with "+o+(1===o?" argument.":" arguments.")+" Expects "+n+".")}};function bt(t,e){return`${t} failed: ${e} argument `}function xt(t,e,r){if((!r||e)&&"string"!=typeof e)throw new Error(bt(t,"namespace")+"must be a valid firebase namespace.")}function _t(t,e,r,o){if((!o||r)&&"function"!=typeof r)throw new Error(bt(t,e)+"must be a valid function.")}function gt(t,e,r,o){if((!o||r)&&("object"!=typeof r||null===r))throw new Error(bt(t,e)+"must be a valid context object.")}exports.validateArgCount=dt;const yt=function(t){const e=[];let r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);if(s>=55296&&s<=56319){const e=s-55296;o(++n<t.length,"Surrogate pair missing trail surrogate."),s=65536+(e<<10)+(t.charCodeAt(n)-56320)}s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=63&s|128):s<65536?(e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=63&s|128):(e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=63&s|128)}return e};exports.stringToByteArray=yt;const vt=function(t){let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);o<128?e++:o<2048?e+=2:o>=55296&&o<=56319?(e+=4,r++):e+=3}return e};exports.stringLength=vt;const Et=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})};exports.uuidv4=Et;const mt=1e3,St=2,At=144e5;exports.MAX_VALUE_MILLIS=At;const Ot=.5;function Ct(t,e=mt,r=St){const o=e*Math.pow(r,t),n=Math.round(Ot*o*(Math.random()-.5)*2);return Math.min(At,o+n)}function Dt(t){return Number.isFinite(t)?t+wt(t):`${t}`}function wt(t){const e=(t=Math.abs(t))%100;if(e>=10&&e<=20)return"th";const r=t%10;return 1===r?"st":2===r?"nd":3===r?"rd":"th"}function Tt(t){return t&&t._delegate?t._delegate:t}exports.RANDOM_FACTOR=Ot;
|
|
465
465
|
},{"process":"pBGv"}],"vhY9":[function(require,module,exports) {
|
|
466
466
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Provider=exports.ComponentContainer=exports.Component=void 0;var t=require("@firebase/util");class e{constructor(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}exports.Component=e;const n="[DEFAULT]";class i{constructor(t,e){this.name=t,this.container=e,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.Deferred;if(this.instancesDeferred.set(n,e),this.isInitialized(n)||this.shouldAutoInitialize())try{const t=this.getOrInitializeService({instanceIdentifier:n});t&&e.resolve(t)}catch(i){}}return this.instancesDeferred.get(n).promise}getImmediate(t){var e;const n=this.normalizeInstanceIdentifier(null==t?void 0:t.identifier),i=null!==(e=null==t?void 0:t.optional)&&void 0!==e&&e;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(i)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(s){if(i)return null;throw s}}getComponent(){return this.component}setComponent(t){if(t.name!==this.name)throw Error(`Mismatching Component ${t.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=t,this.shouldAutoInitialize()){if(r(t))try{this.getOrInitializeService({instanceIdentifier:n})}catch(e){}for(const[t,n]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(t);try{const t=this.getOrInitializeService({instanceIdentifier:i});n.resolve(t)}catch(e){}}}}clearInstance(t=n){this.instancesDeferred.delete(t),this.instancesOptions.delete(t),this.instances.delete(t)}async delete(){const t=Array.from(this.instances.values());await Promise.all([...t.filter(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...t.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return null!=this.component}isInitialized(t=n){return this.instances.has(t)}getOptions(t=n){return this.instancesOptions.get(t)||{}}initialize(t={}){const{options:e={}}=t,n=this.normalizeInstanceIdentifier(t.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:n,options:e});for(const[s,r]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(s)&&r.resolve(i)}return i}onInit(t,e){var n;const i=this.normalizeInstanceIdentifier(e),s=null!==(n=this.onInitCallbacks.get(i))&&void 0!==n?n:new Set;s.add(t),this.onInitCallbacks.set(i,s);const r=this.instances.get(i);return r&&t(r,i),()=>{s.delete(t)}}invokeOnInitCallbacks(t,e){const n=this.onInitCallbacks.get(e);if(n)for(const s of n)try{s(t,e)}catch(i){}}getOrInitializeService({instanceIdentifier:t,options:e={}}){let n=this.instances.get(t);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:s(t),options:e}),this.instances.set(t,n),this.instancesOptions.set(t,e),this.invokeOnInitCallbacks(n,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,n)}catch(i){}return n||null}normalizeInstanceIdentifier(t=n){return this.component?this.component.multipleInstances?t:n:t}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}function s(t){return t===n?void 0:t}function r(t){return"EAGER"===t.instantiationMode}exports.Provider=i;class o{constructor(t){this.name=t,this.providers=new Map}addComponent(t){const e=this.getProvider(t.name);if(e.isComponentSet())throw new Error(`Component ${t.name} has already been registered with ${this.name}`);e.setComponent(t)}addOrOverwriteComponent(t){this.getProvider(t.name).isComponentSet()&&this.providers.delete(t.name),this.addComponent(t)}getProvider(t){if(this.providers.has(t))return this.providers.get(t);const e=new i(t,this);return this.providers.set(t,e),e}getProviders(){return Array.from(this.providers.values())}}exports.ComponentContainer=o;
|
|
467
467
|
},{"@firebase/util":"chA2"}],"JJem":[function(require,module,exports) {
|
|
@@ -471,31 +471,31 @@ var t=arguments[3],e=require("process");Object.defineProperty(exports,"__esModul
|
|
|
471
471
|
},{}],"JZvK":[function(require,module,exports) {
|
|
472
472
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.deleteDB=n,exports.openDB=t,Object.defineProperty(exports,"unwrap",{enumerable:!0,get:function(){return e.u}}),Object.defineProperty(exports,"wrap",{enumerable:!0,get:function(){return e.w}});var e=require("./wrap-idb-value.js");function t(t,n,{blocked:r,upgrade:o,blocking:d,terminated:i}={}){const s=indexedDB.open(t,n),a=(0,e.w)(s);return o&&s.addEventListener("upgradeneeded",t=>{o((0,e.w)(s.result),t.oldVersion,t.newVersion,(0,e.w)(s.transaction))}),r&&s.addEventListener("blocked",()=>r()),a.then(e=>{i&&e.addEventListener("close",()=>i()),d&&e.addEventListener("versionchange",()=>d())}).catch(()=>{}),a}function n(t,{blocked:n}={}){const r=indexedDB.deleteDatabase(t);return n&&r.addEventListener("blocked",()=>n()),(0,e.w)(r).then(()=>void 0)}const r=["get","getKey","getAll","getAllKeys","count"],o=["put","add","delete","clear"],d=new Map;function i(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(d.get(t))return d.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,s=o.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!r.includes(n))return;const a=async function(e,...t){const r=this.transaction(e,s?"readwrite":"readonly");let o=r.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),s&&r.done]))[0]};return d.set(t,a),a}(0,e.r)(e=>({...e,get:(t,n,r)=>i(t,n)||e.get(t,n,r),has:(t,n)=>!!i(t,n)||e.has(t,n)}));
|
|
473
473
|
},{"./wrap-idb-value.js":"F1qz"}],"h2Mb":[function(require,module,exports) {
|
|
474
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"FirebaseError",{enumerable:!0,get:function(){return a.FirebaseError}}),exports._DEFAULT_ENTRY_NAME=exports.SDK_VERSION=void 0,exports._addComponent=L,exports._addOrOverwriteComponent=M,exports._apps=void 0,exports._clearComponents=V,exports._components=void 0,exports._getProvider=U,exports._registerComponent=T,exports._removeServiceInstance=R,exports.deleteApp=Q,exports.getApp=Y,exports.getApps=G,exports.initializeApp=W,exports.onLog=Z,exports.registerVersion=X,exports.setLogLevel=ee;var e=require("@firebase/component"),t=require("@firebase/logger"),a=require("@firebase/util"),r=require("idb");class n{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(i(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null}).filter(e=>e).join(" ")}}function i(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}const s="@firebase/app",o="0.9.3",c=new t.Logger("@firebase/app"),p="@firebase/app-compat",h="@firebase/analytics-compat",l="@firebase/analytics",f="@firebase/app-check-compat",d="@firebase/app-check",b="@firebase/auth",g="@firebase/auth-compat",u="@firebase/database",m="@firebase/database-compat",_="@firebase/functions",w="@firebase/functions-compat",v="@firebase/installations",D="@firebase/installations-compat",C="@firebase/messaging",E="@firebase/messaging-compat",y="@firebase/performance",x="@firebase/performance-compat",I="@firebase/remote-config",S="@firebase/remote-config-compat",P="@firebase/storage",O="@firebase/storage-compat",A="@firebase/firestore",$="@firebase/firestore-compat",N="firebase",F="9.17.1",j="[DEFAULT]";exports._DEFAULT_ENTRY_NAME=j;const k={[s]:"fire-core",[p]:"fire-core-compat",[l]:"fire-analytics",[h]:"fire-analytics-compat",[d]:"fire-app-check",[f]:"fire-app-check-compat",[b]:"fire-auth",[g]:"fire-auth-compat",[u]:"fire-rtdb",[m]:"fire-rtdb-compat",[_]:"fire-fn",[w]:"fire-fn-compat",[v]:"fire-iid",[D]:"fire-iid-compat",[C]:"fire-fcm",[E]:"fire-fcm-compat",[y]:"fire-perf",[x]:"fire-perf-compat",[I]:"fire-rc",[S]:"fire-rc-compat",[P]:"fire-gcs",[O]:"fire-gcs-compat",[A]:"fire-fst",[$]:"fire-fst-compat","fire-js":"fire-js",[N]:"fire-js-all"},B=new Map;exports._apps=B;const H=new Map;function L(e,t){try{e.container.addComponent(t)}catch(a){c.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,a)}}function M(e,t){e.container.addOrOverwriteComponent(t)}function T(e){const t=e.name;if(H.has(t))return c.debug(`There were multiple attempts to register component ${t}.`),!1;H.set(t,e);for(const a of B.values())L(a,e);return!0}function U(e,t){const a=e.container.getProvider("heartbeat").getImmediate({optional:!0});return a&&a.triggerHeartbeat(),e.container.getProvider(t)}function R(e,t,a=j){U(e,t).clearInstance(a)}function V(){H.clear()}exports._components=H;const q={"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."},z=new a.ErrorFactory("app","Firebase",q);class J{constructor(t,a,r){this._isDeleted=!1,this._options=Object.assign({},t),this._config=Object.assign({},a),this._name=a.name,this._automaticDataCollectionEnabled=a.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new e.Component("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 z.create("app-deleted",{appName:this._name})}}const K=F;function W(t,r={}){let n=t;if("object"!=typeof r){r={name:r}}const i=Object.assign({name:j,automaticDataCollectionEnabled:!1},r),s=i.name;if("string"!=typeof s||!s)throw z.create("bad-app-name",{appName:String(s)});if(n||(n=(0,a.getDefaultAppConfig)()),!n)throw z.create("no-options");const o=B.get(s);if(o){if((0,a.deepEqual)(n,o.options)&&(0,a.deepEqual)(i,o.config))return o;throw z.create("duplicate-app",{appName:s})}const c=new e.ComponentContainer(s);for(const e of H.values())c.addComponent(e);const p=new J(n,i,c);return B.set(s,p),p}function Y(e=j){const t=B.get(e);if(!t&&e===j)return W();if(!t)throw z.create("no-app",{appName:e});return t}function G(){return Array.from(B.values())}async function Q(e){const t=e.name;B.has(t)&&(B.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function X(t,a,r){var n;let i=null!==(n=k[t])&&void 0!==n?n:t;r&&(i+=`-${r}`);const s=i.match(/\s|\//),o=a.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${a}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${a}" contains illegal characters (whitespace or "/")`),void c.warn(e.join(" "))}T(new e.Component(`${i}-version`,()=>({library:i,version:a}),"VERSION"))}function Z(e,a){if(null!==e&&"function"!=typeof e)throw z.create("invalid-log-argument");(0,t.setUserLogHandler)(e,a)}function ee(e){(0,t.setLogLevel)(e)}exports.SDK_VERSION="9.17.1";const te="firebase-heartbeat-database",ae=1,re="firebase-heartbeat-store";let ne=null;function ie(){return ne||(ne=(0,r.openDB)(te,ae,{upgrade:(e,t)=>{switch(t){case 0:e.createObjectStore(re)}}}).catch(e=>{throw z.create("idb-open",{originalErrorMessage:e.message})})),ne}async function se(e){try{return(await ie()).transaction(re).objectStore(re).get(ce(e))}catch(t){if(t instanceof a.FirebaseError)c.warn(t.message);else{const e=z.create("idb-get",{originalErrorMessage:null==t?void 0:t.message});c.warn(e.message)}}}async function oe(e,t){try{const n=(await ie()).transaction(re,"readwrite"),i=n.objectStore(re);return await i.put(t,ce(e)),n.done}catch(r){if(r instanceof a.FirebaseError)c.warn(r.message);else{const e=z.create("idb-set",{originalErrorMessage:null==r?void 0:r.message});c.warn(e.message)}}}function ce(e){return`${e.name}!${e.options.appId}`}const pe=1024,he=2592e6;class le{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new be(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=fe();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:e}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=he}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";const e=fe(),{heartbeatsToSend:t,unsentEntries:r}=de(this._heartbeatsCache.heartbeats),n=(0,a.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),n}}function fe(){return(new Date).toISOString().substring(0,10)}function de(e,t=pe){const a=[];let r=e.slice();for(const n of e){const e=a.find(e=>e.agent===n.agent);if(e){if(e.dates.push(n.date),ge(a)>t){e.dates.pop();break}}else if(a.push({agent:n.agent,dates:[n.date]}),ge(a)>t){a.pop();break}r=r.slice(1)}return{heartbeatsToSend:a,unsentEntries:r}}class be{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(0,a.isIndexedDBAvailable)()&&(0,a.validateIndexedDBOpenable)().then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){return await se(this.app)||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const a=await this.read();return oe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:a.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const a=await this.read();return oe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:a.lastSentHeartbeatDate,heartbeats:[...a.heartbeats,...e.heartbeats]})}}}function ge(e){return(0,a.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:e})).length}function ue(t){T(new e.Component("platform-logger",e=>new n(e),"PRIVATE")),T(new e.Component("heartbeat",e=>new le(e),"PRIVATE")),X(s,o,t),X(s,o,"esm2017"),X("fire-js","")}ue("");
|
|
474
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"FirebaseError",{enumerable:!0,get:function(){return a.FirebaseError}}),exports._DEFAULT_ENTRY_NAME=exports.SDK_VERSION=void 0,exports._addComponent=L,exports._addOrOverwriteComponent=M,exports._apps=void 0,exports._clearComponents=V,exports._components=void 0,exports._getProvider=U,exports._registerComponent=T,exports._removeServiceInstance=R,exports.deleteApp=Q,exports.getApp=Y,exports.getApps=G,exports.initializeApp=W,exports.onLog=Z,exports.registerVersion=X,exports.setLogLevel=ee;var e=require("@firebase/component"),t=require("@firebase/logger"),a=require("@firebase/util"),r=require("idb");class n{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{if(i(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null}).filter(e=>e).join(" ")}}function i(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}const s="@firebase/app",o="0.9.5",c=new t.Logger("@firebase/app"),p="@firebase/app-compat",h="@firebase/analytics-compat",l="@firebase/analytics",f="@firebase/app-check-compat",d="@firebase/app-check",b="@firebase/auth",g="@firebase/auth-compat",u="@firebase/database",m="@firebase/database-compat",_="@firebase/functions",w="@firebase/functions-compat",v="@firebase/installations",D="@firebase/installations-compat",C="@firebase/messaging",E="@firebase/messaging-compat",y="@firebase/performance",x="@firebase/performance-compat",I="@firebase/remote-config",S="@firebase/remote-config-compat",P="@firebase/storage",O="@firebase/storage-compat",A="@firebase/firestore",$="@firebase/firestore-compat",N="firebase",F="9.18.0",j="[DEFAULT]";exports._DEFAULT_ENTRY_NAME=j;const k={[s]:"fire-core",[p]:"fire-core-compat",[l]:"fire-analytics",[h]:"fire-analytics-compat",[d]:"fire-app-check",[f]:"fire-app-check-compat",[b]:"fire-auth",[g]:"fire-auth-compat",[u]:"fire-rtdb",[m]:"fire-rtdb-compat",[_]:"fire-fn",[w]:"fire-fn-compat",[v]:"fire-iid",[D]:"fire-iid-compat",[C]:"fire-fcm",[E]:"fire-fcm-compat",[y]:"fire-perf",[x]:"fire-perf-compat",[I]:"fire-rc",[S]:"fire-rc-compat",[P]:"fire-gcs",[O]:"fire-gcs-compat",[A]:"fire-fst",[$]:"fire-fst-compat","fire-js":"fire-js",[N]:"fire-js-all"},B=new Map;exports._apps=B;const H=new Map;function L(e,t){try{e.container.addComponent(t)}catch(a){c.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,a)}}function M(e,t){e.container.addOrOverwriteComponent(t)}function T(e){const t=e.name;if(H.has(t))return c.debug(`There were multiple attempts to register component ${t}.`),!1;H.set(t,e);for(const a of B.values())L(a,e);return!0}function U(e,t){const a=e.container.getProvider("heartbeat").getImmediate({optional:!0});return a&&a.triggerHeartbeat(),e.container.getProvider(t)}function R(e,t,a=j){U(e,t).clearInstance(a)}function V(){H.clear()}exports._components=H;const q={"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."},z=new a.ErrorFactory("app","Firebase",q);class J{constructor(t,a,r){this._isDeleted=!1,this._options=Object.assign({},t),this._config=Object.assign({},a),this._name=a.name,this._automaticDataCollectionEnabled=a.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new e.Component("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 z.create("app-deleted",{appName:this._name})}}const K=F;function W(t,r={}){let n=t;if("object"!=typeof r){r={name:r}}const i=Object.assign({name:j,automaticDataCollectionEnabled:!1},r),s=i.name;if("string"!=typeof s||!s)throw z.create("bad-app-name",{appName:String(s)});if(n||(n=(0,a.getDefaultAppConfig)()),!n)throw z.create("no-options");const o=B.get(s);if(o){if((0,a.deepEqual)(n,o.options)&&(0,a.deepEqual)(i,o.config))return o;throw z.create("duplicate-app",{appName:s})}const c=new e.ComponentContainer(s);for(const e of H.values())c.addComponent(e);const p=new J(n,i,c);return B.set(s,p),p}function Y(e=j){const t=B.get(e);if(!t&&e===j)return W();if(!t)throw z.create("no-app",{appName:e});return t}function G(){return Array.from(B.values())}async function Q(e){const t=e.name;B.has(t)&&(B.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function X(t,a,r){var n;let i=null!==(n=k[t])&&void 0!==n?n:t;r&&(i+=`-${r}`);const s=i.match(/\s|\//),o=a.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${a}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${a}" contains illegal characters (whitespace or "/")`),void c.warn(e.join(" "))}T(new e.Component(`${i}-version`,()=>({library:i,version:a}),"VERSION"))}function Z(e,a){if(null!==e&&"function"!=typeof e)throw z.create("invalid-log-argument");(0,t.setUserLogHandler)(e,a)}function ee(e){(0,t.setLogLevel)(e)}exports.SDK_VERSION="9.18.0";const te="firebase-heartbeat-database",ae=1,re="firebase-heartbeat-store";let ne=null;function ie(){return ne||(ne=(0,r.openDB)(te,ae,{upgrade:(e,t)=>{switch(t){case 0:e.createObjectStore(re)}}}).catch(e=>{throw z.create("idb-open",{originalErrorMessage:e.message})})),ne}async function se(e){try{return(await ie()).transaction(re).objectStore(re).get(ce(e))}catch(t){if(t instanceof a.FirebaseError)c.warn(t.message);else{const e=z.create("idb-get",{originalErrorMessage:null==t?void 0:t.message});c.warn(e.message)}}}async function oe(e,t){try{const n=(await ie()).transaction(re,"readwrite"),i=n.objectStore(re);return await i.put(t,ce(e)),n.done}catch(r){if(r instanceof a.FirebaseError)c.warn(r.message);else{const e=z.create("idb-set",{originalErrorMessage:null==r?void 0:r.message});c.warn(e.message)}}}function ce(e){return`${e.name}!${e.options.appId}`}const pe=1024,he=2592e6;class le{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new be(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=fe();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some(e=>e.date===t))return this._heartbeatsCache.heartbeats.push({date:t,agent:e}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=he}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";const e=fe(),{heartbeatsToSend:t,unsentEntries:r}=de(this._heartbeatsCache.heartbeats),n=(0,a.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),n}}function fe(){return(new Date).toISOString().substring(0,10)}function de(e,t=pe){const a=[];let r=e.slice();for(const n of e){const e=a.find(e=>e.agent===n.agent);if(e){if(e.dates.push(n.date),ge(a)>t){e.dates.pop();break}}else if(a.push({agent:n.agent,dates:[n.date]}),ge(a)>t){a.pop();break}r=r.slice(1)}return{heartbeatsToSend:a,unsentEntries:r}}class be{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(0,a.isIndexedDBAvailable)()&&(0,a.validateIndexedDBOpenable)().then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){return await se(this.app)||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const a=await this.read();return oe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:a.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const a=await this.read();return oe(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:a.lastSentHeartbeatDate,heartbeats:[...a.heartbeats,...e.heartbeats]})}}}function ge(e){return(0,a.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:e})).length}function ue(t){T(new e.Component("platform-logger",e=>new n(e),"PRIVATE")),T(new e.Component("heartbeat",e=>new le(e),"PRIVATE")),X(s,o,t),X(s,o,"esm2017"),X("fire-js","")}ue("");
|
|
475
475
|
},{"@firebase/component":"vhY9","@firebase/logger":"JJem","@firebase/util":"chA2","idb":"JZvK"}],"CMFQ":[function(require,module,exports) {
|
|
476
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=require("@firebase/util"),t=require("@firebase/component"),n=i(require("@firebase/app")),r=require("@firebase/logger");function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(a=function(e){return e?n:t})(e)}function i(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=a(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var s=i?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(r,o,s):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}class o{constructor(e,r){this._delegate=e,this.firebase=r,(0,n._addComponent)(e,new t.Component("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),(0,n.deleteApp)(this._delegate)))}_getService(e,t=n._DEFAULT_ENTRY_NAME){var r;this._delegate.checkDestroyed();const a=this._delegate.container.getProvider(e);return a.isInitialized()||"EXPLICIT"!==(null===(r=a.getComponent())||void 0===r?void 0:r.instantiationMode)||a.initialize(),a.getImmediate({identifier:t})}_removeServiceInstance(e,t=n._DEFAULT_ENTRY_NAME){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){(0,n._addComponent)(this._delegate,e)}_addOrOverwriteComponent(e){(0,n._addOrOverwriteComponent)(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const s={"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."},p=new e.ErrorFactory("app-compat","Firebase",s);function c(t){const r={},a={__esModule:!0,initializeApp:function(i,o={}){const s=n.initializeApp(i,o);if((0,e.contains)(r,s.name))return r[s.name];const p=new t(s,a);return r[s.name]=p,p},app:i,registerVersion:n.registerVersion,setLogLevel:n.setLogLevel,onLog:n.onLog,apps:null,SDK_VERSION:n.SDK_VERSION,INTERNAL:{registerComponent:function(r){const o=r.name,s=o.replace("-compat","");if(n._registerComponent(r)&&"PUBLIC"===r.type){const n=(e=i())=>{if("function"!=typeof e[s])throw p.create("invalid-app-argument",{appName:o});return e[s]()};void 0!==r.serviceProps&&(0,e.deepExtend)(n,r.serviceProps),a[s]=n,t.prototype[s]=function(...e){const t=this._getService.bind(this,o);return t.apply(this,r.multipleInstances?e:[])}}return"PUBLIC"===r.type?a[s]:null},removeApp:function(e){delete r[e]},useAsService:function(e,t){if("serverAuth"===t)return null;return t},modularAPIs:n}};function i(t){if(t=t||n._DEFAULT_ENTRY_NAME,!(0,e.contains)(r,t))throw p.create("no-app",{appName:t});return r[t]}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(r).map(e=>r[e])}}),i.App=t,a}function l(){const t=c(o);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:l,extendNamespace:function(n){(0,e.deepExtend)(t,n)},createSubscribe:e.createSubscribe,ErrorFactory:e.ErrorFactory,deepExtend:e.deepExtend}),t}const u=l(),d=new r.Logger("@firebase/app-compat"),f="@firebase/app-compat",m="0.2.
|
|
476
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=require("@firebase/util"),t=require("@firebase/component"),n=i(require("@firebase/app")),r=require("@firebase/logger");function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(a=function(e){return e?n:t})(e)}function i(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=a(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var s=i?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(r,o,s):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}class o{constructor(e,r){this._delegate=e,this.firebase=r,(0,n._addComponent)(e,new t.Component("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),(0,n.deleteApp)(this._delegate)))}_getService(e,t=n._DEFAULT_ENTRY_NAME){var r;this._delegate.checkDestroyed();const a=this._delegate.container.getProvider(e);return a.isInitialized()||"EXPLICIT"!==(null===(r=a.getComponent())||void 0===r?void 0:r.instantiationMode)||a.initialize(),a.getImmediate({identifier:t})}_removeServiceInstance(e,t=n._DEFAULT_ENTRY_NAME){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){(0,n._addComponent)(this._delegate,e)}_addOrOverwriteComponent(e){(0,n._addOrOverwriteComponent)(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const s={"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."},p=new e.ErrorFactory("app-compat","Firebase",s);function c(t){const r={},a={__esModule:!0,initializeApp:function(i,o={}){const s=n.initializeApp(i,o);if((0,e.contains)(r,s.name))return r[s.name];const p=new t(s,a);return r[s.name]=p,p},app:i,registerVersion:n.registerVersion,setLogLevel:n.setLogLevel,onLog:n.onLog,apps:null,SDK_VERSION:n.SDK_VERSION,INTERNAL:{registerComponent:function(r){const o=r.name,s=o.replace("-compat","");if(n._registerComponent(r)&&"PUBLIC"===r.type){const n=(e=i())=>{if("function"!=typeof e[s])throw p.create("invalid-app-argument",{appName:o});return e[s]()};void 0!==r.serviceProps&&(0,e.deepExtend)(n,r.serviceProps),a[s]=n,t.prototype[s]=function(...e){const t=this._getService.bind(this,o);return t.apply(this,r.multipleInstances?e:[])}}return"PUBLIC"===r.type?a[s]:null},removeApp:function(e){delete r[e]},useAsService:function(e,t){if("serverAuth"===t)return null;return t},modularAPIs:n}};function i(t){if(t=t||n._DEFAULT_ENTRY_NAME,!(0,e.contains)(r,t))throw p.create("no-app",{appName:t});return r[t]}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(r).map(e=>r[e])}}),i.App=t,a}function l(){const t=c(o);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:l,extendNamespace:function(n){(0,e.deepExtend)(t,n)},createSubscribe:e.createSubscribe,ErrorFactory:e.ErrorFactory,deepExtend:e.deepExtend}),t}const u=l(),d=new r.Logger("@firebase/app-compat"),f="@firebase/app-compat",m="0.2.5";function g(e){(0,n.registerVersion)(f,m,e)}if((0,e.isBrowser)()&&void 0!==self.firebase){d.warn("\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n ");const e=self.firebase.SDK_VERSION;e&&e.indexOf("LITE")>=0&&d.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n ")}const b=u;exports.default=b,g();
|
|
477
477
|
},{"@firebase/util":"chA2","@firebase/component":"vhY9","@firebase/app":"h2Mb","@firebase/logger":"JJem"}],"tq2Y":[function(require,module,exports) {
|
|
478
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return e.default}});var e=r(require("@firebase/app-compat"));function r(e){return e&&e.__esModule?e:{default:e}}var t="firebase",a="9.
|
|
478
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return e.default}});var e=r(require("@firebase/app-compat"));function r(e){return e&&e.__esModule?e:{default:e}}var t="firebase",a="9.18.0";e.default.registerVersion(t,a,"app-compat");
|
|
479
479
|
},{"@firebase/app-compat":"CMFQ"}],"Q6BU":[function(require,module,exports) {
|
|
480
480
|
var process = require("process");
|
|
481
|
-
var e=require("process");Object.defineProperty(exports,"__esModule",{value:!0}),exports._TEST_ACCESS_hijackHash=exports._TEST_ACCESS_forceRestClient=exports._ReferenceImpl=exports._QueryParams=exports._QueryImpl=exports.TransactionResult=exports.QueryConstraint=exports.OnDisconnect=exports.Database=exports.DataSnapshot=void 0,exports._repoManagerDatabaseFromApp=ol,exports._setSDKVersion=l,exports._validateWritablePath=exports._validatePathString=void 0,exports.child=pa,exports.connectDatabaseEmulator=fl,exports.enableLogging=yl,exports.endAt=Ma,exports.endBefore=Fa,exports.equalTo=el,exports.forceLongPolling=_l,exports.forceWebSockets=dl,exports.get=Ta,exports.getDatabase=pl,exports.goOffline=ml,exports.goOnline=gl,exports.increment=Tl,exports.limitToFirst=ja,exports.limitToLast=Va,exports.off=Ra,exports.onChildAdded=Sa,exports.onChildChanged=xa,exports.onChildMoved=Pa,exports.onChildRemoved=Na,exports.onDisconnect=fa,exports.onValue=Ea,exports.orderByChild=Ya,exports.orderByKey=Ka,exports.orderByPriority=$a,exports.orderByValue=Ja,exports.push=ma,exports.query=tl,exports.ref=da,exports.refFromURL=_a,exports.remove=ga,exports.runTransaction=bl,exports.serverTimestamp=wl,exports.set=ya,exports.setPriority=va,exports.setWithPriority=Ca,exports.startAfter=Ua,exports.startAt=Oa,exports.update=wa;var t=require("@firebase/app"),n=require("@firebase/component"),i=require("@firebase/util"),s=require("@firebase/logger");const r="@firebase/database",o="0.14.3";let a="";function l(e){a=e}class h{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),(0,i.stringify)(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:(0,i.jsonEval)(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class c{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return(0,i.contains)(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const u=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new h(t)}}catch(t){}return new c},d=u("localStorage"),_=u("sessionStorage"),p=new s.Logger("@firebase/database"),f=function(){let e=1;return function(){return e++}}(),m=function(e){const t=(0,i.stringToByteArray)(e),n=new i.Sha1;n.update(t);const s=n.digest();return i.base64.encodeByteArray(s)},g=function(...e){let t="";for(let n=0;n<e.length;n++){const s=e[n];Array.isArray(s)||s&&"object"==typeof s&&"number"==typeof s.length?t+=g.apply(null,s):t+="object"==typeof s?(0,i.stringify)(s):s,t+=" "}return t};let y=null,v=!0;const C=function(e,t){(0,i.assert)(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(p.logLevel=s.LogLevel.VERBOSE,y=p.log.bind(p),t&&_.set("logging_enabled",!0)):"function"==typeof e?y=e:(y=null,_.remove("logging_enabled"))},w=function(...e){if(!0===v&&(v=!1,null===y&&!0===_.get("logging_enabled")&&C(!0)),y){const t=g.apply(null,e);y(t)}},T=function(e){return function(...t){w(e,...t)}},I=function(...e){const t="FIREBASE INTERNAL ERROR: "+g(...e);p.error(t)},b=function(...e){const t=`FIREBASE FATAL ERROR: ${g(...e)}`;throw p.error(t),new Error(t)},k=function(...e){const t="FIREBASE WARNING: "+g(...e);p.warn(t)},E=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&k("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},S=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},x=function(e){if((0,i.isNodeSdk)()||"complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}},P="[MIN_NAME]",N="[MAX_NAME]",R=function(e,t){if(e===t)return 0;if(e===P||t===N)return-1;if(t===P||e===N)return 1;{const n=V(e),i=V(t);return null!==n?null!==i?n-i==0?e.length-t.length:n-i:-1:null!==i?1:e<t?-1:1}},D=function(e,t){return e===t?0:e<t?-1:1},A=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+(0,i.stringify)(t))},M=function(e){if("object"!=typeof e||null===e)return(0,i.stringify)(e);const t=[];for(const i in e)t.push(i);t.sort();let n="{";for(let s=0;s<t.length;s++)0!==s&&(n+=","),n+=(0,i.stringify)(t[s]),n+=":",n+=M(e[t[s]]);return n+="}"},q=function(e,t){const n=e.length;if(n<=t)return[e];const i=[];for(let s=0;s<n;s+=t)s+t>n?i.push(e.substring(s,n)):i.push(e.substring(s,s+t));return i};function F(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const L=function(e){(0,i.assert)(!S(e),"Invalid JSON number");let t,n,s,r,o;0===e?(n=0,s=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(n=(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,s=Math.round(e*Math.pow(2,52-r)-Math.pow(2,52))):(n=0,s=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(s%2?1:0),s=Math.floor(s/2);for(o=11;o;o-=1)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse();const l=a.join("");let h="";for(o=0;o<64;o+=8){let e=parseInt(l.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),h+=e}return h.toLowerCase()},O=function(){return!("object"!=typeof window||!window.chrome||!window.chrome.extension||/^chrome/.test(window.location.href))},W=function(){return"object"==typeof Windows&&"object"==typeof Windows.UI};function U(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const i=new Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}const B=new RegExp("^-?(0*)\\d{1,10}$"),j=-2147483648,H=2147483647,V=function(e){if(B.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},z=function(e){try{e()}catch(t){setTimeout(()=>{const e=t.stack||"";throw k("Exception was thrown by user callback.",e),t},Math.floor(0))}},Y=function(){return("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Q=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class K{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then(e=>this.appCheck=e)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){k(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class G{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&"auth/token-not-initialized"===e.code?(w("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',k(e)}}class ${constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}$.OWNER="owner";const X="5",J="v",Z="s",ee="r",te="f",ne=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,ie="ls",se="p",re="ac",oe="websocket",ae="long_polling";class le{constructor(e,t,n,i,s=!1,r="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=r,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=d.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&d.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function he(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams}function ce(e,t,n){let s;if((0,i.assert)("string"==typeof t,"typeof type must == string"),(0,i.assert)("object"==typeof n,"typeof params must == object"),t===oe)s=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==ae)throw new Error("Unknown connection type: "+t);s=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}he(e)&&(n.ns=e.namespace);const r=[];return F(n,(e,t)=>{r.push(e+"="+t)}),s+r.join("&")}class ue{constructor(){this.counters_={}}incrementCounter(e,t=1){(0,i.contains)(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return(0,i.deepCopy)(this.counters_)}}const de={},_e={};function pe(e){const t=e.toString();return de[t]||(de[t]=new ue),de[t]}function fe(e,t){const n=e.toString();return _e[n]||(_e[n]=t()),_e[n]}class me{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&z(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const ge="start",ye="close",ve="pLPCommand",Ce="pRTLPCB",we="id",Te="pw",Ie="ser",be="cb",ke="seg",Ee="ts",Se="d",xe="dframe",Pe=1870,Ne=30,Re=Pe-Ne,De=25e3,Ae=3e4;class Me{constructor(e,t,n,i,s,r,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.transportSessionId=r,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=T(e),this.stats_=pe(t),this.urlFn=(e=>(this.appCheckToken&&(e[re]=this.appCheckToken),ce(t,ae,e)))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new me(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Ae)),x(()=>{if(this.isClosed_)return;this.scriptTagHolder=new qe((...e)=>{const[t,n,i,s,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ge)this.id=n,this.password=i;else{if(t!==ye)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const e={};e[ge]="t",e[Ie]=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e[be]=this.scriptTagHolder.uniqueCallbackIdentifier),e[J]=X,this.transportSessionId&&(e[Z]=this.transportSessionId),this.lastSessionId&&(e[ie]=this.lastSessionId),this.applicationId&&(e[se]=this.applicationId),this.appCheckToken&&(e[re]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&ne.test(location.hostname)&&(e[ee]=te);const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Me.forceAllow_=!0}static forceDisallow(){Me.forceDisallow_=!0}static isAvailable(){return!(0,i.isNodeSdk)()&&(!!Me.forceAllow_||!Me.forceDisallow_&&"undefined"!=typeof document&&null!=document.createElement&&!O()&&!W())}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=(0,i.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=(0,i.base64Encode)(t),s=q(n,Re);for(let i=0;i<s.length;i++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,s.length,s[i]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if((0,i.isNodeSdk)())return;this.myDisconnFrame=document.createElement("iframe");const n={};n[xe]="t",n[we]=e,n[Te]=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=(0,i.stringify)(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class qe{constructor(e,t,n,s){if(this.onDisconnect=n,this.urlFn=s,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,(0,i.isNodeSdk)())this.commandCB=e,this.onMessageCB=t;else{this.uniqueCallbackIdentifier=f(),window[ve+this.uniqueCallbackIdentifier]=e,window[Ce+this.uniqueCallbackIdentifier]=t,this.myIFrame=qe.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)){n='<script>document.domain="'+document.domain+'";<\/script>'}const i="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(r){w("frame writing exception"),r.stack&&w(r.stack),w(r)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||w("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e[we]=this.myID,e[Te]=this.myPW,e[Ie]=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+Ne+n.length<=Pe))break;{const e=this.pendingSegs.shift();n=n+"&"+ke+i+"="+e.seg+"&"+Ee+i+"="+e.ts+"&"+Se+i+"="+e.d,i++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(De));this.addTag(e,()=>{clearTimeout(i),n()})}addTag(e,t){(0,i.isNodeSdk)()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;const i=this.myIFrame.doc.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.onload=i.onreadystatechange=function(){const e=i.readyState;e&&"loaded"!==e&&"complete"!==e||(i.onload=i.onreadystatechange=null,i.parentNode&&i.parentNode.removeChild(i),t())},i.onerror=(()=>{w("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()}),this.myIFrame.doc.body.appendChild(i)}catch(n){}},Math.floor(1))}}const Fe=16384,Le=45e3;let Oe=null;"undefined"!=typeof MozWebSocket?Oe=MozWebSocket:"undefined"!=typeof WebSocket&&(Oe=WebSocket);class We{constructor(e,t,n,i,s,r,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=T(this.connId),this.stats_=pe(t),this.connURL=We.connectionURL_(t,r,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,s,r){const o={};return o[J]=X,!(0,i.isNodeSdk)()&&"undefined"!=typeof location&&location.hostname&&ne.test(location.hostname)&&(o[ee]=te),t&&(o[Z]=t),n&&(o[ie]=n),s&&(o[re]=s),r&&(o[se]=r),ce(e,oe,o)}open(t,n){this.onDisconnect=n,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,d.set("previous_websocket_failure",!0);try{let t;if((0,i.isNodeSdk)()){const n=this.nodeAdmin?"AdminNode":"Node";t={headers:{"User-Agent":`Firebase/${X}/${a}/${e.platform}/${n}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(t.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(t.headers["X-Firebase-AppCheck"]=this.appCheckToken);const i=e.env,s=0===this.connURL.indexOf("wss://")?i.HTTPS_PROXY||i.https_proxy:i.HTTP_PROXY||i.http_proxy;s&&(t.proxy={origin:s})}this.mySock=new Oe(this.connURL,[],t)}catch(s){this.log_("Error instantiating WebSocket.");const e=s.message||s.data;return e&&this.log_(e),void this.onClosed_()}this.mySock.onopen=(()=>{this.log_("Websocket connected."),this.everConnected_=!0}),this.mySock.onclose=(()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()}),this.mySock.onmessage=(e=>{this.handleIncomingFrame(e)}),this.mySock.onerror=(e=>{this.log_("WebSocket error. Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()})}start(){}static forceDisallow(){We.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==Oe&&!We.forceDisallow_}static previouslyFailed(){return d.isInMemoryStorage||!0===d.get("previous_websocket_failure")}markConnectionHealthy(){d.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=(0,i.jsonEval)(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if((0,i.assert)(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=(0,i.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=q(t,Fe);n.length>1&&this.sendString_(String(n.length));for(let i=0;i<n.length;i++)this.sendString_(n[i])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(Le))}sendString_(e){try{this.mySock.send(e)}catch(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}We.responsesRequiredToBeHealthy=2,We.healthyTimeout=3e4;class Ue{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Me,We]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=We&&We.isAvailable();let n=t&&!We.previouslyFailed();if(e.webSocketOnly&&(t||k("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[We];else{const e=this.transports_=[];for(const t of Ue.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);Ue.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}Ue.globalTransportInitialized_=!1;const Be=6e4,je=5e3,He=10240,Ve=102400,ze="t",Ye="d",Qe="s",Ke="r",Ge="e",$e="o",Xe="a",Je="n",Ze="p",et="h";class tt{constructor(e,t,n,i,s,r,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=r,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=T("c:"+this.id+":"),this.transportManager_=new Ue(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Q(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Ve?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>He?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(ze in e){const t=e[ze];t===Xe?this.upgradeIfSecondaryHealthy_():t===Ke?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):t===$e&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=A("t",e),n=A("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:Ze,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:Xe,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Je,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=A("t",e),n=A("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=A(ze,e);if(Ye in e){const n=e[Ye];if(t===et){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if(t===Je){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else t===Qe?this.onConnectionShutdown_(n):t===Ke?this.onReset_(n):t===Ge?I("Server Error: "+n):t===$e?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):I("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,n=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),X!==n&&k("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Q(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(Be))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Q(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(je))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:Ze,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(d.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class nt{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class it{constructor(e){this.allowedEvents_=e,this.listeners_={},(0,i.assert)(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let s=0;s<i.length;s++)if(i[s].callback===t&&(!n||n===i[s].context))return void i.splice(s,1)}validateEventType_(e){(0,i.assert)(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class st extends it{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||(0,i.isMobileCordova)()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new st}getInitialEvent(e){return(0,i.assert)("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}const rt=32,ot=768;class at{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function lt(){return new at("")}function ht(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function ct(e){return e.pieces_.length-e.pieceNum_}function ut(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new at(e.pieces_,t)}function dt(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function _t(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}function pt(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function ft(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new at(t,0)}function mt(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof at)for(let i=t.pieceNum_;i<t.pieces_.length;i++)n.push(t.pieces_[i]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new at(n,0)}function gt(e){return e.pieceNum_>=e.pieces_.length}function yt(e,t){const n=ht(e),i=ht(t);if(null===n)return t;if(n===i)return yt(ut(e),ut(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function vt(e,t){const n=pt(e,0),i=pt(t,0);for(let s=0;s<n.length&&s<i.length;s++){const e=R(n[s],i[s]);if(0!==e)return e}return n.length===i.length?0:n.length<i.length?-1:1}function Ct(e,t){if(ct(e)!==ct(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function wt(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(ct(e)>ct(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class Tt{constructor(e,t){this.errorPrefix_=t,this.parts_=pt(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=(0,i.stringLength)(this.parts_[n]);kt(this)}}function It(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=(0,i.stringLength)(t),kt(e)}function bt(e){const t=e.parts_.pop();e.byteLength_-=(0,i.stringLength)(t),e.parts_.length>0&&(e.byteLength_-=1)}function kt(e){if(e.byteLength_>ot)throw new Error(e.errorPrefix_+"has a key path longer than "+ot+" bytes ("+e.byteLength_+").");if(e.parts_.length>rt)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+rt+") or object contains a cycle "+Et(e))}function Et(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class St extends it{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new St}getInitialEvent(e){return(0,i.assert)("visible"===e,"Unknown event type: "+e),[this.visible_]}}const xt=1e3,Pt=3e5,Nt=3e4,Rt=1.3,Dt=3e4,At="server_kill",Mt=3;class qt extends nt{constructor(e,t,n,s,r,o,a,l){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=s,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=l,this.id=qt.nextPersistentConnectionId_++,this.log_=T("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=xt,this.maxReconnectDelay_=Pt,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,l&&!(0,i.isNodeSdk)())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");St.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&st.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const s=++this.requestNumber_,r={r:s,a:e,b:t};this.log_((0,i.stringify)(r)),(0,i.assert)(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),n&&(this.requestCBHash_[s]=n)}get(e){this.initConnection_();const t=new i.Deferred,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const s=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(s),t.promise}listen(e,t,n,s){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),(0,i.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),(0,i.assert)(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:s,hashFn:t,query:e,tag:n};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(e){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const s={p:n};e.tag&&(s.q=t._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest("q",s,s=>{const r=s.d,o=s.s;qt.warnOnListenWarnings_(r,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",s),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,r))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&(0,i.contains)(e,"w")){const n=(0,i.safeGet)(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();k("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${e} at `+`${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||(0,i.isAdmin)(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=Nt)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=(0,i.isValidFormat)(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{const n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){const n=e._path.toString(),s=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+s),(0,i.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,s)&&this.connected_&&this.sendUnlisten_(n,s,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const s={p:e};i&&(s.q=n,s.t=i),this.sendRequest("n",s)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){const s={p:t,d:n};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,e=>{i&&setTimeout(()=>{i(e.s,e.d)},Math.floor(0))})}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,s){this.initConnection_();const r={p:t,d:n};void 0!==s&&(r.h=s),this.outstandingPuts_.push({action:e,request:r,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)})}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+(0,i.stringify)(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):I("Unrecognized action received from server: "+(0,i.stringify)(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){(0,i.assert)(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=xt,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=xt,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>Dt&&(this.reconnectDelay_=xt),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*Rt)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),s=this.id+":"+qt.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const l=function(){a?a.close():(o=!0,n())},h=function(e){(0,i.assert)(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:l,sendRequest:h};const c=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[i,h]=await Promise.all([this.authTokenProvider_.getToken(c),this.appCheckTokenProvider_.getToken(c)]);o?w("getToken() completed but was canceled"):(w("getToken() completed. Creating connection."),this.authToken_=i&&i.accessToken,this.appCheckToken_=h&&h.token,a=new tt(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,e=>{k(e+" ("+this.repoInfo_.toString()+")"),this.interrupt(At)},r))}catch(I){this.log_("Failed to get token: "+I),o||(this.repoInfo_.nodeAdmin&&k(I),l())}}}interrupt(e){w("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){w("Resuming connection for reason: "+e),delete this.interruptReasons_[e],(0,i.isEmpty)(this.interruptReasons_)&&(this.reconnectDelay_=xt,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>M(e)).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new at(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){w("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Mt&&(this.reconnectDelay_=Nt,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){w("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Mt&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let t="js";(0,i.isNodeSdk)()&&(t=this.repoInfo_.nodeAdmin?"admin_node":"node"),e["sdk."+t+"."+a.replace(/\./g,"-")]=1,(0,i.isMobileCordova)()?e["framework.cordova"]=1:(0,i.isReactNative)()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=st.getInstance().currentlyOnline();return(0,i.isEmpty)(this.interruptReasons_)&&e}}qt.nextPersistentConnectionId_=0,qt.nextConnectionId_=0;class Ft{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new Ft(e,t)}}class Lt{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new Ft(P,e),i=new Ft(P,t);return 0!==this.compare(n,i)}minPost(){return Ft.MIN}}let Ot;class Wt extends Lt{static get __EMPTY_NODE(){return Ot}static set __EMPTY_NODE(e){Ot=e}compare(e,t){return R(e.name,t.name)}isDefinedOn(e){throw(0,i.assertionError)("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return Ft.MIN}maxPost(){return new Ft(N,Ot)}makePost(e,t){return(0,i.assert)("string"==typeof e,"KeyIndex indexValue must always be a string."),new Ft(e,Ot)}toString(){return".key"}}const Ut=new Wt;class Bt{constructor(e,t,n,i,s=null){this.isReverse_=i,this.resultGenerator_=s,this.nodeStack_=[];let r=1;for(;!e.isEmpty();)if(e=e,r=t?n(e.key,t):1,i&&(r*=-1),r<0)e=this.isReverse_?e.left:e.right;else{if(0===r){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class jt{constructor(e,t,n,i,s){this.key=e,this.value=t,this.color=null!=n?n:jt.RED,this.left=null!=i?i:Vt.EMPTY_NODE,this.right=null!=s?s:Vt.EMPTY_NODE}copy(e,t,n,i,s){return new jt(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=s?s:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this;const s=n(e,i.key);return(i=s<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===s?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return Vt.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),(e=e.copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,i;if(t(e,(n=this).key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return Vt.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=(e=e.rotateRight_()).colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,jt.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,jt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}jt.RED=!0,jt.BLACK=!1;class Ht{copy(e,t,n,i,s){return this}insert(e,t,n){return new jt(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}}class Vt{constructor(e,t=Vt.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Vt(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,jt.BLACK,null,null))}remove(e){return new Vt(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,jt.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Bt(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Bt(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Bt(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Bt(this.root_,null,this.comparator_,!0,e)}}function zt(e,t){return R(e.name,t.name)}function Yt(e,t){return R(e,t)}let Qt;function Kt(e){Qt=e}Vt.EMPTY_NODE=new Ht;const Gt=function(e){return"number"==typeof e?"number:"+L(e):"string:"+e},$t=function(e){if(e.isLeafNode()){const t=e.val();(0,i.assert)("string"==typeof t||"number"==typeof t||"object"==typeof t&&(0,i.contains)(t,".sv"),"Priority must be a string or number.")}else(0,i.assert)(e===Qt||e.isEmpty(),"priority of unexpected type.");(0,i.assert)(e===Qt||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Xt,Jt,Zt;class en{constructor(e,t=en.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,(0,i.assert)(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),$t(this.priorityNode_)}static set __childrenNodeConstructor(e){Xt=e}static get __childrenNodeConstructor(){return Xt}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new en(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:en.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return gt(e)?this:".priority"===ht(e)?this.priorityNode_:en.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:en.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=ht(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:((0,i.assert)(".priority"!==n||1===ct(e),".priority must be the last token in a path"),this.updateImmediateChild(n,en.__childrenNodeConstructor.EMPTY_NODE.updateChild(ut(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+Gt(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?L(this.value_):this.value_,this.lazyHash_=m(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===en.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof en.__childrenNodeConstructor?-1:((0,i.assert)(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,s=en.VALUE_TYPE_ORDER.indexOf(t),r=en.VALUE_TYPE_ORDER.indexOf(n);return(0,i.assert)(s>=0,"Unknown leaf type: "+t),(0,i.assert)(r>=0,"Unknown leaf type: "+n),s===r?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-s}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}function tn(e){Jt=e}function nn(e){Zt=e}en.VALUE_TYPE_ORDER=["object","boolean","number","string"];class sn extends Lt{compare(e,t){const n=e.node.getPriority(),i=t.node.getPriority(),s=n.compareTo(i);return 0===s?R(e.name,t.name):s}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return Ft.MIN}maxPost(){return new Ft(N,new en("[PRIORITY-POST]",Zt))}makePost(e,t){const n=Jt(e);return new Ft(t,new en("[PRIORITY-POST]",n))}toString(){return".priority"}}const rn=new sn,on=Math.log(2);class an{constructor(e){this.count=(e=>parseInt(Math.log(e)/on,10))(e+1),this.current_=this.count-1;const t=(e=>parseInt(Array(e+1).join("1"),2))(this.count);this.bits_=e+1&t}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const ln=function(e,t,n,i){e.sort(t);const s=function(t,i){const r=i-t;let o,a;if(0===r)return null;if(1===r)return o=e[t],a=n?n(o):o,new jt(a,o.node,jt.BLACK,null,null);{const l=parseInt(r/2,10)+t,h=s(t,l),c=s(l+1,i);return o=e[l],a=n?n(o):o,new jt(a,o.node,jt.BLACK,h,c)}},r=function(t){let i=null,r=null,o=e.length;const a=function(t,i){const r=o-t,a=o;o-=t;const h=s(r+1,a),c=e[r],u=n?n(c):c;l(new jt(u,c.node,i,null,h))},l=function(e){i?(i.left=e,i=e):(r=e,i=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?a(i,jt.BLACK):(a(i,jt.BLACK),a(i,jt.RED))}return r}(new an(e.length));return new Vt(i||t,r)};let hn;const cn={};class un{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,i.assert)(cn&&rn,"ChildrenNode.ts has not been loaded"),hn=hn||new un({".priority":cn},{".priority":rn})}get(e){const t=(0,i.safeGet)(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Vt?t:null}hasIndex(e){return(0,i.contains)(this.indexSet_,e.toString())}addIndex(e,t){(0,i.assert)(e!==Ut,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let s=!1;const r=t.getIterator(Ft.Wrap);let o,a=r.getNext();for(;a;)s=s||e.isDefinedOn(a.node),n.push(a),a=r.getNext();o=s?ln(n,e.getCompare()):cn;const l=e.toString(),h=Object.assign({},this.indexSet_);h[l]=e;const c=Object.assign({},this.indexes_);return c[l]=o,new un(c,h)}addToIndexes(e,t){const n=(0,i.map)(this.indexes_,(n,s)=>{const r=(0,i.safeGet)(this.indexSet_,s);if((0,i.assert)(r,"Missing index implementation for "+s),n===cn){if(r.isDefinedOn(e.node)){const n=[],i=t.getIterator(Ft.Wrap);let s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),ln(n,r.getCompare())}return cn}{const i=t.get(e.name);let s=n;return i&&(s=s.remove(new Ft(e.name,i))),s.insert(e,e.node)}});return new un(n,this.indexSet_)}removeFromIndexes(e,t){const n=(0,i.map)(this.indexes_,n=>{if(n===cn)return n;{const i=t.get(e.name);return i?n.remove(new Ft(e.name,i)):n}});return new un(n,this.indexSet_)}}let dn;class _n{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&$t(this.priorityNode_),this.children_.isEmpty()&&(0,i.assert)(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return dn||(dn=new _n(new Vt(Yt),null,un.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||dn}updatePriority(e){return this.children_.isEmpty()?this:new _n(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?dn:t}}getChild(e){const t=ht(e);return null===t?this:this.getImmediateChild(t).getChild(ut(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if((0,i.assert)(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new Ft(e,t);let i,s;t.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),s=this.indexMap_.addToIndexes(n,this.children_));const r=i.isEmpty()?dn:this.priorityNode_;return new _n(i,r,s)}}updateChild(e,t){const n=ht(e);if(null===n)return t;{(0,i.assert)(".priority"!==ht(e)||1===ct(e),".priority must be the last token in a path");const s=this.getImmediateChild(n).updateChild(ut(e),t);return this.updateImmediateChild(n,s)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,s=!0;if(this.forEachChild(rn,(r,o)=>{t[r]=o.val(e),n++,s&&_n.INTEGER_REGEXP_.test(r)?i=Math.max(i,Number(r)):s=!1}),!e&&s&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Gt(this.getPriority().val())+":"),this.forEachChild(rn,(t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)}),this.lazyHash_=""===e?"":m(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new Ft(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new Ft(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new Ft(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{const n=this.children_.getIteratorFrom(e.name,Ft.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{const n=this.children_.getReverseIteratorFrom(e.name,Ft.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===fn?-1:0}withIndex(e){if(e===Ut||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new _n(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Ut||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(rn),n=t.getIterator(rn);let i=e.getNext(),s=n.getNext();for(;i&&s;){if(i.name!==s.name||!i.node.equals(s.node))return!1;i=e.getNext(),s=n.getNext()}return null===i&&null===s}return!1}return!1}}resolveIndex_(e){return e===Ut?null:this.indexMap_.get(e.toString())}}_n.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class pn extends _n{constructor(){super(new Vt(Yt),_n.EMPTY_NODE,un.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return _n.EMPTY_NODE}isEmpty(){return!1}}const fn=new pn;Object.defineProperties(Ft,{MIN:{value:new Ft(P,_n.EMPTY_NODE)},MAX:{value:new Ft(N,fn)}}),Wt.__EMPTY_NODE=_n.EMPTY_NODE,en.__childrenNodeConstructor=_n,Kt(fn),nn(fn);const mn=!0;function gn(e,t=null){if(null===e)return _n.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),(0,i.assert)(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){return new en(e,gn(t))}if(e instanceof Array||!mn){let n=_n.EMPTY_NODE;return F(e,(t,s)=>{if((0,i.contains)(e,t)&&"."!==t.substring(0,1)){const e=gn(s);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}}),n.updatePriority(gn(t))}{const n=[];let i=!1;if(F(e,(e,t)=>{if("."!==e.substring(0,1)){const s=gn(t);s.isEmpty()||(i=i||!s.getPriority().isEmpty(),n.push(new Ft(e,s)))}}),0===n.length)return _n.EMPTY_NODE;const s=ln(n,zt,e=>e.name,Yt);if(i){const e=ln(n,rn.getCompare());return new _n(s,gn(t),new un({".priority":e},{".priority":rn}))}return new _n(s,gn(t),un.Default)}}tn(gn);class yn extends Lt{constructor(e){super(),this.indexPath_=e,(0,i.assert)(!gt(e)&&".priority"!==ht(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),i=this.extractChild(t.node),s=n.compareTo(i);return 0===s?R(e.name,t.name):s}makePost(e,t){const n=gn(e),i=_n.EMPTY_NODE.updateChild(this.indexPath_,n);return new Ft(t,i)}maxPost(){const e=_n.EMPTY_NODE.updateChild(this.indexPath_,fn);return new Ft(N,e)}toString(){return pt(this.indexPath_,0).join("/")}}class vn extends Lt{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?R(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return Ft.MIN}maxPost(){return Ft.MAX}makePost(e,t){const n=gn(e);return new Ft(t,n)}toString(){return".value"}}const Cn=new vn;function wn(e){return{type:"value",snapshotNode:e}}function Tn(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function In(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function bn(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}function kn(e,t){return{type:"child_moved",snapshotNode:t,childName:e}}class En{constructor(e){this.index_=e}updateChild(e,t,n,s,r,o){(0,i.assert)(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(s).equals(n.getChild(s))&&a.isEmpty()===n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(In(t,a)):(0,i.assert)(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Tn(t,n)):o.trackChildChange(bn(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(rn,(e,i)=>{t.hasChild(e)||n.trackChildChange(In(e,i))}),t.isLeafNode()||t.forEachChild(rn,(t,i)=>{if(e.hasChild(t)){const s=e.getImmediateChild(t);s.equals(i)||n.trackChildChange(bn(t,i,s))}else n.trackChildChange(Tn(t,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?_n.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Sn{constructor(e){this.indexedFilter_=new En(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Sn.getStartPost_(e),this.endPost_=Sn.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,i,s,r){return this.matches(new Ft(t,n))||(n=_n.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,s,r)}updateFullNode(e,t,n){t.isLeafNode()&&(t=_n.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(_n.EMPTY_NODE);const s=this;return t.forEachChild(rn,(e,t)=>{s.matches(new Ft(e,t))||(i=i.updateImmediateChild(e,_n.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class xn{constructor(e){this.withinDirectionalStart=(e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e)),this.withinDirectionalEnd=(e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e)),this.withinStartPost=(e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0}),this.withinEndPost=(e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0}),this.rangedFilter_=new Sn(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,i,s,r){return this.rangedFilter_.matches(new Ft(t,n))||(n=_n.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,i,s,r):this.fullLimitUpdateChild_(e,t,n,s,r)}updateFullNode(e,t,n){let i;if(t.isLeafNode()||t.isEmpty())i=_n.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=_n.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;i=i.updateImmediateChild(t.name,t.node),n++}}}else{let e;i=(i=t.withIndex(this.index_)).updatePriority(_n.EMPTY_NODE),e=this.reverse_?i.getReverseIterator(this.index_):i.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:i=i.updateImmediateChild(t.name,_n.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,s,r){let o;if(this.reverse_){const e=this.index_.getCompare();o=((t,n)=>e(n,t))}else o=this.index_.getCompare();const a=e;(0,i.assert)(a.numChildren()===this.limit_,"");const l=new Ft(t,n),h=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),c=this.rangedFilter_.matches(l);if(a.hasChild(t)){const e=a.getImmediateChild(t);let i=s.getChildAfterChild(this.index_,h,this.reverse_);for(;null!=i&&(i.name===t||a.hasChild(i.name));)i=s.getChildAfterChild(this.index_,i,this.reverse_);const u=null==i?1:o(i,l);if(c&&!n.isEmpty()&&u>=0)return null!=r&&r.trackChildChange(bn(t,n,e)),a.updateImmediateChild(t,n);{null!=r&&r.trackChildChange(In(t,e));const n=a.updateImmediateChild(t,_n.EMPTY_NODE);return null!=i&&this.rangedFilter_.matches(i)?(null!=r&&r.trackChildChange(Tn(i.name,i.node)),n.updateImmediateChild(i.name,i.node)):n}}return n.isEmpty()?e:c&&o(h,l)>=0?(null!=r&&(r.trackChildChange(In(h.name,h.node)),r.trackChildChange(Tn(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(h.name,_n.EMPTY_NODE)):e}}class Pn{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=rn}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return(0,i.assert)(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return(0,i.assert)(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:P}hasEnd(){return this.endSet_}getIndexEndValue(){return(0,i.assert)(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return(0,i.assert)(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:N}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return(0,i.assert)(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===rn}copy(){const e=new Pn;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function Nn(e){return e.loadsAllData()?new En(e.getIndex()):e.hasLimit()?new xn(e):new Sn(e)}function Rn(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}function Dn(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}function An(e,t,n){const i=e.copy();return i.startSet_=!0,void 0===t&&(t=null),i.indexStartValue_=t,null!=n?(i.startNameSet_=!0,i.indexStartName_=n):(i.startNameSet_=!1,i.indexStartName_=""),i}function Mn(e,t,n){let i;return(i=e.index_===Ut||n?An(e,t,n):An(e,t,N)).startAfterSet_=!0,i}function qn(e,t,n){const i=e.copy();return i.endSet_=!0,void 0===t&&(t=null),i.indexEndValue_=t,void 0!==n?(i.endNameSet_=!0,i.indexEndName_=n):(i.endNameSet_=!1,i.indexEndName_=""),i}function Fn(e,t,n){let i;return(i=e.index_===Ut||n?qn(e,t,n):qn(e,t,P)).endBeforeSet_=!0,i}function Ln(e,t){const n=e.copy();return n.index_=t,n}function On(e){const t={};if(e.isDefault())return t;let n;if(e.index_===rn?n="$priority":e.index_===Cn?n="$value":e.index_===Ut?n="$key":((0,i.assert)(e.index_ instanceof yn,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=(0,i.stringify)(n),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=(0,i.stringify)(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+(0,i.stringify)(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=(0,i.stringify)(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+(0,i.stringify)(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Wn(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==rn&&(t.i=e.index_.toString()),t}exports._QueryParams=Pn;class Un extends nt{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=T("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:((0,i.assert)(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,s){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=Un.getListenId_(e,n),a={};this.listens_[o]=a;const l=On(e._queryParams);this.restRequest_(r+".json",l,(e,t)=>{let l=t;if(404===e&&(l=null,e=null),null===e&&this.onDataUpdate_(r,l,!1,n),(0,i.safeGet)(this.listens_,o)===a){let t;s(t=e?401===e?"permission_denied":"rest_error:"+e:"ok",null)}})}unlisten(e,t){const n=Un.getListenId_(e,t);delete this.listens_[n]}get(e){const t=On(e._queryParams),n=e._path.toString(),s=new i.Deferred;return this.restRequest_(n+".json",t,(e,t)=>{let i=t;404===e&&(i=null,e=null),null===e?(this.onDataUpdate_(n,i,!1,null),s.resolve(i)):s.reject(new Error(i))}),s.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([s,r])=>{s&&s.accessToken&&(t.auth=s.accessToken),r&&r.token&&(t.ac=r.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+(0,i.querystring)(t);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=(()=>{if(n&&4===a.readyState){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let t=null;if(a.status>=200&&a.status<300){try{t=(0,i.jsonEval)(a.responseText)}catch(e){k("Failed to parse JSON response for "+o+": "+a.responseText)}n(null,t)}else 401!==a.status&&404!==a.status&&k("Got unsuccessful REST response for "+o+" Status: "+a.status),n(a.status);n=null}}),a.open("GET",o,!0),a.send()})}}class Bn{constructor(){this.rootNode_=_n.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function jn(){return{value:null,children:new Map}}function Hn(e,t,n){if(gt(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=ht(t);e.children.has(i)||e.children.set(i,jn()),Hn(e.children.get(i),t=ut(t),n)}}function Vn(e,t){if(gt(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(rn,(t,n)=>{Hn(e,new at(t),n)}),Vn(e,t)}}if(e.children.size>0){const n=ht(t);if(t=ut(t),e.children.has(n)){Vn(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function zn(e,t,n){null!==e.value?n(t,e.value):Yn(e,(e,i)=>{zn(i,new at(t.toString()+"/"+e),n)})}function Yn(e,t){e.children.forEach((e,n)=>{t(n,e)})}class Qn{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&F(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}const Kn=1e4,Gn=3e4,$n=3e5;class Xn{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Qn(e);const n=Kn+(Gn-Kn)*Math.random();Q(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;F(e,(e,s)=>{s>0&&(0,i.contains)(this.statsToReport_,e)&&(t[e]=s,n=!0)}),n&&this.server_.reportStats(t),Q(this.reportStats_.bind(this),Math.floor(2*Math.random()*$n))}}var Jn;function Zn(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function ei(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function ti(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(Jn||(Jn={}));class ni{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Jn.ACK_USER_WRITE,this.source=Zn()}operationForChild(e){if(gt(this.path)){if(null!=this.affectedTree.value)return(0,i.assert)(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new at(e));return new ni(lt(),t,this.revert)}}return(0,i.assert)(ht(this.path)===e,"operationForChild called for unrelated child."),new ni(ut(this.path),this.affectedTree,this.revert)}}class ii{constructor(e,t){this.source=e,this.path=t,this.type=Jn.LISTEN_COMPLETE}operationForChild(e){return gt(this.path)?new ii(this.source,lt()):new ii(this.source,ut(this.path))}}class si{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Jn.OVERWRITE}operationForChild(e){return gt(this.path)?new si(this.source,lt(),this.snap.getImmediateChild(e)):new si(this.source,ut(this.path),this.snap)}}class ri{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Jn.MERGE}operationForChild(e){if(gt(this.path)){const t=this.children.subtree(new at(e));return t.isEmpty()?null:t.value?new si(this.source,lt(),t.value):new ri(this.source,lt(),t)}return(0,i.assert)(ht(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new ri(this.source,ut(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class oi{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(gt(e))return this.isFullyInitialized()&&!this.filtered_;const t=ht(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class ai{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function li(e,t,n,i){const s=[],r=[];return t.forEach(t=>{"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&r.push(kn(t.childName,t.snapshotNode))}),hi(e,s,"child_removed",t,i,n),hi(e,s,"child_added",t,i,n),hi(e,s,"child_moved",r,i,n),hi(e,s,"child_changed",t,i,n),hi(e,s,"value",t,i,n),s}function hi(e,t,n,i,s,r){const o=i.filter(e=>e.type===n);o.sort((t,n)=>ui(e,t,n)),o.forEach(n=>{const i=ci(e,n,r);s.forEach(s=>{s.respondsTo(n.type)&&t.push(s.createEvent(i,e.query_))})})}function ci(e,t,n){return"value"===t.type||"child_removed"===t.type?t:(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_),t)}function ui(e,t,n){if(null==t.childName||null==n.childName)throw(0,i.assertionError)("Should only compare child_ events.");const s=new Ft(t.childName,t.snapshotNode),r=new Ft(n.childName,n.snapshotNode);return e.index_.compare(s,r)}function di(e,t){return{eventCache:e,serverCache:t}}function _i(e,t,n,i){return di(new oi(t,n,i),e.serverCache)}function pi(e,t,n,i){return di(e.eventCache,new oi(t,n,i))}function fi(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function mi(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let gi;const yi=()=>(gi||(gi=new Vt(D)),gi);class vi{constructor(e,t=yi()){this.value=e,this.children=t}static fromObject(e){let t=new vi(null);return F(e,(e,n)=>{t=t.set(new at(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:lt(),value:this.value};if(gt(e))return null;{const n=ht(e),i=this.children.get(n);if(null!==i){const s=i.findRootMostMatchingPathAndValue(ut(e),t);if(null!=s){return{path:mt(new at(n),s.path),value:s.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(gt(e))return this;{const t=ht(e),n=this.children.get(t);return null!==n?n.subtree(ut(e)):new vi(null)}}set(e,t){if(gt(e))return new vi(t,this.children);{const n=ht(e),i=(this.children.get(n)||new vi(null)).set(ut(e),t),s=this.children.insert(n,i);return new vi(this.value,s)}}remove(e){if(gt(e))return this.children.isEmpty()?new vi(null):new vi(null,this.children);{const t=ht(e),n=this.children.get(t);if(n){const i=n.remove(ut(e));let s;return s=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&s.isEmpty()?new vi(null):new vi(this.value,s)}return this}}get(e){if(gt(e))return this.value;{const t=ht(e),n=this.children.get(t);return n?n.get(ut(e)):null}}setTree(e,t){if(gt(e))return t;{const n=ht(e),i=(this.children.get(n)||new vi(null)).setTree(ut(e),t);let s;return s=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new vi(this.value,s)}}fold(e){return this.fold_(lt(),e)}fold_(e,t){const n={};return this.children.inorderTraversal((i,s)=>{n[i]=s.fold_(mt(e,i),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,lt(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(gt(e))return null;{const i=ht(e),s=this.children.get(i);return s?s.findOnPath_(ut(e),mt(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,lt(),t)}foreachOnPath_(e,t,n){if(gt(e))return this;{this.value&&n(t,this.value);const i=ht(e),s=this.children.get(i);return s?s.foreachOnPath_(ut(e),mt(t,i),n):new vi(null)}}foreach(e){this.foreach_(lt(),e)}foreach_(e,t){this.children.inorderTraversal((n,i)=>{i.foreach_(mt(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}class Ci{constructor(e){this.writeTree_=e}static empty(){return new Ci(new vi(null))}}function wi(e,t,n){if(gt(t))return new Ci(new vi(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const s=i.path;let r=i.value;const o=yt(s,t);return r=r.updateChild(o,n),new Ci(e.writeTree_.set(s,r))}{const i=new vi(n),s=e.writeTree_.setTree(t,i);return new Ci(s)}}}function Ti(e,t,n){let i=e;return F(n,(e,n)=>{i=wi(i,mt(t,e),n)}),i}function Ii(e,t){if(gt(t))return Ci.empty();{const n=e.writeTree_.setTree(t,new vi(null));return new Ci(n)}}function bi(e,t){return null!=ki(e,t)}function ki(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(yt(n.path,t)):null}function Ei(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(rn,(e,n)=>{t.push(new Ft(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new Ft(e,n.value))}),t}function Si(e,t){if(gt(t))return e;{const n=ki(e,t);return new Ci(null!=n?new vi(n):e.writeTree_.subtree(t))}}function xi(e){return e.writeTree_.isEmpty()}function Pi(e,t){return Ni(lt(),e.writeTree_,t)}function Ni(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let s=null;return t.children.inorderTraversal((t,r)=>{".priority"===t?((0,i.assert)(null!==r.value,"Priority writes must always be leaf nodes"),s=r.value):n=Ni(mt(e,t),r,n)}),n.getChild(e).isEmpty()||null===s||(n=n.updateChild(mt(e,".priority"),s)),n}}function Ri(e,t){return es(t,e)}function Di(e,t,n,s,r){(0,i.assert)(s>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),e.allWrites.push({path:t,snap:n,writeId:s,visible:r}),r&&(e.visibleWrites=wi(e.visibleWrites,t,n)),e.lastWriteId=s}function Ai(e,t,n,s){(0,i.assert)(s>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:s,visible:!0}),e.visibleWrites=Ti(e.visibleWrites,t,n),e.lastWriteId=s}function Mi(e,t){for(let n=0;n<e.allWrites.length;n++){const i=e.allWrites[n];if(i.writeId===t)return i}return null}function qi(e,t){const n=e.allWrites.findIndex(e=>e.writeId===t);(0,i.assert)(n>=0,"removeWrite called with nonexistent writeId.");const s=e.allWrites[n];e.allWrites.splice(n,1);let r=s.visible,o=!1,a=e.allWrites.length-1;for(;r&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=n&&Fi(t,s.path)?r=!1:wt(s.path,t.path)&&(o=!0)),a--}if(r){if(o)return Li(e),!0;if(s.snap)e.visibleWrites=Ii(e.visibleWrites,s.path);else{F(s.children,t=>{e.visibleWrites=Ii(e.visibleWrites,mt(s.path,t))})}return!0}return!1}function Fi(e,t){if(e.snap)return wt(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&wt(mt(e.path,n),t))return!0;return!1}function Li(e){e.visibleWrites=Wi(e.allWrites,Oi,lt()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}function Oi(e){return e.visible}function Wi(e,t,n){let s=Ci.empty();for(let r=0;r<e.length;++r){const o=e[r];if(t(o)){const e=o.path;let t;if(o.snap)wt(n,e)?s=wi(s,t=yt(n,e),o.snap):wt(e,n)&&(t=yt(e,n),s=wi(s,lt(),o.snap.getChild(t)));else{if(!o.children)throw(0,i.assertionError)("WriteRecord should have .snap or .children");if(wt(n,e))s=Ti(s,t=yt(n,e),o.children);else if(wt(e,n))if(gt(t=yt(e,n)))s=Ti(s,lt(),o.children);else{const e=(0,i.safeGet)(o.children,ht(t));if(e){const n=e.getChild(ut(t));s=wi(s,lt(),n)}}}}}return s}function Ui(e,t,n,i,s){if(i||s){const r=Si(e.visibleWrites,t);if(!s&&xi(r))return n;if(s||null!=n||bi(r,lt())){const r=function(e){return(e.visible||s)&&(!i||!~i.indexOf(e.writeId))&&(wt(e.path,t)||wt(t,e.path))};return Pi(Wi(e.allWrites,r,t),n||_n.EMPTY_NODE)}return null}{const i=ki(e.visibleWrites,t);if(null!=i)return i;{const i=Si(e.visibleWrites,t);if(xi(i))return n;if(null!=n||bi(i,lt())){return Pi(i,n||_n.EMPTY_NODE)}return null}}}function Bi(e,t,n){let i=_n.EMPTY_NODE;const s=ki(e.visibleWrites,t);if(s)return s.isLeafNode()||s.forEachChild(rn,(e,t)=>{i=i.updateImmediateChild(e,t)}),i;if(n){const s=Si(e.visibleWrites,t);return n.forEachChild(rn,(e,t)=>{const n=Pi(Si(s,new at(e)),t);i=i.updateImmediateChild(e,n)}),Ei(s).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}return Ei(Si(e.visibleWrites,t)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}function ji(e,t,n,s,r){(0,i.assert)(s||r,"Either existingEventSnap or existingServerSnap must exist");const o=mt(t,n);if(bi(e.visibleWrites,o))return null;{const t=Si(e.visibleWrites,o);return xi(t)?r.getChild(n):Pi(t,r.getChild(n))}}function Hi(e,t,n,i){const s=mt(t,n),r=ki(e.visibleWrites,s);if(null!=r)return r;if(i.isCompleteForChild(n)){return Pi(Si(e.visibleWrites,s),i.getNode().getImmediateChild(n))}return null}function Vi(e,t){return ki(e.visibleWrites,t)}function zi(e,t,n,i,s,r,o){let a;const l=Si(e.visibleWrites,t),h=ki(l,lt());if(null!=h)a=h;else{if(null==n)return[];a=Pi(l,n)}if((a=a.withIndex(o)).isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=r?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let l=n.getNext();for(;l&&e.length<s;)0!==t(l,i)&&e.push(l),l=n.getNext();return e}}function Yi(){return{visibleWrites:Ci.empty(),allWrites:[],lastWriteId:-1}}function Qi(e,t,n,i){return Ui(e.writeTree,e.treePath,t,n,i)}function Ki(e,t){return Bi(e.writeTree,e.treePath,t)}function Gi(e,t,n,i){return ji(e.writeTree,e.treePath,t,n,i)}function $i(e,t){return Vi(e.writeTree,mt(e.treePath,t))}function Xi(e,t,n,i,s,r){return zi(e.writeTree,e.treePath,t,n,i,s,r)}function Ji(e,t,n){return Hi(e.writeTree,e.treePath,t,n)}function Zi(e,t){return es(mt(e.treePath,t),e.writeTree)}function es(e,t){return{treePath:e,writeTree:t}}class ts{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;(0,i.assert)("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),(0,i.assert)(".priority"!==n,"Only non-priority child changes can be tracked.");const s=this.changeMap.get(n);if(s){const r=s.type;if("child_added"===t&&"child_removed"===r)this.changeMap.set(n,bn(n,e.snapshotNode,s.snapshotNode));else if("child_removed"===t&&"child_added"===r)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===r)this.changeMap.set(n,In(n,s.oldSnap));else if("child_changed"===t&&"child_added"===r)this.changeMap.set(n,Tn(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==r)throw(0,i.assertionError)("Illegal combination of changes: "+e+" occurred after "+s);this.changeMap.set(n,bn(n,e.snapshotNode,s.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}class ns{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}}const is=new ns;class ss{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new oi(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Ji(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:mi(this.viewCache_),s=Xi(this.writes_,i,t,1,n,e);return 0===s.length?null:s[0]}}function rs(e){return{filter:e}}function os(e,t){(0,i.assert)(t.eventCache.getNode().isIndexed(e.filter.getIndex()),"Event snap not indexed"),(0,i.assert)(t.serverCache.getNode().isIndexed(e.filter.getIndex()),"Server snap not indexed")}function as(e,t,n,s,r){const o=new ts;let a,l;if(n.type===Jn.OVERWRITE){const h=n;h.source.fromUser?a=us(e,t,h.path,h.snap,s,r,o):((0,i.assert)(h.source.fromServer,"Unknown source."),l=h.source.tagged||t.serverCache.isFiltered()&&!gt(h.path),a=cs(e,t,h.path,h.snap,s,r,l,o))}else if(n.type===Jn.MERGE){const h=n;h.source.fromUser?a=_s(e,t,h.path,h.children,s,r,o):((0,i.assert)(h.source.fromServer,"Unknown source."),l=h.source.tagged||t.serverCache.isFiltered(),a=fs(e,t,h.path,h.children,s,r,l,o))}else if(n.type===Jn.ACK_USER_WRITE){const i=n;a=i.revert?ys(e,t,i.path,s,r,o):ms(e,t,i.path,i.affectedTree,s,r,o)}else{if(n.type!==Jn.LISTEN_COMPLETE)throw(0,i.assertionError)("Unknown operation type: "+n.type);a=gs(e,t,n.path,s,o)}const h=o.getChanges();return ls(t,a,h),{viewCache:a,changes:h}}function ls(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const s=i.getNode().isLeafNode()||i.getNode().isEmpty(),r=fi(e);(n.length>0||!e.eventCache.isFullyInitialized()||s&&!i.getNode().equals(r)||!i.getNode().getPriority().equals(r.getPriority()))&&n.push(wn(fi(t)))}}function hs(e,t,n,s,r,o){const a=t.eventCache;if(null!=$i(s,n))return t;{let l,h;if(gt(n))if((0,i.assert)(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=mi(t),i=Ki(s,n instanceof _n?n:_n.EMPTY_NODE);l=e.filter.updateFullNode(t.eventCache.getNode(),i,o)}else{const n=Qi(s,mi(t));l=e.filter.updateFullNode(t.eventCache.getNode(),n,o)}else{const c=ht(n);if(".priority"===c){(0,i.assert)(1===ct(n),"Can't have a priority with additional path components");const r=a.getNode(),o=Gi(s,n,r,h=t.serverCache.getNode());l=null!=o?e.filter.updatePriority(r,o):a.getNode()}else{const i=ut(n);let u;if(a.isCompleteForChild(c)){h=t.serverCache.getNode();const e=Gi(s,n,a.getNode(),h);u=null!=e?a.getNode().getImmediateChild(c).updateChild(i,e):a.getNode().getImmediateChild(c)}else u=Ji(s,c,t.serverCache);l=null!=u?e.filter.updateChild(a.getNode(),c,u,i,r,o):a.getNode()}}return _i(t,l,a.isFullyInitialized()||gt(n),e.filter.filtersNodes())}}function cs(e,t,n,i,s,r,o,a){const l=t.serverCache;let h;const c=o?e.filter:e.filter.getIndexedFilter();if(gt(n))h=c.updateFullNode(l.getNode(),i,null);else if(c.filtersNodes()&&!l.isFiltered()){const e=l.getNode().updateChild(n,i);h=c.updateFullNode(l.getNode(),e,null)}else{const e=ht(n);if(!l.isCompleteForPath(n)&&ct(n)>1)return t;const s=ut(n),r=l.getNode().getImmediateChild(e).updateChild(s,i);h=".priority"===e?c.updatePriority(l.getNode(),r):c.updateChild(l.getNode(),e,r,s,is,null)}const u=pi(t,h,l.isFullyInitialized()||gt(n),c.filtersNodes());return hs(e,u,n,s,new ss(s,u,r),a)}function us(e,t,n,i,s,r,o){const a=t.eventCache;let l,h;const c=new ss(s,t,r);if(gt(n))h=e.filter.updateFullNode(t.eventCache.getNode(),i,o),l=_i(t,h,!0,e.filter.filtersNodes());else{const s=ht(n);if(".priority"===s)h=e.filter.updatePriority(t.eventCache.getNode(),i),l=_i(t,h,a.isFullyInitialized(),a.isFiltered());else{const r=ut(n),h=a.getNode().getImmediateChild(s);let u;if(gt(r))u=i;else{const e=c.getCompleteChild(s);u=null!=e?".priority"===dt(r)&&e.getChild(ft(r)).isEmpty()?e:e.updateChild(r,i):_n.EMPTY_NODE}if(h.equals(u))l=t;else{l=_i(t,e.filter.updateChild(a.getNode(),s,u,r,c,o),a.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function ds(e,t){return e.eventCache.isCompleteForChild(t)}function _s(e,t,n,i,s,r,o){let a=t;return i.foreach((i,l)=>{const h=mt(n,i);ds(t,ht(h))&&(a=us(e,a,h,l,s,r,o))}),i.foreach((i,l)=>{const h=mt(n,i);ds(t,ht(h))||(a=us(e,a,h,l,s,r,o))}),a}function ps(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function fs(e,t,n,i,s,r,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l,h=t;l=gt(n)?i:new vi(null).setTree(n,i);const c=t.serverCache.getNode();return l.children.inorderTraversal((n,i)=>{if(c.hasChild(n)){const l=t.serverCache.getNode().getImmediateChild(n),c=ps(e,l,i);h=cs(e,h,new at(n),c,s,r,o,a)}}),l.children.inorderTraversal((n,i)=>{const l=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!c.hasChild(n)&&!l){const l=t.serverCache.getNode().getImmediateChild(n),c=ps(e,l,i);h=cs(e,h,new at(n),c,s,r,o,a)}}),h}function ms(e,t,n,i,s,r,o){if(null!=$i(s,n))return t;const a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=i.value){if(gt(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return cs(e,t,n,l.getNode().getChild(n),s,r,a,o);if(gt(n)){let i=new vi(null);return l.getNode().forEachChild(Ut,(e,t)=>{i=i.set(new at(e),t)}),fs(e,t,n,i,s,r,a,o)}return t}{let h=new vi(null);return i.foreach((e,t)=>{const i=mt(n,e);l.isCompleteForPath(i)&&(h=h.set(e,l.getNode().getChild(i)))}),fs(e,t,n,h,s,r,a,o)}}function gs(e,t,n,i,s){const r=t.serverCache;return hs(e,pi(t,r.getNode(),r.isFullyInitialized()||gt(n),r.isFiltered()),n,i,is,s)}function ys(e,t,n,s,r,o){let a;if(null!=$i(s,n))return t;{const l=new ss(s,t,r),h=t.eventCache.getNode();let c;if(gt(n)||".priority"===ht(n)){let n;if(t.serverCache.isFullyInitialized())n=Qi(s,mi(t));else{const e=t.serverCache.getNode();(0,i.assert)(e instanceof _n,"serverChildren would be complete if leaf node"),n=Ki(s,e)}n=n,c=e.filter.updateFullNode(h,n,o)}else{const i=ht(n);let r=Ji(s,i,t.serverCache);null==r&&t.serverCache.isCompleteForChild(i)&&(r=h.getImmediateChild(i)),(c=null!=r?e.filter.updateChild(h,i,r,ut(n),l,o):t.eventCache.getNode().hasChild(i)?e.filter.updateChild(h,i,_n.EMPTY_NODE,ut(n),l,o):h).isEmpty()&&t.serverCache.isFullyInitialized()&&(a=Qi(s,mi(t))).isLeafNode()&&(c=e.filter.updateFullNode(c,a,o))}return a=t.serverCache.isFullyInitialized()||null!=$i(s,lt()),_i(t,c,a,e.filter.filtersNodes())}}class vs{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,i=new En(n.getIndex()),s=Nn(n);this.processor_=rs(s);const r=t.serverCache,o=t.eventCache,a=i.updateFullNode(_n.EMPTY_NODE,r.getNode(),null),l=s.updateFullNode(_n.EMPTY_NODE,o.getNode(),null),h=new oi(a,r.isFullyInitialized(),i.filtersNodes()),c=new oi(l,o.isFullyInitialized(),s.filtersNodes());this.viewCache_=di(c,h),this.eventGenerator_=new ai(this.query_)}get query(){return this.query_}}function Cs(e){return e.viewCache_.serverCache.getNode()}function ws(e){return fi(e.viewCache_)}function Ts(e,t){const n=mi(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!gt(t)&&!n.getImmediateChild(ht(t)).isEmpty())?n.getChild(t):null}function Is(e){return 0===e.eventRegistrations_.length}function bs(e,t){e.eventRegistrations_.push(t)}function ks(e,t,n){const s=[];if(n){(0,i.assert)(null==t,"A cancel should cancel all event registrations.");const r=e.query._path;e.eventRegistrations_.forEach(e=>{const t=e.createCancelEvent(n,r);t&&s.push(t)})}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){const s=e.eventRegistrations_[i];if(s.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(i+1));break}}else n.push(s)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return s}function Es(e,t,n,s){t.type===Jn.MERGE&&null!==t.source.queryId&&((0,i.assert)(mi(e.viewCache_),"We should always have a full cache before handling merges"),(0,i.assert)(fi(e.viewCache_),"Missing event cache, even though we have a server cache"));const r=e.viewCache_,o=as(e.processor_,r,t,n,s);return os(e.processor_,o.viewCache),(0,i.assert)(o.viewCache.serverCache.isFullyInitialized()||!r.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=o.viewCache,xs(e,o.changes,o.viewCache.eventCache.getNode(),null)}function Ss(e,t){const n=e.viewCache_.eventCache,i=[];if(!n.getNode().isLeafNode()){n.getNode().forEachChild(rn,(e,t)=>{i.push(Tn(e,t))})}return n.isFullyInitialized()&&i.push(wn(n.getNode())),xs(e,i,n.getNode(),t)}function xs(e,t,n,i){const s=i?[i]:e.eventRegistrations_;return li(e.eventGenerator_,t,n,s)}let Ps,Ns;class Rs{constructor(){this.views=new Map}}function Ds(e){(0,i.assert)(!Ps,"__referenceConstructor has already been defined"),Ps=e}function As(){return(0,i.assert)(Ps,"Reference.ts has not been loaded"),Ps}function Ms(e){return 0===e.views.size}function qs(e,t,n,s){const r=t.source.queryId;if(null!==r){const o=e.views.get(r);return(0,i.assert)(null!=o,"SyncTree gave us an op for an invalid query."),Es(o,t,n,s)}{let i=[];for(const r of e.views.values())i=i.concat(Es(r,t,n,s));return i}}function Fs(e,t,n,i,s){const r=t._queryIdentifier,o=e.views.get(r);if(!o){let e=Qi(n,s?i:null),r=!1;e?r=!0:i instanceof _n?(e=Ki(n,i),r=!1):(e=_n.EMPTY_NODE,r=!1);const o=di(new oi(e,r,!1),new oi(i,s,!1));return new vs(t,o)}return o}function Ls(e,t,n,i,s,r){const o=Fs(e,t,i,s,r);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),bs(o,n),Ss(o,n)}function Os(e,t,n,i){const s=t._queryIdentifier,r=[];let o=[];const a=Hs(e);if("default"===s)for(const[l,h]of e.views.entries())o=o.concat(ks(h,n,i)),Is(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||r.push(h.query));else{const t=e.views.get(s);t&&(o=o.concat(ks(t,n,i)),Is(t)&&(e.views.delete(s),t.query._queryParams.loadsAllData()||r.push(t.query)))}return a&&!Hs(e)&&r.push(new(As())(t._repo,t._path)),{removed:r,events:o}}function Ws(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Us(e,t){let n=null;for(const i of e.views.values())n=n||Ts(i,t);return n}function Bs(e,t){if(t._queryParams.loadsAllData())return Vs(e);{const n=t._queryIdentifier;return e.views.get(n)}}function js(e,t){return null!=Bs(e,t)}function Hs(e){return null!=Vs(e)}function Vs(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}function zs(e){(0,i.assert)(!Ns,"__referenceConstructor has already been defined"),Ns=e}function Ys(){return(0,i.assert)(Ns,"Reference.ts has not been loaded"),Ns}let Qs=1;class Ks{constructor(e){this.listenProvider_=e,this.syncPointTree_=new vi(null),this.pendingWriteTree_=Yi(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Gs(e,t,n,i,s){return Di(e.pendingWriteTree_,t,n,i,s),s?lr(e,new si(Zn(),t,n)):[]}function $s(e,t,n,i){Ai(e.pendingWriteTree_,t,n,i);const s=vi.fromObject(n);return lr(e,new ri(Zn(),t,s))}function Xs(e,t,n=!1){const i=Mi(e.pendingWriteTree_,t);if(qi(e.pendingWriteTree_,t)){let t=new vi(null);return null!=i.snap?t=t.set(lt(),!0):F(i.children,e=>{t=t.set(new at(e),!0)}),lr(e,new ni(i.path,t,n))}return[]}function Js(e,t,n){return lr(e,new si(ei(),t,n))}function Zs(e,t,n){const i=vi.fromObject(n);return lr(e,new ri(ei(),t,i))}function er(e,t){return lr(e,new ii(ei(),t))}function tr(e,t,n){const i=pr(e,n);if(i){const n=fr(i),s=n.path,r=n.queryId,o=yt(s,t);return mr(e,s,new ii(ti(r),o))}return[]}function nr(e,t,n,i,s=!1){const r=t._path,o=e.syncPointTree_.get(r);let a=[];if(o&&("default"===t._queryIdentifier||js(o,t))){const l=Os(o,t,n,i);Ms(o)&&(e.syncPointTree_=e.syncPointTree_.remove(r));const h=l.removed;if(a=l.events,!s){const n=-1!==h.findIndex(e=>e._queryParams.loadsAllData()),s=e.syncPointTree_.findOnPath(r,(e,t)=>Hs(t));if(n&&!s){const t=e.syncPointTree_.subtree(r);if(!t.isEmpty()){const n=gr(t);for(let t=0;t<n.length;++t){const i=n[t],s=i.query,r=ur(e,i);e.listenProvider_.startListening(yr(s),dr(e,s),r.hashFn,r.onComplete)}}}if(!s&&h.length>0&&!i)if(n){const n=null;e.listenProvider_.stopListening(yr(t),n)}else h.forEach(t=>{const n=e.queryToTagMap.get(_r(t));e.listenProvider_.stopListening(yr(t),n)})}vr(e,h)}return a}function ir(e,t,n,i){const s=pr(e,i);if(null!=s){const i=fr(s),r=i.path,o=i.queryId,a=yt(r,t);return mr(e,r,new si(ti(o),a,n))}return[]}function sr(e,t,n,i){const s=pr(e,i);if(s){const i=fr(s),r=i.path,o=i.queryId,a=yt(r,t),l=vi.fromObject(n);return mr(e,r,new ri(ti(o),a,l))}return[]}function rr(e,t,n,s=!1){const r=t._path;let o=null,a=!1;e.syncPointTree_.foreachOnPath(r,(e,t)=>{const n=yt(e,r);o=o||Us(t,n),a=a||Hs(t)});let l,h=e.syncPointTree_.get(r);if(h?(a=a||Hs(h),o=o||Us(h,lt())):(h=new Rs,e.syncPointTree_=e.syncPointTree_.set(r,h)),null!=o)l=!0;else{l=!1,o=_n.EMPTY_NODE,e.syncPointTree_.subtree(r).foreachChild((e,t)=>{const n=Us(t,lt());n&&(o=o.updateImmediateChild(e,n))})}const c=js(h,t);if(!c&&!t._queryParams.loadsAllData()){const n=_r(t);(0,i.assert)(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const s=Cr();e.queryToTagMap.set(n,s),e.tagToQueryMap.set(s,n)}let u=Ls(h,t,n,Ri(e.pendingWriteTree_,r),o,l);if(!c&&!a&&!s){const n=Bs(h,t);u=u.concat(wr(e,t,n))}return u}function or(e,t,n){const i=e.pendingWriteTree_,s=e.syncPointTree_.findOnPath(t,(e,n)=>{const i=Us(n,yt(e,t));if(i)return i});return Ui(i,t,s,n,!0)}function ar(e,t){const n=t._path;let i=null;e.syncPointTree_.foreachOnPath(n,(e,t)=>{const s=yt(e,n);i=i||Us(t,s)});let s=e.syncPointTree_.get(n);s?i=i||Us(s,lt()):(s=new Rs,e.syncPointTree_=e.syncPointTree_.set(n,s));const r=null!=i,o=r?new oi(i,!0,!1):null;return ws(Fs(s,t,Ri(e.pendingWriteTree_,t._path),r?o.getNode():_n.EMPTY_NODE,r))}function lr(e,t){return hr(t,e.syncPointTree_,null,Ri(e.pendingWriteTree_,lt()))}function hr(e,t,n,i){if(gt(e.path))return cr(e,t,n,i);{const s=t.get(lt());null==n&&null!=s&&(n=Us(s,lt()));let r=[];const o=ht(e.path),a=e.operationForChild(o),l=t.children.get(o);if(l&&a){const e=n?n.getImmediateChild(o):null,t=Zi(i,o);r=r.concat(hr(a,l,e,t))}return s&&(r=r.concat(qs(s,e,i,n))),r}}function cr(e,t,n,i){const s=t.get(lt());null==n&&null!=s&&(n=Us(s,lt()));let r=[];return t.children.inorderTraversal((t,s)=>{const o=n?n.getImmediateChild(t):null,a=Zi(i,t),l=e.operationForChild(t);l&&(r=r.concat(cr(l,s,o,a)))}),s&&(r=r.concat(qs(s,e,i,n))),r}function ur(e,t){const n=t.query,i=dr(e,n);return{hashFn:()=>{return(Cs(t)||_n.EMPTY_NODE).hash()},onComplete:t=>{if("ok"===t)return i?tr(e,n._path,i):er(e,n._path);{const i=U(t,n);return nr(e,n,null,i)}}}}function dr(e,t){const n=_r(t);return e.queryToTagMap.get(n)}function _r(e){return e._path.toString()+"$"+e._queryIdentifier}function pr(e,t){return e.tagToQueryMap.get(t)}function fr(e){const t=e.indexOf("$");return(0,i.assert)(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new at(e.substr(0,t))}}function mr(e,t,n){const s=e.syncPointTree_.get(t);return(0,i.assert)(s,"Missing sync point for query tag that we're tracking"),qs(s,n,Ri(e.pendingWriteTree_,t),null)}function gr(e){return e.fold((e,t,n)=>{if(t&&Hs(t)){return[Vs(t)]}{let e=[];return t&&(e=Ws(t)),F(n,(t,n)=>{e=e.concat(n)}),e}})}function yr(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(Ys())(e._repo,e._path):e}function vr(e,t){for(let n=0;n<t.length;++n){const i=t[n];if(!i._queryParams.loadsAllData()){const t=_r(i),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}function Cr(){return Qs++}function wr(e,t,n){const s=t._path,r=dr(e,t),o=ur(e,n),a=e.listenProvider_.startListening(yr(t),r,o.hashFn,o.onComplete),l=e.syncPointTree_.subtree(s);if(r)(0,i.assert)(!Hs(l.value),"If we're adding a query, it shouldn't be shadowed");else{const t=l.fold((e,t,n)=>{if(!gt(e)&&t&&Hs(t))return[Vs(t).query];{let e=[];return t&&(e=e.concat(Ws(t).map(e=>e.query))),F(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){const i=t[n];e.listenProvider_.stopListening(yr(i),dr(e,i))}}return a}class Tr{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new Tr(t)}node(){return this.node_}}class Ir{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=mt(this.path_,e);return new Ir(this.syncTree_,t)}node(){return or(this.syncTree_,this.path_)}}const br=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},kr=function(e,t,n){return e&&"object"==typeof e?((0,i.assert)(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Er(e[".sv"],t,n):"object"==typeof e[".sv"]?Sr(e[".sv"],t):void(0,i.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Er=function(e,t,n){switch(e){case"timestamp":return n.timestamp;default:(0,i.assert)(!1,"Unexpected server value: "+e)}},Sr=function(e,t,n){e.hasOwnProperty("increment")||(0,i.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const s=e.increment;"number"!=typeof s&&(0,i.assert)(!1,"Unexpected increment value: "+s);const r=t.node();if((0,i.assert)(null!=r,"Expected ChildrenNode.EMPTY_NODE for nulls"),!r.isLeafNode())return s;const o=r.getValue();return"number"!=typeof o?s:o+s},xr=function(e,t,n,i){return Nr(t,new Ir(n,e),i)},Pr=function(e,t,n){return Nr(e,new Tr(t),n)};function Nr(e,t,n){const i=e.getPriority().val(),s=kr(i,t.getImmediateChild(".priority"),n);let r;if(e.isLeafNode()){const i=e,r=kr(i.getValue(),t,n);return r!==i.getValue()||s!==i.getPriority().val()?new en(r,gn(s)):e}{const i=e;return r=i,s!==i.getPriority().val()&&(r=r.updatePriority(new en(s))),i.forEachChild(rn,(e,i)=>{const s=Nr(i,t.getImmediateChild(e),n);s!==i&&(r=r.updateImmediateChild(e,s))}),r}}class Rr{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function Dr(e,t){let n=t instanceof at?t:new at(t),s=e,r=ht(n);for(;null!==r;){const e=(0,i.safeGet)(s.node.children,r)||{children:{},childCount:0};s=new Rr(r,s,e),r=ht(n=ut(n))}return s}function Ar(e){return e.node.value}function Mr(e,t){e.node.value=t,Br(e)}function qr(e){return e.node.childCount>0}function Fr(e){return void 0===Ar(e)&&!qr(e)}function Lr(e,t){F(e.node.children,(n,i)=>{t(new Rr(n,e,i))})}function Or(e,t,n,i){n&&!i&&t(e),Lr(e,e=>{Or(e,t,!0,i)}),n&&i&&t(e)}function Wr(e,t,n){let i=n?e:e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}return!1}function Ur(e){return new at(null===e.parent?e.name:Ur(e.parent)+"/"+e.name)}function Br(e){null!==e.parent&&jr(e.parent,e.name,e)}function jr(e,t,n){const s=Fr(n),r=(0,i.contains)(e.node.children,t);s&&r?(delete e.node.children[t],e.node.childCount--,Br(e)):s||r||(e.node.children[t]=n.node,e.node.childCount++,Br(e))}const Hr=/[\[\].#$\/\u0000-\u001F\u007F]/,Vr=/[\[\].#$\u0000-\u001F\u007F]/,zr=10485760,Yr=function(e){return"string"==typeof e&&0!==e.length&&!Hr.test(e)},Qr=function(e){return"string"==typeof e&&0!==e.length&&!Vr.test(e)},Kr=function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),Qr(e)},Gr=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!S(e)||e&&"object"==typeof e&&(0,i.contains)(e,".sv")},$r=function(e,t,n,s){s&&void 0===t||Xr((0,i.errorPrefix)(e,"value"),t,n)},Xr=function(e,t,n){const s=n instanceof at?new Tt(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+Et(s));if("function"==typeof t)throw new Error(e+"contains a function "+Et(s)+" with contents = "+t.toString());if(S(t))throw new Error(e+"contains "+t.toString()+" "+Et(s));if("string"==typeof t&&t.length>10485760/3&&(0,i.stringLength)(t)>10485760)throw new Error(e+"contains a string greater than 10485760 utf8 bytes "+Et(s)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,i=!1;if(F(t,(t,r)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(i=!0,!Yr(t)))throw new Error(e+" contains an invalid key ("+t+") "+Et(s)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');It(s,t),Xr(e,r,s),bt(s)}),n&&i)throw new Error(e+' contains ".value" child '+Et(s)+" in addition to actual children.")}},Jr=function(e,t){let n,i;for(n=0;n<t.length;n++){const s=pt(i=t[n]);for(let t=0;t<s.length;t++)if(".priority"===s[t]&&t===s.length-1);else if(!Yr(s[t]))throw new Error(e+"contains an invalid key ("+s[t]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(vt);let s=null;for(n=0;n<t.length;n++){if(i=t[n],null!==s&&wt(s,i))throw new Error(e+"contains a path "+s.toString()+" that is ancestor of another path "+i.toString());s=i}},Zr=function(e,t,n,s){if(s&&void 0===t)return;const r=(0,i.errorPrefix)(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(r+" must be an object containing the children to replace.");const o=[];F(t,(e,t)=>{const i=new at(e);if(Xr(r,t,mt(n,i)),".priority"===dt(i)&&!Gr(t))throw new Error(r+"contains an invalid value for '"+i.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(i)}),Jr(r,o)},eo=function(e,t,n){if(!n||void 0!==t){if(S(t))throw new Error((0,i.errorPrefix)(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Gr(t))throw new Error((0,i.errorPrefix)(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},to=function(e,t,n,s){if(!(s&&void 0===n||Yr(n)))throw new Error((0,i.errorPrefix)(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},no=function(e,t,n,s){if(!(s&&void 0===n||Qr(n)))throw new Error((0,i.errorPrefix)(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')};exports._validatePathString=no;const io=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),no(e,t,n,i)},so=function(e,t){if(".info"===ht(t))throw new Error(e+" failed = Can't modify data under /.info/")};exports._validateWritablePath=so;const ro=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Yr(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Kr(n))throw new Error((0,i.errorPrefix)(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class oo{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function ao(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i],r=s.getPath();null===n||Ct(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function lo(e,t,n){ao(e,n),co(e,e=>Ct(e,t))}function ho(e,t,n){ao(e,n),co(e,e=>wt(e,t)||wt(t,e))}function co(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){const s=e.eventLists_[i];if(s){t(s.path)?(uo(e.eventLists_[i]),e.eventLists_[i]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function uo(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const i=n.getEventRunner();y&&w("event: "+n.toString()),z(i)}}}const _o="repo_interrupt",po=25;class fo{constructor(e,t,n,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new oo,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=jn(),this.transactionQueueTree_=new Rr,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function mo(e,t,n){if(e.stats_=pe(e.repoInfo_),e.forceRestClient_||Y())e.server_=new Un(e.repoInfo_,(t,n,i,s)=>{vo(e,t,n,i,s)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>Co(e,!0),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{(0,i.stringify)(n)}catch(s){throw new Error("Invalid authOverride provided: "+s)}}e.persistentConnection_=new qt(e.repoInfo_,t,(t,n,i,s)=>{vo(e,t,n,i,s)},t=>{Co(e,t)},t=>{wo(e,t)},e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener(t=>{e.server_.refreshAuthToken(t)}),e.appCheckProvider_.addTokenChangeListener(t=>{e.server_.refreshAppCheckToken(t.token)}),e.statsReporter_=fe(e.repoInfo_,()=>new Xn(e.stats_,e.server_)),e.infoData_=new Bn,e.infoSyncTree_=new Ks({startListening:(t,n,i,s)=>{let r=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(r=Js(e.infoSyncTree_,t._path,o),setTimeout(()=>{s("ok")},0)),r},stopListening:()=>{}}),To(e,"connected",!1),e.serverSyncTree_=new Ks({startListening:(t,n,i,s)=>(e.server_.listen(t,i,n,(n,i)=>{const r=s(n,i);ho(e.eventQueue_,t._path,r)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function go(e){const t=e.infoData_.getNode(new at(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function yo(e){return br({timestamp:go(e)})}function vo(e,t,n,s,r){e.dataUpdateCount++;const o=new at(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let a=[];if(r)if(s){const t=(0,i.map)(n,e=>gn(e));a=sr(e.serverSyncTree_,o,t,r)}else{const t=gn(n);a=ir(e.serverSyncTree_,o,t,r)}else if(s){const t=(0,i.map)(n,e=>gn(e));a=Zs(e.serverSyncTree_,o,t)}else{const t=gn(n);a=Js(e.serverSyncTree_,o,t)}let l=o;a.length>0&&(l=jo(e,o)),ho(e.eventQueue_,l,a)}function Co(e,t){To(e,"connected",t),!1===t&&So(e)}function wo(e,t){F(t,(t,n)=>{To(e,t,n)})}function To(e,t,n){const i=new at("/.info/"+t),s=gn(n);e.infoData_.updateSnapshot(i,s);const r=Js(e.infoSyncTree_,i,s);ho(e.eventQueue_,i,r)}function Io(e){return e.nextWriteId_++}function bo(e,t,n){const s=ar(e.serverSyncTree_,t);return null!=s?Promise.resolve(s):e.server_.get(t).then(i=>{const s=gn(i).withIndex(t._queryParams.getIndex());let r;if(rr(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())r=Js(e.serverSyncTree_,t._path,s);else{const n=dr(e.serverSyncTree_,t);r=ir(e.serverSyncTree_,t._path,s,n)}return ho(e.eventQueue_,t._path,r),nr(e.serverSyncTree_,t,n,null,!0),s},n=>(Fo(e,"get for query "+(0,i.stringify)(t)+" failed: "+n),Promise.reject(new Error(n))))}function ko(e,t,n,i,s){Fo(e,"set",{path:t.toString(),value:n,priority:i});const r=yo(e),o=gn(n,i),a=or(e.serverSyncTree_,t),l=Pr(o,a,r),h=Io(e),c=Gs(e.serverSyncTree_,t,l,h,!0);ao(e.eventQueue_,c),e.server_.put(t.toString(),o.val(!0),(n,i)=>{const r="ok"===n;r||k("set at "+t+" failed: "+n);const o=Xs(e.serverSyncTree_,h,!r);ho(e.eventQueue_,t,o),Lo(e,s,n,i)});const u=Ko(e,t);jo(e,u),ho(e.eventQueue_,u,[])}function Eo(e,t,n,i){Fo(e,"update",{path:t.toString(),value:n});let s=!0;const r=yo(e),o={};if(F(n,(n,i)=>{s=!1,o[n]=xr(mt(t,n),gn(i),e.serverSyncTree_,r)}),s)w("update() called with empty data. Don't do anything."),Lo(e,i,"ok",void 0);else{const s=Io(e),r=$s(e.serverSyncTree_,t,o,s);ao(e.eventQueue_,r),e.server_.merge(t.toString(),n,(n,r)=>{const o="ok"===n;o||k("update at "+t+" failed: "+n);const a=Xs(e.serverSyncTree_,s,!o),l=a.length>0?jo(e,t):t;ho(e.eventQueue_,l,a),Lo(e,i,n,r)}),F(n,n=>{const i=Ko(e,mt(t,n));jo(e,i)}),ho(e.eventQueue_,t,[])}}function So(e){Fo(e,"onDisconnectEvents");const t=yo(e),n=jn();zn(e.onDisconnect_,lt(),(i,s)=>{const r=xr(i,s,e.serverSyncTree_,t);Hn(n,i,r)});let i=[];zn(n,lt(),(t,n)=>{i=i.concat(Js(e.serverSyncTree_,t,n));const s=Ko(e,t);jo(e,s)}),e.onDisconnect_=jn(),ho(e.eventQueue_,lt(),i)}function xo(e,t,n){e.server_.onDisconnectCancel(t.toString(),(i,s)=>{"ok"===i&&Vn(e.onDisconnect_,t),Lo(e,n,i,s)})}function Po(e,t,n,i){const s=gn(n);e.server_.onDisconnectPut(t.toString(),s.val(!0),(n,r)=>{"ok"===n&&Hn(e.onDisconnect_,t,s),Lo(e,i,n,r)})}function No(e,t,n,i,s){const r=gn(n,i);e.server_.onDisconnectPut(t.toString(),r.val(!0),(n,i)=>{"ok"===n&&Hn(e.onDisconnect_,t,r),Lo(e,s,n,i)})}function Ro(e,t,n,s){if((0,i.isEmpty)(n))return w("onDisconnect().update() called with empty data. Don't do anything."),void Lo(e,s,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,(i,r)=>{"ok"===i&&F(n,(n,i)=>{const s=gn(i);Hn(e.onDisconnect_,mt(t,n),s)}),Lo(e,s,i,r)})}function Do(e,t,n){let i;i=".info"===ht(t._path)?rr(e.infoSyncTree_,t,n):rr(e.serverSyncTree_,t,n),lo(e.eventQueue_,t._path,i)}function Ao(e,t,n){let i;i=".info"===ht(t._path)?nr(e.infoSyncTree_,t,n):nr(e.serverSyncTree_,t,n),lo(e.eventQueue_,t._path,i)}function Mo(e){e.persistentConnection_&&e.persistentConnection_.interrupt(_o)}function qo(e){e.persistentConnection_&&e.persistentConnection_.resume(_o)}function Fo(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),w(n,...t)}function Lo(e,t,n,i){t&&z(()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let s=e;i&&(s+=": "+i);const r=new Error(s);r.code=e,t(r)}})}function Oo(e,t,n,s,r,o){Fo(e,"transaction on "+t);const a={path:t,update:n,onComplete:s,status:null,order:f(),applyLocally:o,retryCount:0,unwatcher:r,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},l=Wo(e,t,void 0);a.currentInputSnapshot=l;const h=a.update(l.val());if(void 0===h)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Xr("transaction failed: Data returned ",h,a.path),a.status=0;const n=Dr(e.transactionQueueTree_,t),s=Ar(n)||[];let r;if(s.push(a),Mr(n,s),"object"==typeof h&&null!==h&&(0,i.contains)(h,".priority"))r=(0,i.safeGet)(h,".priority"),(0,i.assert)(Gr(r),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{r=(or(e.serverSyncTree_,t)||_n.EMPTY_NODE).getPriority().val()}const o=yo(e),c=gn(h,r),u=Pr(c,l,o);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=u,a.currentWriteId=Io(e);const d=Gs(e.serverSyncTree_,t,u,a.currentWriteId,a.applyLocally);ho(e.eventQueue_,t,d),Uo(e,e.transactionQueueTree_)}}function Wo(e,t,n){return or(e.serverSyncTree_,t,n)||_n.EMPTY_NODE}function Uo(e,t=e.transactionQueueTree_){if(t||Qo(e,t),Ar(t)){const n=zo(e,t);(0,i.assert)(n.length>0,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&Bo(e,Ur(t),n)}else qr(t)&&Lr(t,t=>{Uo(e,t)})}function Bo(e,t,n){const s=n.map(e=>e.currentWriteId),r=Wo(e,t,s);let o=r;const a=r.hash();for(let c=0;c<n.length;c++){const e=n[c];(0,i.assert)(0===e.status,"tryToSendTransactionQueue_: items in queue should all be run."),e.status=1,e.retryCount++;const s=yt(t,e.path);o=o.updateChild(s,e.currentOutputSnapshotRaw)}const l=o.val(!0),h=t;e.server_.put(h.toString(),l,i=>{Fo(e,"transaction put response",{path:h.toString(),status:i});let s=[];if("ok"===i){const i=[];for(let t=0;t<n.length;t++)n[t].status=2,s=s.concat(Xs(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&i.push(()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved)),n[t].unwatcher();Qo(e,Dr(e.transactionQueueTree_,t)),Uo(e,e.transactionQueueTree_),ho(e.eventQueue_,t,s);for(let e=0;e<i.length;e++)z(i[e])}else{if("datastale"===i)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{k("transaction at "+h.toString()+" failed: "+i);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=i}jo(e,t)}},a)}function jo(e,t){const n=Vo(e,t),i=Ur(n);return Ho(e,zo(e,n),i),i}function Ho(e,t,n){if(0===t.length)return;const s=[];let r=[];const o=t.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let l=0;l<t.length;l++){const h=t[l],c=yt(n,h.path);let u,d=!1;if((0,i.assert)(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)d=!0,u=h.abortReason,r=r.concat(Xs(e.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=po)d=!0,u="maxretry",r=r.concat(Xs(e.serverSyncTree_,h.currentWriteId,!0));else{const n=Wo(e,h.path,o);h.currentInputSnapshot=n;const s=t[l].update(n.val());if(void 0!==s){Xr("transaction failed: Data returned ",s,h.path);let t=gn(s);"object"==typeof s&&null!=s&&(0,i.contains)(s,".priority")||(t=t.updatePriority(n.getPriority()));const a=h.currentWriteId,l=yo(e),c=Pr(t,n,l);h.currentOutputSnapshotRaw=t,h.currentOutputSnapshotResolved=c,h.currentWriteId=Io(e),o.splice(o.indexOf(a),1),r=(r=r.concat(Gs(e.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(Xs(e.serverSyncTree_,a,!0))}else d=!0,u="nodata",r=r.concat(Xs(e.serverSyncTree_,h.currentWriteId,!0))}ho(e.eventQueue_,n,r),r=[],d&&(t[l].status=2,a=t[l].unwatcher,setTimeout(a,Math.floor(0)),t[l].onComplete&&("nodata"===u?s.push(()=>t[l].onComplete(null,!1,t[l].currentInputSnapshot)):s.push(()=>t[l].onComplete(new Error(u),!1,null))))}var a;Qo(e,e.transactionQueueTree_);for(let i=0;i<s.length;i++)z(s[i]);Uo(e,e.transactionQueueTree_)}function Vo(e,t){let n,i=e.transactionQueueTree_;for(n=ht(t);null!==n&&void 0===Ar(i);)i=Dr(i,n),n=ht(t=ut(t));return i}function zo(e,t){const n=[];return Yo(e,t,n),n.sort((e,t)=>e.order-t.order),n}function Yo(e,t,n){const i=Ar(t);if(i)for(let s=0;s<i.length;s++)n.push(i[s]);Lr(t,t=>{Yo(e,t,n)})}function Qo(e,t){const n=Ar(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,Mr(t,n.length>0?n:void 0)}Lr(t,t=>{Qo(e,t)})}function Ko(e,t){const n=Ur(Vo(e,t)),i=Dr(e.transactionQueueTree_,t);return Wr(i,t=>{Go(e,t)}),Go(e,i),Or(i,t=>{Go(e,t)}),n}function Go(e,t){const n=Ar(t);if(n){const s=[];let r=[],o=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?((0,i.assert)(o===t-1,"All SENT items should be at beginning of queue."),o=t,n[t].status=3,n[t].abortReason="set"):((0,i.assert)(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),r=r.concat(Xs(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&s.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===o?Mr(t,void 0):n.length=o+1,ho(e.eventQueue_,Ur(t),r);for(let e=0;e<s.length;e++)z(s[e])}}function $o(e){let t="";const n=e.split("/");for(let s=0;s<n.length;s++)if(n[s].length>0){let e=n[s];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(i){}t+="/"+e}return t}function Xo(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):k(`Invalid query segment '${n}' in query '${e}'`)}return t}const Jo=function(e,t){const n=Zo(e),i=n.namespace;"firebase.com"===n.domain&&b(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||b("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&k("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new le(n.host,n.secure,i,s,t,"",i!==n.subdomain),path:new at(n.pathString)}},Zo=function(e){let t="",n="",i="",s="",r="",o=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(c,u)),c<u&&(s=$o(e.substring(c,u)));const d=Xo(e.substring(Math.min(e.length,u)));(h=t.indexOf(":"))>=0?(o="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;const _=t.slice(0,h);if("localhost"===_.toLowerCase())n="localhost";else if(_.split(".").length<=2)n=_;else{const e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),r=i}"ns"in d&&(r=d.ns)}return{host:t,port:l,domain:n,subdomain:i,secure:o,scheme:a,pathString:s,namespace:r}},ea="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ta=function(){let e=0;const t=[];return function(n){const s=n===e;let r;e=n;const o=new Array(8);for(r=7;r>=0;r--)o[r]=ea.charAt(n%64),n=Math.floor(n/64);(0,i.assert)(0===n,"Cannot push at time == 0");let a=o.join("");if(s){for(r=11;r>=0&&63===t[r];r--)t[r]=0;t[r]++}else for(r=0;r<12;r++)t[r]=Math.floor(64*Math.random());for(r=0;r<12;r++)a+=ea.charAt(t[r]);return(0,i.assert)(20===a.length,"nextPushId: Length should be 20."),a}}();class na{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+(0,i.stringify)(this.snapshot.exportVal())}}class ia{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class sa{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return(0,i.assert)(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class ra{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new i.Deferred;return xo(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){so("OnDisconnect.remove",this._path);const e=new i.Deferred;return Po(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){so("OnDisconnect.set",this._path),$r("OnDisconnect.set",e,this._path,!1);const t=new i.Deferred;return Po(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){so("OnDisconnect.setWithPriority",this._path),$r("OnDisconnect.setWithPriority",e,this._path,!1),eo("OnDisconnect.setWithPriority",t,!1);const n=new i.Deferred;return No(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){so("OnDisconnect.update",this._path),Zr("OnDisconnect.update",e,this._path,!1);const t=new i.Deferred;return Ro(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}exports.OnDisconnect=ra;class oa{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return gt(this._path)?null:dt(this._path)}get ref(){return new ca(this._repo,this._path)}get _queryIdentifier(){const e=Wn(this._queryParams),t=M(e);return"{}"===t?"default":t}get _queryObject(){return Wn(this._queryParams)}isEqual(e){if(!((e=(0,i.getModularInstance)(e))instanceof oa))return!1;const t=this._repo===e._repo,n=Ct(this._path,e._path),s=this._queryIdentifier===e._queryIdentifier;return t&&n&&s}toJSON(){return this.toString()}toString(){return this._repo.toString()+_t(this._path)}}function aa(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function la(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===Ut){const i="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",s="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==P)throw new Error(i);if("string"!=typeof t)throw new Error(s)}if(e.hasEnd()){if(e.getIndexEndName()!==N)throw new Error(i);if("string"!=typeof n)throw new Error(s)}}else if(e.getIndex()===rn){if(null!=t&&!Gr(t)||null!=n&&!Gr(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if((0,i.assert)(e.getIndex()instanceof yn||e.getIndex()===Cn,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function ha(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}exports._QueryImpl=oa;class ca extends oa{constructor(e,t){super(e,t,new Pn,!1)}get parent(){const e=ft(this._path);return null===e?null:new ca(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}exports._ReferenceImpl=ca;class ua{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new at(e),n=pa(this.ref,e);return new ua(this._node.getChild(t),n,rn)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,(t,n)=>e(new ua(n,pa(this.ref,t),rn)))}hasChild(e){const t=new at(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function da(e,t){return(e=(0,i.getModularInstance)(e))._checkNotDeleted("ref"),void 0!==t?pa(e._root,t):e._root}function _a(e,t){(e=(0,i.getModularInstance)(e))._checkNotDeleted("refFromURL");const n=Jo(t,e._repo.repoInfo_.nodeAdmin);ro("refFromURL",n);const s=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||s.host===e._repo.repoInfo_.host||b("refFromURL: Host name does not match the current database: (found "+s.host+" but expected "+e._repo.repoInfo_.host+")"),da(e,n.path.toString())}function pa(e,t){return null===ht((e=(0,i.getModularInstance)(e))._path)?io("child","path",t,!1):no("child","path",t,!1),new ca(e._repo,mt(e._path,t))}function fa(e){return e=(0,i.getModularInstance)(e),new ra(e._repo,e._path)}function ma(e,t){e=(0,i.getModularInstance)(e),so("push",e._path),$r("push",t,e._path,!0);const n=go(e._repo),s=ta(n),r=pa(e,s),o=pa(e,s);let a;return a=null!=t?ya(o,t).then(()=>o):Promise.resolve(o),r.then=a.then.bind(a),r.catch=a.then.bind(a,void 0),r}function ga(e){return so("remove",e._path),ya(e,null)}function ya(e,t){e=(0,i.getModularInstance)(e),so("set",e._path),$r("set",t,e._path,!1);const n=new i.Deferred;return ko(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function va(e,t){e=(0,i.getModularInstance)(e),so("setPriority",e._path),eo("setPriority",t,!1);const n=new i.Deferred;return ko(e._repo,mt(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}function Ca(e,t,n){if(so("setWithPriority",e._path),$r("setWithPriority",t,e._path,!1),eo("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const s=new i.Deferred;return ko(e._repo,e._path,t,n,s.wrapCallback(()=>{})),s.promise}function wa(e,t){Zr("update",t,e._path,!1);const n=new i.Deferred;return Eo(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function Ta(e){e=(0,i.getModularInstance)(e);const t=new sa(()=>{}),n=new Ia(t);return bo(e._repo,e,n).then(t=>new ua(t,new ca(e._repo,e._path),e._queryParams.getIndex()))}exports.DataSnapshot=ua;class Ia{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new na("value",this,new ua(e.snapshotNode,new ca(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ia(this,e,t):null}matches(e){return e instanceof Ia&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ba{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ia(this,e,t):null}createEvent(e,t){(0,i.assert)(null!=e.childName,"Child events should have a childName.");const n=pa(new ca(t._repo,t._path),e.childName),s=t._queryParams.getIndex();return new na(e.type,this,new ua(e.snapshotNode,n,s),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof ba&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function ka(e,t,n,i,s){let r;if("object"==typeof i&&(r=void 0,s=i),"function"==typeof i&&(r=i),s&&s.onlyOnce){const t=n,i=(n,i)=>{Ao(e._repo,e,a),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}const o=new sa(n,r||void 0),a="value"===t?new Ia(o):new ba(t,o);return Do(e._repo,e,a),()=>Ao(e._repo,e,a)}function Ea(e,t,n,i){return ka(e,"value",t,n,i)}function Sa(e,t,n,i){return ka(e,"child_added",t,n,i)}function xa(e,t,n,i){return ka(e,"child_changed",t,n,i)}function Pa(e,t,n,i){return ka(e,"child_moved",t,n,i)}function Na(e,t,n,i){return ka(e,"child_removed",t,n,i)}function Ra(e,t,n){let i=null;const s=n?new sa(n):null;"value"===t?i=new Ia(s):t&&(i=new ba(t,s)),Ao(e._repo,e,i)}class Da{}exports.QueryConstraint=Da;class Aa extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("endAt",this._value,e._path,!0);const t=qn(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Ma(e,t){return to("endAt","key",t,!0),new Aa(e,t)}class qa extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("endBefore",this._value,e._path,!1);const t=Fn(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Fa(e,t){return to("endBefore","key",t,!0),new qa(e,t)}class La extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("startAt",this._value,e._path,!0);const t=An(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Oa(e=null,t){return to("startAt","key",t,!0),new La(e,t)}class Wa extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("startAfter",this._value,e._path,!1);const t=Mn(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Ua(e,t){return to("startAfter","key",t,!0),new Wa(e,t)}class Ba extends Da{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new oa(e._repo,e._path,Rn(e._queryParams,this._limit),e._orderByCalled)}}function ja(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Ba(e)}class Ha extends Da{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new oa(e._repo,e._path,Dn(e._queryParams,this._limit),e._orderByCalled)}}function Va(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Ha(e)}class za extends Da{constructor(e){super(),this._path=e}_apply(e){aa(e,"orderByChild");const t=new at(this._path);if(gt(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new yn(t),i=Ln(e._queryParams,n);return la(i),new oa(e._repo,e._path,i,!0)}}function Ya(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return no("orderByChild","path",e,!1),new za(e)}class Qa extends Da{_apply(e){aa(e,"orderByKey");const t=Ln(e._queryParams,Ut);return la(t),new oa(e._repo,e._path,t,!0)}}function Ka(){return new Qa}class Ga extends Da{_apply(e){aa(e,"orderByPriority");const t=Ln(e._queryParams,rn);return la(t),new oa(e._repo,e._path,t,!0)}}function $a(){return new Ga}class Xa extends Da{_apply(e){aa(e,"orderByValue");const t=Ln(e._queryParams,Cn);return la(t),new oa(e._repo,e._path,t,!0)}}function Ja(){return new Xa}class Za extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if($r("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new Aa(this._value,this._key)._apply(new La(this._value,this._key)._apply(e))}}function el(e,t){return to("equalTo","key",t,!0),new Za(e,t)}function tl(e,...t){let n=(0,i.getModularInstance)(e);for(const i of t)n=i._apply(n);return n}Ds(ca),zs(ca);const nl="FIREBASE_DATABASE_EMULATOR_HOST",il={};let sl=!1;function rl(e,t,n,i){e.repoInfo_=new le(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),i&&(e.authTokenProvider_=i)}function ol(t,n,i,s,r){let o=s||t.options.databaseURL;void 0===o&&(t.options.projectId||b("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),w("Using default host for project ",t.options.projectId),o=`${t.options.projectId}-default-rtdb.firebaseio.com`);let a,l=Jo(o,r),h=l.repoInfo,c=void 0;void 0!==e&&e.env&&(c=e.env[nl]),c?(a=!0,o=`http://${c}?ns=${h.namespace}`,h=(l=Jo(o,r)).repoInfo):a=!l.repoInfo.secure;const u=r&&a?new $($.OWNER):new G(t.name,t.options,n);ro("Invalid Firebase Database URL",l),gt(l.path)||b("Database URL must point to the root of a Firebase Database (not including a child path).");const d=ll(h,t,u,new K(t.name,i));return new cl(d,t)}function al(e,t){const n=il[t];n&&n[e.key]===e||b(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Mo(e),delete n[e.key]}function ll(e,t,n,i){let s=il[t.name];s||(s={},il[t.name]=s);let r=s[e.toURLString()];return r&&b("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new fo(e,sl,n,i),s[e.toURLString()]=r,r}function hl(e){sl=e}class cl{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(mo(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ca(this._repo,lt())),this._rootInternal}_delete(){return null!==this._rootInternal&&(al(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&b("Cannot call "+e+" on a deleted database.")}}function ul(){Ue.IS_TRANSPORT_INITIALIZED&&k("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function dl(){ul(),Me.forceDisallow()}function _l(){ul(),We.forceDisallow(),Me.forceAllow()}function pl(e=(0,t.getApp)(),n){const s=(0,t._getProvider)(e,"database").getImmediate({identifier:n});if(!s._instanceStarted){const e=(0,i.getDefaultEmulatorHostnameAndPort)("database");e&&fl(s,...e)}return s}function fl(e,t,n,s={}){(e=(0,i.getModularInstance)(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&b("Cannot call useEmulator() after instance has already been initialized.");const r=e._repoInternal;let o=void 0;if(r.repoInfo_.nodeAdmin)s.mockUserToken&&b('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new $($.OWNER);else if(s.mockUserToken){const t="string"==typeof s.mockUserToken?s.mockUserToken:(0,i.createMockUserToken)(s.mockUserToken,e.app.options.projectId);o=new $(t)}rl(r,t,n,o)}function ml(e){(e=(0,i.getModularInstance)(e))._checkNotDeleted("goOffline"),Mo(e._repo)}function gl(e){(e=(0,i.getModularInstance)(e))._checkNotDeleted("goOnline"),qo(e._repo)}function yl(e,t){C(e,t)}function vl(e){l(t.SDK_VERSION),(0,t._registerComponent)(new n.Component("database",(e,{instanceIdentifier:t})=>{return ol(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),(0,t.registerVersion)(r,o,e),(0,t.registerVersion)(r,o,"esm2017")}exports.Database=cl;const Cl={".sv":"timestamp"};function wl(){return Cl}function Tl(e){return{".sv":{increment:e}}}class Il{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function bl(e,t,n){var s;if(e=(0,i.getModularInstance)(e),so("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const r=null===(s=null==n?void 0:n.applyLocally)||void 0===s||s,o=new i.Deferred,a=Ea(e,()=>{});return Oo(e._repo,e._path,t,(t,n,i)=>{let s=null;t?o.reject(t):(s=new ua(i,new ca(e._repo,e._path),rn),o.resolve(new Il(n,s)))},a,r),o.promise}exports.TransactionResult=Il,qt.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},qt.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};const kl=function(e){const t=qt.prototype.put;return qt.prototype.put=function(n,i,s,r){void 0!==r&&(r=e()),t.call(this,n,i,s,r)},function(){qt.prototype.put=t}};exports._TEST_ACCESS_hijackHash=kl;const El=function(e){hl(e)};exports._TEST_ACCESS_forceRestClient=El,vl();
|
|
481
|
+
var e=require("process");Object.defineProperty(exports,"__esModule",{value:!0}),exports._TEST_ACCESS_hijackHash=exports._TEST_ACCESS_forceRestClient=exports._ReferenceImpl=exports._QueryParams=exports._QueryImpl=exports.TransactionResult=exports.QueryConstraint=exports.OnDisconnect=exports.Database=exports.DataSnapshot=void 0,exports._repoManagerDatabaseFromApp=ol,exports._setSDKVersion=l,exports._validateWritablePath=exports._validatePathString=void 0,exports.child=pa,exports.connectDatabaseEmulator=fl,exports.enableLogging=yl,exports.endAt=Ma,exports.endBefore=Fa,exports.equalTo=el,exports.forceLongPolling=_l,exports.forceWebSockets=dl,exports.get=Ta,exports.getDatabase=pl,exports.goOffline=ml,exports.goOnline=gl,exports.increment=Tl,exports.limitToFirst=ja,exports.limitToLast=Va,exports.off=Ra,exports.onChildAdded=Sa,exports.onChildChanged=xa,exports.onChildMoved=Pa,exports.onChildRemoved=Na,exports.onDisconnect=fa,exports.onValue=Ea,exports.orderByChild=Ya,exports.orderByKey=Ka,exports.orderByPriority=$a,exports.orderByValue=Ja,exports.push=ma,exports.query=tl,exports.ref=da,exports.refFromURL=_a,exports.remove=ga,exports.runTransaction=bl,exports.serverTimestamp=wl,exports.set=ya,exports.setPriority=va,exports.setWithPriority=Ca,exports.startAfter=Ua,exports.startAt=Oa,exports.update=wa;var t=require("@firebase/app"),n=require("@firebase/component"),i=require("@firebase/util"),s=require("@firebase/logger");const r="@firebase/database",o="0.14.4";let a="";function l(e){a=e}class h{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),(0,i.stringify)(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:(0,i.jsonEval)(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class c{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return(0,i.contains)(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const u=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new h(t)}}catch(t){}return new c},d=u("localStorage"),_=u("sessionStorage"),p=new s.Logger("@firebase/database"),f=function(){let e=1;return function(){return e++}}(),m=function(e){const t=(0,i.stringToByteArray)(e),n=new i.Sha1;n.update(t);const s=n.digest();return i.base64.encodeByteArray(s)},g=function(...e){let t="";for(let n=0;n<e.length;n++){const s=e[n];Array.isArray(s)||s&&"object"==typeof s&&"number"==typeof s.length?t+=g.apply(null,s):t+="object"==typeof s?(0,i.stringify)(s):s,t+=" "}return t};let y=null,v=!0;const C=function(e,t){(0,i.assert)(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(p.logLevel=s.LogLevel.VERBOSE,y=p.log.bind(p),t&&_.set("logging_enabled",!0)):"function"==typeof e?y=e:(y=null,_.remove("logging_enabled"))},w=function(...e){if(!0===v&&(v=!1,null===y&&!0===_.get("logging_enabled")&&C(!0)),y){const t=g.apply(null,e);y(t)}},T=function(e){return function(...t){w(e,...t)}},I=function(...e){const t="FIREBASE INTERNAL ERROR: "+g(...e);p.error(t)},b=function(...e){const t=`FIREBASE FATAL ERROR: ${g(...e)}`;throw p.error(t),new Error(t)},k=function(...e){const t="FIREBASE WARNING: "+g(...e);p.warn(t)},E=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&k("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},S=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},x=function(e){if((0,i.isNodeSdk)()||"complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}},P="[MIN_NAME]",N="[MAX_NAME]",R=function(e,t){if(e===t)return 0;if(e===P||t===N)return-1;if(t===P||e===N)return 1;{const n=V(e),i=V(t);return null!==n?null!==i?n-i==0?e.length-t.length:n-i:-1:null!==i?1:e<t?-1:1}},D=function(e,t){return e===t?0:e<t?-1:1},A=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+(0,i.stringify)(t))},M=function(e){if("object"!=typeof e||null===e)return(0,i.stringify)(e);const t=[];for(const i in e)t.push(i);t.sort();let n="{";for(let s=0;s<t.length;s++)0!==s&&(n+=","),n+=(0,i.stringify)(t[s]),n+=":",n+=M(e[t[s]]);return n+="}"},q=function(e,t){const n=e.length;if(n<=t)return[e];const i=[];for(let s=0;s<n;s+=t)s+t>n?i.push(e.substring(s,n)):i.push(e.substring(s,s+t));return i};function F(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const L=function(e){(0,i.assert)(!S(e),"Invalid JSON number");let t,n,s,r,o;0===e?(n=0,s=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(n=(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,s=Math.round(e*Math.pow(2,52-r)-Math.pow(2,52))):(n=0,s=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(s%2?1:0),s=Math.floor(s/2);for(o=11;o;o-=1)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse();const l=a.join("");let h="";for(o=0;o<64;o+=8){let e=parseInt(l.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),h+=e}return h.toLowerCase()},O=function(){return!("object"!=typeof window||!window.chrome||!window.chrome.extension||/^chrome/.test(window.location.href))},W=function(){return"object"==typeof Windows&&"object"==typeof Windows.UI};function U(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const i=new Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}const B=new RegExp("^-?(0*)\\d{1,10}$"),j=-2147483648,H=2147483647,V=function(e){if(B.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},z=function(e){try{e()}catch(t){setTimeout(()=>{const e=t.stack||"";throw k("Exception was thrown by user callback.",e),t},Math.floor(0))}},Y=function(){return("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Q=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class K{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then(e=>this.appCheck=e)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){k(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class G{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&"auth/token-not-initialized"===e.code?(w("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(t=>t.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(t=>t.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',k(e)}}class ${constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}$.OWNER="owner";const X="5",J="v",Z="s",ee="r",te="f",ne=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,ie="ls",se="p",re="ac",oe="websocket",ae="long_polling";class le{constructor(e,t,n,i,s=!1,r="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=r,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=d.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&d.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function he(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams}function ce(e,t,n){let s;if((0,i.assert)("string"==typeof t,"typeof type must == string"),(0,i.assert)("object"==typeof n,"typeof params must == object"),t===oe)s=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==ae)throw new Error("Unknown connection type: "+t);s=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}he(e)&&(n.ns=e.namespace);const r=[];return F(n,(e,t)=>{r.push(e+"="+t)}),s+r.join("&")}class ue{constructor(){this.counters_={}}incrementCounter(e,t=1){(0,i.contains)(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return(0,i.deepCopy)(this.counters_)}}const de={},_e={};function pe(e){const t=e.toString();return de[t]||(de[t]=new ue),de[t]}function fe(e,t){const n=e.toString();return _e[n]||(_e[n]=t()),_e[n]}class me{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&z(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const ge="start",ye="close",ve="pLPCommand",Ce="pRTLPCB",we="id",Te="pw",Ie="ser",be="cb",ke="seg",Ee="ts",Se="d",xe="dframe",Pe=1870,Ne=30,Re=Pe-Ne,De=25e3,Ae=3e4;class Me{constructor(e,t,n,i,s,r,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.transportSessionId=r,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=T(e),this.stats_=pe(t),this.urlFn=(e=>(this.appCheckToken&&(e[re]=this.appCheckToken),ce(t,ae,e)))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new me(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Ae)),x(()=>{if(this.isClosed_)return;this.scriptTagHolder=new qe((...e)=>{const[t,n,i,s,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ge)this.id=n,this.password=i;else{if(t!==ye)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const e={};e[ge]="t",e[Ie]=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e[be]=this.scriptTagHolder.uniqueCallbackIdentifier),e[J]=X,this.transportSessionId&&(e[Z]=this.transportSessionId),this.lastSessionId&&(e[ie]=this.lastSessionId),this.applicationId&&(e[se]=this.applicationId),this.appCheckToken&&(e[re]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&ne.test(location.hostname)&&(e[ee]=te);const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Me.forceAllow_=!0}static forceDisallow(){Me.forceDisallow_=!0}static isAvailable(){return!(0,i.isNodeSdk)()&&(!!Me.forceAllow_||!Me.forceDisallow_&&"undefined"!=typeof document&&null!=document.createElement&&!O()&&!W())}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=(0,i.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=(0,i.base64Encode)(t),s=q(n,Re);for(let i=0;i<s.length;i++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,s.length,s[i]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if((0,i.isNodeSdk)())return;this.myDisconnFrame=document.createElement("iframe");const n={};n[xe]="t",n[we]=e,n[Te]=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=(0,i.stringify)(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class qe{constructor(e,t,n,s){if(this.onDisconnect=n,this.urlFn=s,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,(0,i.isNodeSdk)())this.commandCB=e,this.onMessageCB=t;else{this.uniqueCallbackIdentifier=f(),window[ve+this.uniqueCallbackIdentifier]=e,window[Ce+this.uniqueCallbackIdentifier]=t,this.myIFrame=qe.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)){n='<script>document.domain="'+document.domain+'";<\/script>'}const i="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(r){w("frame writing exception"),r.stack&&w(r.stack),w(r)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||w("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e[we]=this.myID,e[Te]=this.myPW,e[Ie]=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+Ne+n.length<=Pe))break;{const e=this.pendingSegs.shift();n=n+"&"+ke+i+"="+e.seg+"&"+Ee+i+"="+e.ts+"&"+Se+i+"="+e.d,i++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(De));this.addTag(e,()=>{clearTimeout(i),n()})}addTag(e,t){(0,i.isNodeSdk)()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;const i=this.myIFrame.doc.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.onload=i.onreadystatechange=function(){const e=i.readyState;e&&"loaded"!==e&&"complete"!==e||(i.onload=i.onreadystatechange=null,i.parentNode&&i.parentNode.removeChild(i),t())},i.onerror=(()=>{w("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()}),this.myIFrame.doc.body.appendChild(i)}catch(n){}},Math.floor(1))}}const Fe=16384,Le=45e3;let Oe=null;"undefined"!=typeof MozWebSocket?Oe=MozWebSocket:"undefined"!=typeof WebSocket&&(Oe=WebSocket);class We{constructor(e,t,n,i,s,r,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=T(this.connId),this.stats_=pe(t),this.connURL=We.connectionURL_(t,r,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,s,r){const o={};return o[J]=X,!(0,i.isNodeSdk)()&&"undefined"!=typeof location&&location.hostname&&ne.test(location.hostname)&&(o[ee]=te),t&&(o[Z]=t),n&&(o[ie]=n),s&&(o[re]=s),r&&(o[se]=r),ce(e,oe,o)}open(t,n){this.onDisconnect=n,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,d.set("previous_websocket_failure",!0);try{let t;if((0,i.isNodeSdk)()){const n=this.nodeAdmin?"AdminNode":"Node";t={headers:{"User-Agent":`Firebase/${X}/${a}/${e.platform}/${n}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(t.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(t.headers["X-Firebase-AppCheck"]=this.appCheckToken);const i=e.env,s=0===this.connURL.indexOf("wss://")?i.HTTPS_PROXY||i.https_proxy:i.HTTP_PROXY||i.http_proxy;s&&(t.proxy={origin:s})}this.mySock=new Oe(this.connURL,[],t)}catch(s){this.log_("Error instantiating WebSocket.");const e=s.message||s.data;return e&&this.log_(e),void this.onClosed_()}this.mySock.onopen=(()=>{this.log_("Websocket connected."),this.everConnected_=!0}),this.mySock.onclose=(()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()}),this.mySock.onmessage=(e=>{this.handleIncomingFrame(e)}),this.mySock.onerror=(e=>{this.log_("WebSocket error. Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()})}start(){}static forceDisallow(){We.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==Oe&&!We.forceDisallow_}static previouslyFailed(){return d.isInMemoryStorage||!0===d.get("previous_websocket_failure")}markConnectionHealthy(){d.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=(0,i.jsonEval)(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if((0,i.assert)(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=(0,i.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=q(t,Fe);n.length>1&&this.sendString_(String(n.length));for(let i=0;i<n.length;i++)this.sendString_(n[i])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(Le))}sendString_(e){try{this.mySock.send(e)}catch(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}We.responsesRequiredToBeHealthy=2,We.healthyTimeout=3e4;class Ue{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Me,We]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=We&&We.isAvailable();let n=t&&!We.previouslyFailed();if(e.webSocketOnly&&(t||k("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[We];else{const e=this.transports_=[];for(const t of Ue.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);Ue.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}Ue.globalTransportInitialized_=!1;const Be=6e4,je=5e3,He=10240,Ve=102400,ze="t",Ye="d",Qe="s",Ke="r",Ge="e",$e="o",Xe="a",Je="n",Ze="p",et="h";class tt{constructor(e,t,n,i,s,r,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=r,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=T("c:"+this.id+":"),this.transportManager_=new Ue(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Q(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>Ve?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>He?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(ze in e){const t=e[ze];t===Xe?this.upgradeIfSecondaryHealthy_():t===Ke?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):t===$e&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=A("t",e),n=A("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:Ze,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:Xe,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Je,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=A("t",e),n=A("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=A(ze,e);if(Ye in e){const n=e[Ye];if(t===et){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if(t===Je){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else t===Qe?this.onConnectionShutdown_(n):t===Ke?this.onReset_(n):t===Ge?I("Server Error: "+n):t===$e?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):I("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,n=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),X!==n&&k("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Q(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(Be))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Q(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(je))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:Ze,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(d.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class nt{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class it{constructor(e){this.allowedEvents_=e,this.listeners_={},(0,i.assert)(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let s=0;s<i.length;s++)if(i[s].callback===t&&(!n||n===i[s].context))return void i.splice(s,1)}validateEventType_(e){(0,i.assert)(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class st extends it{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||(0,i.isMobileCordova)()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new st}getInitialEvent(e){return(0,i.assert)("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}const rt=32,ot=768;class at{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function lt(){return new at("")}function ht(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function ct(e){return e.pieces_.length-e.pieceNum_}function ut(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new at(e.pieces_,t)}function dt(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function _t(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}function pt(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function ft(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new at(t,0)}function mt(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof at)for(let i=t.pieceNum_;i<t.pieces_.length;i++)n.push(t.pieces_[i]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new at(n,0)}function gt(e){return e.pieceNum_>=e.pieces_.length}function yt(e,t){const n=ht(e),i=ht(t);if(null===n)return t;if(n===i)return yt(ut(e),ut(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function vt(e,t){const n=pt(e,0),i=pt(t,0);for(let s=0;s<n.length&&s<i.length;s++){const e=R(n[s],i[s]);if(0!==e)return e}return n.length===i.length?0:n.length<i.length?-1:1}function Ct(e,t){if(ct(e)!==ct(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function wt(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(ct(e)>ct(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class Tt{constructor(e,t){this.errorPrefix_=t,this.parts_=pt(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=(0,i.stringLength)(this.parts_[n]);kt(this)}}function It(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=(0,i.stringLength)(t),kt(e)}function bt(e){const t=e.parts_.pop();e.byteLength_-=(0,i.stringLength)(t),e.parts_.length>0&&(e.byteLength_-=1)}function kt(e){if(e.byteLength_>ot)throw new Error(e.errorPrefix_+"has a key path longer than "+ot+" bytes ("+e.byteLength_+").");if(e.parts_.length>rt)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+rt+") or object contains a cycle "+Et(e))}function Et(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class St extends it{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new St}getInitialEvent(e){return(0,i.assert)("visible"===e,"Unknown event type: "+e),[this.visible_]}}const xt=1e3,Pt=3e5,Nt=3e4,Rt=1.3,Dt=3e4,At="server_kill",Mt=3;class qt extends nt{constructor(e,t,n,s,r,o,a,l){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=s,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=l,this.id=qt.nextPersistentConnectionId_++,this.log_=T("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=xt,this.maxReconnectDelay_=Pt,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,l&&!(0,i.isNodeSdk)())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");St.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&st.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const s=++this.requestNumber_,r={r:s,a:e,b:t};this.log_((0,i.stringify)(r)),(0,i.assert)(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),n&&(this.requestCBHash_[s]=n)}get(e){this.initConnection_();const t=new i.Deferred,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const s=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(s),t.promise}listen(e,t,n,s){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),(0,i.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),(0,i.assert)(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:s,hashFn:t,query:e,tag:n};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(e){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const s={p:n};e.tag&&(s.q=t._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest("q",s,s=>{const r=s.d,o=s.s;qt.warnOnListenWarnings_(r,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",s),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,r))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&(0,i.contains)(e,"w")){const n=(0,i.safeGet)(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();k("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${e} at `+`${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||(0,i.isAdmin)(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=Nt)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=(0,i.isValidFormat)(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{const n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){const n=e._path.toString(),s=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+s),(0,i.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,s)&&this.connected_&&this.sendUnlisten_(n,s,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const s={p:e};i&&(s.q=n,s.t=i),this.sendRequest("n",s)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){const s={p:t,d:n};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,e=>{i&&setTimeout(()=>{i(e.s,e.d)},Math.floor(0))})}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,s){this.initConnection_();const r={p:t,d:n};void 0!==s&&(r.h=s),this.outstandingPuts_.push({action:e,request:r,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)})}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+(0,i.stringify)(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):I("Unrecognized action received from server: "+(0,i.stringify)(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){(0,i.assert)(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=xt,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=xt,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>Dt&&(this.reconnectDelay_=xt),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*Rt)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),s=this.id+":"+qt.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const l=function(){a?a.close():(o=!0,n())},h=function(e){(0,i.assert)(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:l,sendRequest:h};const c=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[i,h]=await Promise.all([this.authTokenProvider_.getToken(c),this.appCheckTokenProvider_.getToken(c)]);o?w("getToken() completed but was canceled"):(w("getToken() completed. Creating connection."),this.authToken_=i&&i.accessToken,this.appCheckToken_=h&&h.token,a=new tt(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,e=>{k(e+" ("+this.repoInfo_.toString()+")"),this.interrupt(At)},r))}catch(I){this.log_("Failed to get token: "+I),o||(this.repoInfo_.nodeAdmin&&k(I),l())}}}interrupt(e){w("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){w("Resuming connection for reason: "+e),delete this.interruptReasons_[e],(0,i.isEmpty)(this.interruptReasons_)&&(this.reconnectDelay_=xt,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>M(e)).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new at(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){w("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Mt&&(this.reconnectDelay_=Nt,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){w("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Mt&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let t="js";(0,i.isNodeSdk)()&&(t=this.repoInfo_.nodeAdmin?"admin_node":"node"),e["sdk."+t+"."+a.replace(/\./g,"-")]=1,(0,i.isMobileCordova)()?e["framework.cordova"]=1:(0,i.isReactNative)()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=st.getInstance().currentlyOnline();return(0,i.isEmpty)(this.interruptReasons_)&&e}}qt.nextPersistentConnectionId_=0,qt.nextConnectionId_=0;class Ft{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new Ft(e,t)}}class Lt{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new Ft(P,e),i=new Ft(P,t);return 0!==this.compare(n,i)}minPost(){return Ft.MIN}}let Ot;class Wt extends Lt{static get __EMPTY_NODE(){return Ot}static set __EMPTY_NODE(e){Ot=e}compare(e,t){return R(e.name,t.name)}isDefinedOn(e){throw(0,i.assertionError)("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return Ft.MIN}maxPost(){return new Ft(N,Ot)}makePost(e,t){return(0,i.assert)("string"==typeof e,"KeyIndex indexValue must always be a string."),new Ft(e,Ot)}toString(){return".key"}}const Ut=new Wt;class Bt{constructor(e,t,n,i,s=null){this.isReverse_=i,this.resultGenerator_=s,this.nodeStack_=[];let r=1;for(;!e.isEmpty();)if(e=e,r=t?n(e.key,t):1,i&&(r*=-1),r<0)e=this.isReverse_?e.left:e.right;else{if(0===r){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class jt{constructor(e,t,n,i,s){this.key=e,this.value=t,this.color=null!=n?n:jt.RED,this.left=null!=i?i:Vt.EMPTY_NODE,this.right=null!=s?s:Vt.EMPTY_NODE}copy(e,t,n,i,s){return new jt(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=s?s:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this;const s=n(e,i.key);return(i=s<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===s?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return Vt.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),(e=e.copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,i;if(t(e,(n=this).key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return Vt.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=(e=e.rotateRight_()).colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,jt.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,jt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}jt.RED=!0,jt.BLACK=!1;class Ht{copy(e,t,n,i,s){return this}insert(e,t,n){return new jt(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}}class Vt{constructor(e,t=Vt.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Vt(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,jt.BLACK,null,null))}remove(e){return new Vt(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,jt.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Bt(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Bt(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Bt(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Bt(this.root_,null,this.comparator_,!0,e)}}function zt(e,t){return R(e.name,t.name)}function Yt(e,t){return R(e,t)}let Qt;function Kt(e){Qt=e}Vt.EMPTY_NODE=new Ht;const Gt=function(e){return"number"==typeof e?"number:"+L(e):"string:"+e},$t=function(e){if(e.isLeafNode()){const t=e.val();(0,i.assert)("string"==typeof t||"number"==typeof t||"object"==typeof t&&(0,i.contains)(t,".sv"),"Priority must be a string or number.")}else(0,i.assert)(e===Qt||e.isEmpty(),"priority of unexpected type.");(0,i.assert)(e===Qt||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Xt,Jt,Zt;class en{constructor(e,t=en.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,(0,i.assert)(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),$t(this.priorityNode_)}static set __childrenNodeConstructor(e){Xt=e}static get __childrenNodeConstructor(){return Xt}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new en(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:en.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return gt(e)?this:".priority"===ht(e)?this.priorityNode_:en.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:en.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=ht(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:((0,i.assert)(".priority"!==n||1===ct(e),".priority must be the last token in a path"),this.updateImmediateChild(n,en.__childrenNodeConstructor.EMPTY_NODE.updateChild(ut(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+Gt(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?L(this.value_):this.value_,this.lazyHash_=m(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===en.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof en.__childrenNodeConstructor?-1:((0,i.assert)(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,s=en.VALUE_TYPE_ORDER.indexOf(t),r=en.VALUE_TYPE_ORDER.indexOf(n);return(0,i.assert)(s>=0,"Unknown leaf type: "+t),(0,i.assert)(r>=0,"Unknown leaf type: "+n),s===r?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-s}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}function tn(e){Jt=e}function nn(e){Zt=e}en.VALUE_TYPE_ORDER=["object","boolean","number","string"];class sn extends Lt{compare(e,t){const n=e.node.getPriority(),i=t.node.getPriority(),s=n.compareTo(i);return 0===s?R(e.name,t.name):s}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return Ft.MIN}maxPost(){return new Ft(N,new en("[PRIORITY-POST]",Zt))}makePost(e,t){const n=Jt(e);return new Ft(t,new en("[PRIORITY-POST]",n))}toString(){return".priority"}}const rn=new sn,on=Math.log(2);class an{constructor(e){this.count=(e=>parseInt(Math.log(e)/on,10))(e+1),this.current_=this.count-1;const t=(e=>parseInt(Array(e+1).join("1"),2))(this.count);this.bits_=e+1&t}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const ln=function(e,t,n,i){e.sort(t);const s=function(t,i){const r=i-t;let o,a;if(0===r)return null;if(1===r)return o=e[t],a=n?n(o):o,new jt(a,o.node,jt.BLACK,null,null);{const l=parseInt(r/2,10)+t,h=s(t,l),c=s(l+1,i);return o=e[l],a=n?n(o):o,new jt(a,o.node,jt.BLACK,h,c)}},r=function(t){let i=null,r=null,o=e.length;const a=function(t,i){const r=o-t,a=o;o-=t;const h=s(r+1,a),c=e[r],u=n?n(c):c;l(new jt(u,c.node,i,null,h))},l=function(e){i?(i.left=e,i=e):(r=e,i=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?a(i,jt.BLACK):(a(i,jt.BLACK),a(i,jt.RED))}return r}(new an(e.length));return new Vt(i||t,r)};let hn;const cn={};class un{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,i.assert)(cn&&rn,"ChildrenNode.ts has not been loaded"),hn=hn||new un({".priority":cn},{".priority":rn})}get(e){const t=(0,i.safeGet)(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Vt?t:null}hasIndex(e){return(0,i.contains)(this.indexSet_,e.toString())}addIndex(e,t){(0,i.assert)(e!==Ut,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let s=!1;const r=t.getIterator(Ft.Wrap);let o,a=r.getNext();for(;a;)s=s||e.isDefinedOn(a.node),n.push(a),a=r.getNext();o=s?ln(n,e.getCompare()):cn;const l=e.toString(),h=Object.assign({},this.indexSet_);h[l]=e;const c=Object.assign({},this.indexes_);return c[l]=o,new un(c,h)}addToIndexes(e,t){const n=(0,i.map)(this.indexes_,(n,s)=>{const r=(0,i.safeGet)(this.indexSet_,s);if((0,i.assert)(r,"Missing index implementation for "+s),n===cn){if(r.isDefinedOn(e.node)){const n=[],i=t.getIterator(Ft.Wrap);let s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),ln(n,r.getCompare())}return cn}{const i=t.get(e.name);let s=n;return i&&(s=s.remove(new Ft(e.name,i))),s.insert(e,e.node)}});return new un(n,this.indexSet_)}removeFromIndexes(e,t){const n=(0,i.map)(this.indexes_,n=>{if(n===cn)return n;{const i=t.get(e.name);return i?n.remove(new Ft(e.name,i)):n}});return new un(n,this.indexSet_)}}let dn;class _n{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&$t(this.priorityNode_),this.children_.isEmpty()&&(0,i.assert)(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return dn||(dn=new _n(new Vt(Yt),null,un.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||dn}updatePriority(e){return this.children_.isEmpty()?this:new _n(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?dn:t}}getChild(e){const t=ht(e);return null===t?this:this.getImmediateChild(t).getChild(ut(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if((0,i.assert)(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new Ft(e,t);let i,s;t.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),s=this.indexMap_.addToIndexes(n,this.children_));const r=i.isEmpty()?dn:this.priorityNode_;return new _n(i,r,s)}}updateChild(e,t){const n=ht(e);if(null===n)return t;{(0,i.assert)(".priority"!==ht(e)||1===ct(e),".priority must be the last token in a path");const s=this.getImmediateChild(n).updateChild(ut(e),t);return this.updateImmediateChild(n,s)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,s=!0;if(this.forEachChild(rn,(r,o)=>{t[r]=o.val(e),n++,s&&_n.INTEGER_REGEXP_.test(r)?i=Math.max(i,Number(r)):s=!1}),!e&&s&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Gt(this.getPriority().val())+":"),this.forEachChild(rn,(t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)}),this.lazyHash_=""===e?"":m(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new Ft(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new Ft(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new Ft(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{const n=this.children_.getIteratorFrom(e.name,Ft.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{const n=this.children_.getReverseIteratorFrom(e.name,Ft.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===fn?-1:0}withIndex(e){if(e===Ut||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new _n(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Ut||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(rn),n=t.getIterator(rn);let i=e.getNext(),s=n.getNext();for(;i&&s;){if(i.name!==s.name||!i.node.equals(s.node))return!1;i=e.getNext(),s=n.getNext()}return null===i&&null===s}return!1}return!1}}resolveIndex_(e){return e===Ut?null:this.indexMap_.get(e.toString())}}_n.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class pn extends _n{constructor(){super(new Vt(Yt),_n.EMPTY_NODE,un.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return _n.EMPTY_NODE}isEmpty(){return!1}}const fn=new pn;Object.defineProperties(Ft,{MIN:{value:new Ft(P,_n.EMPTY_NODE)},MAX:{value:new Ft(N,fn)}}),Wt.__EMPTY_NODE=_n.EMPTY_NODE,en.__childrenNodeConstructor=_n,Kt(fn),nn(fn);const mn=!0;function gn(e,t=null){if(null===e)return _n.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),(0,i.assert)(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){return new en(e,gn(t))}if(e instanceof Array||!mn){let n=_n.EMPTY_NODE;return F(e,(t,s)=>{if((0,i.contains)(e,t)&&"."!==t.substring(0,1)){const e=gn(s);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}}),n.updatePriority(gn(t))}{const n=[];let i=!1;if(F(e,(e,t)=>{if("."!==e.substring(0,1)){const s=gn(t);s.isEmpty()||(i=i||!s.getPriority().isEmpty(),n.push(new Ft(e,s)))}}),0===n.length)return _n.EMPTY_NODE;const s=ln(n,zt,e=>e.name,Yt);if(i){const e=ln(n,rn.getCompare());return new _n(s,gn(t),new un({".priority":e},{".priority":rn}))}return new _n(s,gn(t),un.Default)}}tn(gn);class yn extends Lt{constructor(e){super(),this.indexPath_=e,(0,i.assert)(!gt(e)&&".priority"!==ht(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),i=this.extractChild(t.node),s=n.compareTo(i);return 0===s?R(e.name,t.name):s}makePost(e,t){const n=gn(e),i=_n.EMPTY_NODE.updateChild(this.indexPath_,n);return new Ft(t,i)}maxPost(){const e=_n.EMPTY_NODE.updateChild(this.indexPath_,fn);return new Ft(N,e)}toString(){return pt(this.indexPath_,0).join("/")}}class vn extends Lt{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?R(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return Ft.MIN}maxPost(){return Ft.MAX}makePost(e,t){const n=gn(e);return new Ft(t,n)}toString(){return".value"}}const Cn=new vn;function wn(e){return{type:"value",snapshotNode:e}}function Tn(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function In(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function bn(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}function kn(e,t){return{type:"child_moved",snapshotNode:t,childName:e}}class En{constructor(e){this.index_=e}updateChild(e,t,n,s,r,o){(0,i.assert)(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(s).equals(n.getChild(s))&&a.isEmpty()===n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(In(t,a)):(0,i.assert)(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Tn(t,n)):o.trackChildChange(bn(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(rn,(e,i)=>{t.hasChild(e)||n.trackChildChange(In(e,i))}),t.isLeafNode()||t.forEachChild(rn,(t,i)=>{if(e.hasChild(t)){const s=e.getImmediateChild(t);s.equals(i)||n.trackChildChange(bn(t,i,s))}else n.trackChildChange(Tn(t,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?_n.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Sn{constructor(e){this.indexedFilter_=new En(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Sn.getStartPost_(e),this.endPost_=Sn.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,i,s,r){return this.matches(new Ft(t,n))||(n=_n.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,s,r)}updateFullNode(e,t,n){t.isLeafNode()&&(t=_n.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(_n.EMPTY_NODE);const s=this;return t.forEachChild(rn,(e,t)=>{s.matches(new Ft(e,t))||(i=i.updateImmediateChild(e,_n.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class xn{constructor(e){this.withinDirectionalStart=(e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e)),this.withinDirectionalEnd=(e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e)),this.withinStartPost=(e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0}),this.withinEndPost=(e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0}),this.rangedFilter_=new Sn(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,i,s,r){return this.rangedFilter_.matches(new Ft(t,n))||(n=_n.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,i,s,r):this.fullLimitUpdateChild_(e,t,n,s,r)}updateFullNode(e,t,n){let i;if(t.isLeafNode()||t.isEmpty())i=_n.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=_n.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;i=i.updateImmediateChild(t.name,t.node),n++}}}else{let e;i=(i=t.withIndex(this.index_)).updatePriority(_n.EMPTY_NODE),e=this.reverse_?i.getReverseIterator(this.index_):i.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:i=i.updateImmediateChild(t.name,_n.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,s,r){let o;if(this.reverse_){const e=this.index_.getCompare();o=((t,n)=>e(n,t))}else o=this.index_.getCompare();const a=e;(0,i.assert)(a.numChildren()===this.limit_,"");const l=new Ft(t,n),h=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),c=this.rangedFilter_.matches(l);if(a.hasChild(t)){const e=a.getImmediateChild(t);let i=s.getChildAfterChild(this.index_,h,this.reverse_);for(;null!=i&&(i.name===t||a.hasChild(i.name));)i=s.getChildAfterChild(this.index_,i,this.reverse_);const u=null==i?1:o(i,l);if(c&&!n.isEmpty()&&u>=0)return null!=r&&r.trackChildChange(bn(t,n,e)),a.updateImmediateChild(t,n);{null!=r&&r.trackChildChange(In(t,e));const n=a.updateImmediateChild(t,_n.EMPTY_NODE);return null!=i&&this.rangedFilter_.matches(i)?(null!=r&&r.trackChildChange(Tn(i.name,i.node)),n.updateImmediateChild(i.name,i.node)):n}}return n.isEmpty()?e:c&&o(h,l)>=0?(null!=r&&(r.trackChildChange(In(h.name,h.node)),r.trackChildChange(Tn(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(h.name,_n.EMPTY_NODE)):e}}class Pn{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=rn}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return(0,i.assert)(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return(0,i.assert)(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:P}hasEnd(){return this.endSet_}getIndexEndValue(){return(0,i.assert)(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return(0,i.assert)(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:N}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return(0,i.assert)(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===rn}copy(){const e=new Pn;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function Nn(e){return e.loadsAllData()?new En(e.getIndex()):e.hasLimit()?new xn(e):new Sn(e)}function Rn(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}function Dn(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}function An(e,t,n){const i=e.copy();return i.startSet_=!0,void 0===t&&(t=null),i.indexStartValue_=t,null!=n?(i.startNameSet_=!0,i.indexStartName_=n):(i.startNameSet_=!1,i.indexStartName_=""),i}function Mn(e,t,n){let i;return(i=e.index_===Ut||n?An(e,t,n):An(e,t,N)).startAfterSet_=!0,i}function qn(e,t,n){const i=e.copy();return i.endSet_=!0,void 0===t&&(t=null),i.indexEndValue_=t,void 0!==n?(i.endNameSet_=!0,i.indexEndName_=n):(i.endNameSet_=!1,i.indexEndName_=""),i}function Fn(e,t,n){let i;return(i=e.index_===Ut||n?qn(e,t,n):qn(e,t,P)).endBeforeSet_=!0,i}function Ln(e,t){const n=e.copy();return n.index_=t,n}function On(e){const t={};if(e.isDefault())return t;let n;if(e.index_===rn?n="$priority":e.index_===Cn?n="$value":e.index_===Ut?n="$key":((0,i.assert)(e.index_ instanceof yn,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=(0,i.stringify)(n),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=(0,i.stringify)(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+(0,i.stringify)(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=(0,i.stringify)(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+(0,i.stringify)(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Wn(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==rn&&(t.i=e.index_.toString()),t}exports._QueryParams=Pn;class Un extends nt{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=T("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:((0,i.assert)(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,s){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=Un.getListenId_(e,n),a={};this.listens_[o]=a;const l=On(e._queryParams);this.restRequest_(r+".json",l,(e,t)=>{let l=t;if(404===e&&(l=null,e=null),null===e&&this.onDataUpdate_(r,l,!1,n),(0,i.safeGet)(this.listens_,o)===a){let t;s(t=e?401===e?"permission_denied":"rest_error:"+e:"ok",null)}})}unlisten(e,t){const n=Un.getListenId_(e,t);delete this.listens_[n]}get(e){const t=On(e._queryParams),n=e._path.toString(),s=new i.Deferred;return this.restRequest_(n+".json",t,(e,t)=>{let i=t;404===e&&(i=null,e=null),null===e?(this.onDataUpdate_(n,i,!1,null),s.resolve(i)):s.reject(new Error(i))}),s.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([s,r])=>{s&&s.accessToken&&(t.auth=s.accessToken),r&&r.token&&(t.ac=r.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+(0,i.querystring)(t);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=(()=>{if(n&&4===a.readyState){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let t=null;if(a.status>=200&&a.status<300){try{t=(0,i.jsonEval)(a.responseText)}catch(e){k("Failed to parse JSON response for "+o+": "+a.responseText)}n(null,t)}else 401!==a.status&&404!==a.status&&k("Got unsuccessful REST response for "+o+" Status: "+a.status),n(a.status);n=null}}),a.open("GET",o,!0),a.send()})}}class Bn{constructor(){this.rootNode_=_n.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function jn(){return{value:null,children:new Map}}function Hn(e,t,n){if(gt(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=ht(t);e.children.has(i)||e.children.set(i,jn()),Hn(e.children.get(i),t=ut(t),n)}}function Vn(e,t){if(gt(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(rn,(t,n)=>{Hn(e,new at(t),n)}),Vn(e,t)}}if(e.children.size>0){const n=ht(t);if(t=ut(t),e.children.has(n)){Vn(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function zn(e,t,n){null!==e.value?n(t,e.value):Yn(e,(e,i)=>{zn(i,new at(t.toString()+"/"+e),n)})}function Yn(e,t){e.children.forEach((e,n)=>{t(n,e)})}class Qn{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&F(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}const Kn=1e4,Gn=3e4,$n=3e5;class Xn{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Qn(e);const n=Kn+(Gn-Kn)*Math.random();Q(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;F(e,(e,s)=>{s>0&&(0,i.contains)(this.statsToReport_,e)&&(t[e]=s,n=!0)}),n&&this.server_.reportStats(t),Q(this.reportStats_.bind(this),Math.floor(2*Math.random()*$n))}}var Jn;function Zn(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function ei(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function ti(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(Jn||(Jn={}));class ni{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Jn.ACK_USER_WRITE,this.source=Zn()}operationForChild(e){if(gt(this.path)){if(null!=this.affectedTree.value)return(0,i.assert)(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new at(e));return new ni(lt(),t,this.revert)}}return(0,i.assert)(ht(this.path)===e,"operationForChild called for unrelated child."),new ni(ut(this.path),this.affectedTree,this.revert)}}class ii{constructor(e,t){this.source=e,this.path=t,this.type=Jn.LISTEN_COMPLETE}operationForChild(e){return gt(this.path)?new ii(this.source,lt()):new ii(this.source,ut(this.path))}}class si{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Jn.OVERWRITE}operationForChild(e){return gt(this.path)?new si(this.source,lt(),this.snap.getImmediateChild(e)):new si(this.source,ut(this.path),this.snap)}}class ri{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Jn.MERGE}operationForChild(e){if(gt(this.path)){const t=this.children.subtree(new at(e));return t.isEmpty()?null:t.value?new si(this.source,lt(),t.value):new ri(this.source,lt(),t)}return(0,i.assert)(ht(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new ri(this.source,ut(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class oi{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(gt(e))return this.isFullyInitialized()&&!this.filtered_;const t=ht(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class ai{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function li(e,t,n,i){const s=[],r=[];return t.forEach(t=>{"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&r.push(kn(t.childName,t.snapshotNode))}),hi(e,s,"child_removed",t,i,n),hi(e,s,"child_added",t,i,n),hi(e,s,"child_moved",r,i,n),hi(e,s,"child_changed",t,i,n),hi(e,s,"value",t,i,n),s}function hi(e,t,n,i,s,r){const o=i.filter(e=>e.type===n);o.sort((t,n)=>ui(e,t,n)),o.forEach(n=>{const i=ci(e,n,r);s.forEach(s=>{s.respondsTo(n.type)&&t.push(s.createEvent(i,e.query_))})})}function ci(e,t,n){return"value"===t.type||"child_removed"===t.type?t:(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_),t)}function ui(e,t,n){if(null==t.childName||null==n.childName)throw(0,i.assertionError)("Should only compare child_ events.");const s=new Ft(t.childName,t.snapshotNode),r=new Ft(n.childName,n.snapshotNode);return e.index_.compare(s,r)}function di(e,t){return{eventCache:e,serverCache:t}}function _i(e,t,n,i){return di(new oi(t,n,i),e.serverCache)}function pi(e,t,n,i){return di(e.eventCache,new oi(t,n,i))}function fi(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function mi(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let gi;const yi=()=>(gi||(gi=new Vt(D)),gi);class vi{constructor(e,t=yi()){this.value=e,this.children=t}static fromObject(e){let t=new vi(null);return F(e,(e,n)=>{t=t.set(new at(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:lt(),value:this.value};if(gt(e))return null;{const n=ht(e),i=this.children.get(n);if(null!==i){const s=i.findRootMostMatchingPathAndValue(ut(e),t);if(null!=s){return{path:mt(new at(n),s.path),value:s.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(gt(e))return this;{const t=ht(e),n=this.children.get(t);return null!==n?n.subtree(ut(e)):new vi(null)}}set(e,t){if(gt(e))return new vi(t,this.children);{const n=ht(e),i=(this.children.get(n)||new vi(null)).set(ut(e),t),s=this.children.insert(n,i);return new vi(this.value,s)}}remove(e){if(gt(e))return this.children.isEmpty()?new vi(null):new vi(null,this.children);{const t=ht(e),n=this.children.get(t);if(n){const i=n.remove(ut(e));let s;return s=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&s.isEmpty()?new vi(null):new vi(this.value,s)}return this}}get(e){if(gt(e))return this.value;{const t=ht(e),n=this.children.get(t);return n?n.get(ut(e)):null}}setTree(e,t){if(gt(e))return t;{const n=ht(e),i=(this.children.get(n)||new vi(null)).setTree(ut(e),t);let s;return s=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new vi(this.value,s)}}fold(e){return this.fold_(lt(),e)}fold_(e,t){const n={};return this.children.inorderTraversal((i,s)=>{n[i]=s.fold_(mt(e,i),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,lt(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(gt(e))return null;{const i=ht(e),s=this.children.get(i);return s?s.findOnPath_(ut(e),mt(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,lt(),t)}foreachOnPath_(e,t,n){if(gt(e))return this;{this.value&&n(t,this.value);const i=ht(e),s=this.children.get(i);return s?s.foreachOnPath_(ut(e),mt(t,i),n):new vi(null)}}foreach(e){this.foreach_(lt(),e)}foreach_(e,t){this.children.inorderTraversal((n,i)=>{i.foreach_(mt(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}class Ci{constructor(e){this.writeTree_=e}static empty(){return new Ci(new vi(null))}}function wi(e,t,n){if(gt(t))return new Ci(new vi(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const s=i.path;let r=i.value;const o=yt(s,t);return r=r.updateChild(o,n),new Ci(e.writeTree_.set(s,r))}{const i=new vi(n),s=e.writeTree_.setTree(t,i);return new Ci(s)}}}function Ti(e,t,n){let i=e;return F(n,(e,n)=>{i=wi(i,mt(t,e),n)}),i}function Ii(e,t){if(gt(t))return Ci.empty();{const n=e.writeTree_.setTree(t,new vi(null));return new Ci(n)}}function bi(e,t){return null!=ki(e,t)}function ki(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(yt(n.path,t)):null}function Ei(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(rn,(e,n)=>{t.push(new Ft(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new Ft(e,n.value))}),t}function Si(e,t){if(gt(t))return e;{const n=ki(e,t);return new Ci(null!=n?new vi(n):e.writeTree_.subtree(t))}}function xi(e){return e.writeTree_.isEmpty()}function Pi(e,t){return Ni(lt(),e.writeTree_,t)}function Ni(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let s=null;return t.children.inorderTraversal((t,r)=>{".priority"===t?((0,i.assert)(null!==r.value,"Priority writes must always be leaf nodes"),s=r.value):n=Ni(mt(e,t),r,n)}),n.getChild(e).isEmpty()||null===s||(n=n.updateChild(mt(e,".priority"),s)),n}}function Ri(e,t){return es(t,e)}function Di(e,t,n,s,r){(0,i.assert)(s>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),e.allWrites.push({path:t,snap:n,writeId:s,visible:r}),r&&(e.visibleWrites=wi(e.visibleWrites,t,n)),e.lastWriteId=s}function Ai(e,t,n,s){(0,i.assert)(s>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:s,visible:!0}),e.visibleWrites=Ti(e.visibleWrites,t,n),e.lastWriteId=s}function Mi(e,t){for(let n=0;n<e.allWrites.length;n++){const i=e.allWrites[n];if(i.writeId===t)return i}return null}function qi(e,t){const n=e.allWrites.findIndex(e=>e.writeId===t);(0,i.assert)(n>=0,"removeWrite called with nonexistent writeId.");const s=e.allWrites[n];e.allWrites.splice(n,1);let r=s.visible,o=!1,a=e.allWrites.length-1;for(;r&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=n&&Fi(t,s.path)?r=!1:wt(s.path,t.path)&&(o=!0)),a--}if(r){if(o)return Li(e),!0;if(s.snap)e.visibleWrites=Ii(e.visibleWrites,s.path);else{F(s.children,t=>{e.visibleWrites=Ii(e.visibleWrites,mt(s.path,t))})}return!0}return!1}function Fi(e,t){if(e.snap)return wt(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&wt(mt(e.path,n),t))return!0;return!1}function Li(e){e.visibleWrites=Wi(e.allWrites,Oi,lt()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}function Oi(e){return e.visible}function Wi(e,t,n){let s=Ci.empty();for(let r=0;r<e.length;++r){const o=e[r];if(t(o)){const e=o.path;let t;if(o.snap)wt(n,e)?s=wi(s,t=yt(n,e),o.snap):wt(e,n)&&(t=yt(e,n),s=wi(s,lt(),o.snap.getChild(t)));else{if(!o.children)throw(0,i.assertionError)("WriteRecord should have .snap or .children");if(wt(n,e))s=Ti(s,t=yt(n,e),o.children);else if(wt(e,n))if(gt(t=yt(e,n)))s=Ti(s,lt(),o.children);else{const e=(0,i.safeGet)(o.children,ht(t));if(e){const n=e.getChild(ut(t));s=wi(s,lt(),n)}}}}}return s}function Ui(e,t,n,i,s){if(i||s){const r=Si(e.visibleWrites,t);if(!s&&xi(r))return n;if(s||null!=n||bi(r,lt())){const r=function(e){return(e.visible||s)&&(!i||!~i.indexOf(e.writeId))&&(wt(e.path,t)||wt(t,e.path))};return Pi(Wi(e.allWrites,r,t),n||_n.EMPTY_NODE)}return null}{const i=ki(e.visibleWrites,t);if(null!=i)return i;{const i=Si(e.visibleWrites,t);if(xi(i))return n;if(null!=n||bi(i,lt())){return Pi(i,n||_n.EMPTY_NODE)}return null}}}function Bi(e,t,n){let i=_n.EMPTY_NODE;const s=ki(e.visibleWrites,t);if(s)return s.isLeafNode()||s.forEachChild(rn,(e,t)=>{i=i.updateImmediateChild(e,t)}),i;if(n){const s=Si(e.visibleWrites,t);return n.forEachChild(rn,(e,t)=>{const n=Pi(Si(s,new at(e)),t);i=i.updateImmediateChild(e,n)}),Ei(s).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}return Ei(Si(e.visibleWrites,t)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}function ji(e,t,n,s,r){(0,i.assert)(s||r,"Either existingEventSnap or existingServerSnap must exist");const o=mt(t,n);if(bi(e.visibleWrites,o))return null;{const t=Si(e.visibleWrites,o);return xi(t)?r.getChild(n):Pi(t,r.getChild(n))}}function Hi(e,t,n,i){const s=mt(t,n),r=ki(e.visibleWrites,s);if(null!=r)return r;if(i.isCompleteForChild(n)){return Pi(Si(e.visibleWrites,s),i.getNode().getImmediateChild(n))}return null}function Vi(e,t){return ki(e.visibleWrites,t)}function zi(e,t,n,i,s,r,o){let a;const l=Si(e.visibleWrites,t),h=ki(l,lt());if(null!=h)a=h;else{if(null==n)return[];a=Pi(l,n)}if((a=a.withIndex(o)).isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=r?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let l=n.getNext();for(;l&&e.length<s;)0!==t(l,i)&&e.push(l),l=n.getNext();return e}}function Yi(){return{visibleWrites:Ci.empty(),allWrites:[],lastWriteId:-1}}function Qi(e,t,n,i){return Ui(e.writeTree,e.treePath,t,n,i)}function Ki(e,t){return Bi(e.writeTree,e.treePath,t)}function Gi(e,t,n,i){return ji(e.writeTree,e.treePath,t,n,i)}function $i(e,t){return Vi(e.writeTree,mt(e.treePath,t))}function Xi(e,t,n,i,s,r){return zi(e.writeTree,e.treePath,t,n,i,s,r)}function Ji(e,t,n){return Hi(e.writeTree,e.treePath,t,n)}function Zi(e,t){return es(mt(e.treePath,t),e.writeTree)}function es(e,t){return{treePath:e,writeTree:t}}class ts{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;(0,i.assert)("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),(0,i.assert)(".priority"!==n,"Only non-priority child changes can be tracked.");const s=this.changeMap.get(n);if(s){const r=s.type;if("child_added"===t&&"child_removed"===r)this.changeMap.set(n,bn(n,e.snapshotNode,s.snapshotNode));else if("child_removed"===t&&"child_added"===r)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===r)this.changeMap.set(n,In(n,s.oldSnap));else if("child_changed"===t&&"child_added"===r)this.changeMap.set(n,Tn(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==r)throw(0,i.assertionError)("Illegal combination of changes: "+e+" occurred after "+s);this.changeMap.set(n,bn(n,e.snapshotNode,s.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}class ns{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}}const is=new ns;class ss{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new oi(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Ji(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:mi(this.viewCache_),s=Xi(this.writes_,i,t,1,n,e);return 0===s.length?null:s[0]}}function rs(e){return{filter:e}}function os(e,t){(0,i.assert)(t.eventCache.getNode().isIndexed(e.filter.getIndex()),"Event snap not indexed"),(0,i.assert)(t.serverCache.getNode().isIndexed(e.filter.getIndex()),"Server snap not indexed")}function as(e,t,n,s,r){const o=new ts;let a,l;if(n.type===Jn.OVERWRITE){const h=n;h.source.fromUser?a=us(e,t,h.path,h.snap,s,r,o):((0,i.assert)(h.source.fromServer,"Unknown source."),l=h.source.tagged||t.serverCache.isFiltered()&&!gt(h.path),a=cs(e,t,h.path,h.snap,s,r,l,o))}else if(n.type===Jn.MERGE){const h=n;h.source.fromUser?a=_s(e,t,h.path,h.children,s,r,o):((0,i.assert)(h.source.fromServer,"Unknown source."),l=h.source.tagged||t.serverCache.isFiltered(),a=fs(e,t,h.path,h.children,s,r,l,o))}else if(n.type===Jn.ACK_USER_WRITE){const i=n;a=i.revert?ys(e,t,i.path,s,r,o):ms(e,t,i.path,i.affectedTree,s,r,o)}else{if(n.type!==Jn.LISTEN_COMPLETE)throw(0,i.assertionError)("Unknown operation type: "+n.type);a=gs(e,t,n.path,s,o)}const h=o.getChanges();return ls(t,a,h),{viewCache:a,changes:h}}function ls(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const s=i.getNode().isLeafNode()||i.getNode().isEmpty(),r=fi(e);(n.length>0||!e.eventCache.isFullyInitialized()||s&&!i.getNode().equals(r)||!i.getNode().getPriority().equals(r.getPriority()))&&n.push(wn(fi(t)))}}function hs(e,t,n,s,r,o){const a=t.eventCache;if(null!=$i(s,n))return t;{let l,h;if(gt(n))if((0,i.assert)(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=mi(t),i=Ki(s,n instanceof _n?n:_n.EMPTY_NODE);l=e.filter.updateFullNode(t.eventCache.getNode(),i,o)}else{const n=Qi(s,mi(t));l=e.filter.updateFullNode(t.eventCache.getNode(),n,o)}else{const c=ht(n);if(".priority"===c){(0,i.assert)(1===ct(n),"Can't have a priority with additional path components");const r=a.getNode(),o=Gi(s,n,r,h=t.serverCache.getNode());l=null!=o?e.filter.updatePriority(r,o):a.getNode()}else{const i=ut(n);let u;if(a.isCompleteForChild(c)){h=t.serverCache.getNode();const e=Gi(s,n,a.getNode(),h);u=null!=e?a.getNode().getImmediateChild(c).updateChild(i,e):a.getNode().getImmediateChild(c)}else u=Ji(s,c,t.serverCache);l=null!=u?e.filter.updateChild(a.getNode(),c,u,i,r,o):a.getNode()}}return _i(t,l,a.isFullyInitialized()||gt(n),e.filter.filtersNodes())}}function cs(e,t,n,i,s,r,o,a){const l=t.serverCache;let h;const c=o?e.filter:e.filter.getIndexedFilter();if(gt(n))h=c.updateFullNode(l.getNode(),i,null);else if(c.filtersNodes()&&!l.isFiltered()){const e=l.getNode().updateChild(n,i);h=c.updateFullNode(l.getNode(),e,null)}else{const e=ht(n);if(!l.isCompleteForPath(n)&&ct(n)>1)return t;const s=ut(n),r=l.getNode().getImmediateChild(e).updateChild(s,i);h=".priority"===e?c.updatePriority(l.getNode(),r):c.updateChild(l.getNode(),e,r,s,is,null)}const u=pi(t,h,l.isFullyInitialized()||gt(n),c.filtersNodes());return hs(e,u,n,s,new ss(s,u,r),a)}function us(e,t,n,i,s,r,o){const a=t.eventCache;let l,h;const c=new ss(s,t,r);if(gt(n))h=e.filter.updateFullNode(t.eventCache.getNode(),i,o),l=_i(t,h,!0,e.filter.filtersNodes());else{const s=ht(n);if(".priority"===s)h=e.filter.updatePriority(t.eventCache.getNode(),i),l=_i(t,h,a.isFullyInitialized(),a.isFiltered());else{const r=ut(n),h=a.getNode().getImmediateChild(s);let u;if(gt(r))u=i;else{const e=c.getCompleteChild(s);u=null!=e?".priority"===dt(r)&&e.getChild(ft(r)).isEmpty()?e:e.updateChild(r,i):_n.EMPTY_NODE}if(h.equals(u))l=t;else{l=_i(t,e.filter.updateChild(a.getNode(),s,u,r,c,o),a.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function ds(e,t){return e.eventCache.isCompleteForChild(t)}function _s(e,t,n,i,s,r,o){let a=t;return i.foreach((i,l)=>{const h=mt(n,i);ds(t,ht(h))&&(a=us(e,a,h,l,s,r,o))}),i.foreach((i,l)=>{const h=mt(n,i);ds(t,ht(h))||(a=us(e,a,h,l,s,r,o))}),a}function ps(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function fs(e,t,n,i,s,r,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l,h=t;l=gt(n)?i:new vi(null).setTree(n,i);const c=t.serverCache.getNode();return l.children.inorderTraversal((n,i)=>{if(c.hasChild(n)){const l=t.serverCache.getNode().getImmediateChild(n),c=ps(e,l,i);h=cs(e,h,new at(n),c,s,r,o,a)}}),l.children.inorderTraversal((n,i)=>{const l=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!c.hasChild(n)&&!l){const l=t.serverCache.getNode().getImmediateChild(n),c=ps(e,l,i);h=cs(e,h,new at(n),c,s,r,o,a)}}),h}function ms(e,t,n,i,s,r,o){if(null!=$i(s,n))return t;const a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=i.value){if(gt(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return cs(e,t,n,l.getNode().getChild(n),s,r,a,o);if(gt(n)){let i=new vi(null);return l.getNode().forEachChild(Ut,(e,t)=>{i=i.set(new at(e),t)}),fs(e,t,n,i,s,r,a,o)}return t}{let h=new vi(null);return i.foreach((e,t)=>{const i=mt(n,e);l.isCompleteForPath(i)&&(h=h.set(e,l.getNode().getChild(i)))}),fs(e,t,n,h,s,r,a,o)}}function gs(e,t,n,i,s){const r=t.serverCache;return hs(e,pi(t,r.getNode(),r.isFullyInitialized()||gt(n),r.isFiltered()),n,i,is,s)}function ys(e,t,n,s,r,o){let a;if(null!=$i(s,n))return t;{const l=new ss(s,t,r),h=t.eventCache.getNode();let c;if(gt(n)||".priority"===ht(n)){let n;if(t.serverCache.isFullyInitialized())n=Qi(s,mi(t));else{const e=t.serverCache.getNode();(0,i.assert)(e instanceof _n,"serverChildren would be complete if leaf node"),n=Ki(s,e)}n=n,c=e.filter.updateFullNode(h,n,o)}else{const i=ht(n);let r=Ji(s,i,t.serverCache);null==r&&t.serverCache.isCompleteForChild(i)&&(r=h.getImmediateChild(i)),(c=null!=r?e.filter.updateChild(h,i,r,ut(n),l,o):t.eventCache.getNode().hasChild(i)?e.filter.updateChild(h,i,_n.EMPTY_NODE,ut(n),l,o):h).isEmpty()&&t.serverCache.isFullyInitialized()&&(a=Qi(s,mi(t))).isLeafNode()&&(c=e.filter.updateFullNode(c,a,o))}return a=t.serverCache.isFullyInitialized()||null!=$i(s,lt()),_i(t,c,a,e.filter.filtersNodes())}}class vs{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,i=new En(n.getIndex()),s=Nn(n);this.processor_=rs(s);const r=t.serverCache,o=t.eventCache,a=i.updateFullNode(_n.EMPTY_NODE,r.getNode(),null),l=s.updateFullNode(_n.EMPTY_NODE,o.getNode(),null),h=new oi(a,r.isFullyInitialized(),i.filtersNodes()),c=new oi(l,o.isFullyInitialized(),s.filtersNodes());this.viewCache_=di(c,h),this.eventGenerator_=new ai(this.query_)}get query(){return this.query_}}function Cs(e){return e.viewCache_.serverCache.getNode()}function ws(e){return fi(e.viewCache_)}function Ts(e,t){const n=mi(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!gt(t)&&!n.getImmediateChild(ht(t)).isEmpty())?n.getChild(t):null}function Is(e){return 0===e.eventRegistrations_.length}function bs(e,t){e.eventRegistrations_.push(t)}function ks(e,t,n){const s=[];if(n){(0,i.assert)(null==t,"A cancel should cancel all event registrations.");const r=e.query._path;e.eventRegistrations_.forEach(e=>{const t=e.createCancelEvent(n,r);t&&s.push(t)})}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){const s=e.eventRegistrations_[i];if(s.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(i+1));break}}else n.push(s)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return s}function Es(e,t,n,s){t.type===Jn.MERGE&&null!==t.source.queryId&&((0,i.assert)(mi(e.viewCache_),"We should always have a full cache before handling merges"),(0,i.assert)(fi(e.viewCache_),"Missing event cache, even though we have a server cache"));const r=e.viewCache_,o=as(e.processor_,r,t,n,s);return os(e.processor_,o.viewCache),(0,i.assert)(o.viewCache.serverCache.isFullyInitialized()||!r.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=o.viewCache,xs(e,o.changes,o.viewCache.eventCache.getNode(),null)}function Ss(e,t){const n=e.viewCache_.eventCache,i=[];if(!n.getNode().isLeafNode()){n.getNode().forEachChild(rn,(e,t)=>{i.push(Tn(e,t))})}return n.isFullyInitialized()&&i.push(wn(n.getNode())),xs(e,i,n.getNode(),t)}function xs(e,t,n,i){const s=i?[i]:e.eventRegistrations_;return li(e.eventGenerator_,t,n,s)}let Ps,Ns;class Rs{constructor(){this.views=new Map}}function Ds(e){(0,i.assert)(!Ps,"__referenceConstructor has already been defined"),Ps=e}function As(){return(0,i.assert)(Ps,"Reference.ts has not been loaded"),Ps}function Ms(e){return 0===e.views.size}function qs(e,t,n,s){const r=t.source.queryId;if(null!==r){const o=e.views.get(r);return(0,i.assert)(null!=o,"SyncTree gave us an op for an invalid query."),Es(o,t,n,s)}{let i=[];for(const r of e.views.values())i=i.concat(Es(r,t,n,s));return i}}function Fs(e,t,n,i,s){const r=t._queryIdentifier,o=e.views.get(r);if(!o){let e=Qi(n,s?i:null),r=!1;e?r=!0:i instanceof _n?(e=Ki(n,i),r=!1):(e=_n.EMPTY_NODE,r=!1);const o=di(new oi(e,r,!1),new oi(i,s,!1));return new vs(t,o)}return o}function Ls(e,t,n,i,s,r){const o=Fs(e,t,i,s,r);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),bs(o,n),Ss(o,n)}function Os(e,t,n,i){const s=t._queryIdentifier,r=[];let o=[];const a=Hs(e);if("default"===s)for(const[l,h]of e.views.entries())o=o.concat(ks(h,n,i)),Is(h)&&(e.views.delete(l),h.query._queryParams.loadsAllData()||r.push(h.query));else{const t=e.views.get(s);t&&(o=o.concat(ks(t,n,i)),Is(t)&&(e.views.delete(s),t.query._queryParams.loadsAllData()||r.push(t.query)))}return a&&!Hs(e)&&r.push(new(As())(t._repo,t._path)),{removed:r,events:o}}function Ws(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Us(e,t){let n=null;for(const i of e.views.values())n=n||Ts(i,t);return n}function Bs(e,t){if(t._queryParams.loadsAllData())return Vs(e);{const n=t._queryIdentifier;return e.views.get(n)}}function js(e,t){return null!=Bs(e,t)}function Hs(e){return null!=Vs(e)}function Vs(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}function zs(e){(0,i.assert)(!Ns,"__referenceConstructor has already been defined"),Ns=e}function Ys(){return(0,i.assert)(Ns,"Reference.ts has not been loaded"),Ns}let Qs=1;class Ks{constructor(e){this.listenProvider_=e,this.syncPointTree_=new vi(null),this.pendingWriteTree_=Yi(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Gs(e,t,n,i,s){return Di(e.pendingWriteTree_,t,n,i,s),s?lr(e,new si(Zn(),t,n)):[]}function $s(e,t,n,i){Ai(e.pendingWriteTree_,t,n,i);const s=vi.fromObject(n);return lr(e,new ri(Zn(),t,s))}function Xs(e,t,n=!1){const i=Mi(e.pendingWriteTree_,t);if(qi(e.pendingWriteTree_,t)){let t=new vi(null);return null!=i.snap?t=t.set(lt(),!0):F(i.children,e=>{t=t.set(new at(e),!0)}),lr(e,new ni(i.path,t,n))}return[]}function Js(e,t,n){return lr(e,new si(ei(),t,n))}function Zs(e,t,n){const i=vi.fromObject(n);return lr(e,new ri(ei(),t,i))}function er(e,t){return lr(e,new ii(ei(),t))}function tr(e,t,n){const i=pr(e,n);if(i){const n=fr(i),s=n.path,r=n.queryId,o=yt(s,t);return mr(e,s,new ii(ti(r),o))}return[]}function nr(e,t,n,i,s=!1){const r=t._path,o=e.syncPointTree_.get(r);let a=[];if(o&&("default"===t._queryIdentifier||js(o,t))){const l=Os(o,t,n,i);Ms(o)&&(e.syncPointTree_=e.syncPointTree_.remove(r));const h=l.removed;if(a=l.events,!s){const n=-1!==h.findIndex(e=>e._queryParams.loadsAllData()),s=e.syncPointTree_.findOnPath(r,(e,t)=>Hs(t));if(n&&!s){const t=e.syncPointTree_.subtree(r);if(!t.isEmpty()){const n=gr(t);for(let t=0;t<n.length;++t){const i=n[t],s=i.query,r=ur(e,i);e.listenProvider_.startListening(yr(s),dr(e,s),r.hashFn,r.onComplete)}}}if(!s&&h.length>0&&!i)if(n){const n=null;e.listenProvider_.stopListening(yr(t),n)}else h.forEach(t=>{const n=e.queryToTagMap.get(_r(t));e.listenProvider_.stopListening(yr(t),n)})}vr(e,h)}return a}function ir(e,t,n,i){const s=pr(e,i);if(null!=s){const i=fr(s),r=i.path,o=i.queryId,a=yt(r,t);return mr(e,r,new si(ti(o),a,n))}return[]}function sr(e,t,n,i){const s=pr(e,i);if(s){const i=fr(s),r=i.path,o=i.queryId,a=yt(r,t),l=vi.fromObject(n);return mr(e,r,new ri(ti(o),a,l))}return[]}function rr(e,t,n,s=!1){const r=t._path;let o=null,a=!1;e.syncPointTree_.foreachOnPath(r,(e,t)=>{const n=yt(e,r);o=o||Us(t,n),a=a||Hs(t)});let l,h=e.syncPointTree_.get(r);if(h?(a=a||Hs(h),o=o||Us(h,lt())):(h=new Rs,e.syncPointTree_=e.syncPointTree_.set(r,h)),null!=o)l=!0;else{l=!1,o=_n.EMPTY_NODE,e.syncPointTree_.subtree(r).foreachChild((e,t)=>{const n=Us(t,lt());n&&(o=o.updateImmediateChild(e,n))})}const c=js(h,t);if(!c&&!t._queryParams.loadsAllData()){const n=_r(t);(0,i.assert)(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const s=Cr();e.queryToTagMap.set(n,s),e.tagToQueryMap.set(s,n)}let u=Ls(h,t,n,Ri(e.pendingWriteTree_,r),o,l);if(!c&&!a&&!s){const n=Bs(h,t);u=u.concat(wr(e,t,n))}return u}function or(e,t,n){const i=e.pendingWriteTree_,s=e.syncPointTree_.findOnPath(t,(e,n)=>{const i=Us(n,yt(e,t));if(i)return i});return Ui(i,t,s,n,!0)}function ar(e,t){const n=t._path;let i=null;e.syncPointTree_.foreachOnPath(n,(e,t)=>{const s=yt(e,n);i=i||Us(t,s)});let s=e.syncPointTree_.get(n);s?i=i||Us(s,lt()):(s=new Rs,e.syncPointTree_=e.syncPointTree_.set(n,s));const r=null!=i,o=r?new oi(i,!0,!1):null;return ws(Fs(s,t,Ri(e.pendingWriteTree_,t._path),r?o.getNode():_n.EMPTY_NODE,r))}function lr(e,t){return hr(t,e.syncPointTree_,null,Ri(e.pendingWriteTree_,lt()))}function hr(e,t,n,i){if(gt(e.path))return cr(e,t,n,i);{const s=t.get(lt());null==n&&null!=s&&(n=Us(s,lt()));let r=[];const o=ht(e.path),a=e.operationForChild(o),l=t.children.get(o);if(l&&a){const e=n?n.getImmediateChild(o):null,t=Zi(i,o);r=r.concat(hr(a,l,e,t))}return s&&(r=r.concat(qs(s,e,i,n))),r}}function cr(e,t,n,i){const s=t.get(lt());null==n&&null!=s&&(n=Us(s,lt()));let r=[];return t.children.inorderTraversal((t,s)=>{const o=n?n.getImmediateChild(t):null,a=Zi(i,t),l=e.operationForChild(t);l&&(r=r.concat(cr(l,s,o,a)))}),s&&(r=r.concat(qs(s,e,i,n))),r}function ur(e,t){const n=t.query,i=dr(e,n);return{hashFn:()=>{return(Cs(t)||_n.EMPTY_NODE).hash()},onComplete:t=>{if("ok"===t)return i?tr(e,n._path,i):er(e,n._path);{const i=U(t,n);return nr(e,n,null,i)}}}}function dr(e,t){const n=_r(t);return e.queryToTagMap.get(n)}function _r(e){return e._path.toString()+"$"+e._queryIdentifier}function pr(e,t){return e.tagToQueryMap.get(t)}function fr(e){const t=e.indexOf("$");return(0,i.assert)(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new at(e.substr(0,t))}}function mr(e,t,n){const s=e.syncPointTree_.get(t);return(0,i.assert)(s,"Missing sync point for query tag that we're tracking"),qs(s,n,Ri(e.pendingWriteTree_,t),null)}function gr(e){return e.fold((e,t,n)=>{if(t&&Hs(t)){return[Vs(t)]}{let e=[];return t&&(e=Ws(t)),F(n,(t,n)=>{e=e.concat(n)}),e}})}function yr(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(Ys())(e._repo,e._path):e}function vr(e,t){for(let n=0;n<t.length;++n){const i=t[n];if(!i._queryParams.loadsAllData()){const t=_r(i),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}function Cr(){return Qs++}function wr(e,t,n){const s=t._path,r=dr(e,t),o=ur(e,n),a=e.listenProvider_.startListening(yr(t),r,o.hashFn,o.onComplete),l=e.syncPointTree_.subtree(s);if(r)(0,i.assert)(!Hs(l.value),"If we're adding a query, it shouldn't be shadowed");else{const t=l.fold((e,t,n)=>{if(!gt(e)&&t&&Hs(t))return[Vs(t).query];{let e=[];return t&&(e=e.concat(Ws(t).map(e=>e.query))),F(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){const i=t[n];e.listenProvider_.stopListening(yr(i),dr(e,i))}}return a}class Tr{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new Tr(t)}node(){return this.node_}}class Ir{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=mt(this.path_,e);return new Ir(this.syncTree_,t)}node(){return or(this.syncTree_,this.path_)}}const br=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},kr=function(e,t,n){return e&&"object"==typeof e?((0,i.assert)(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Er(e[".sv"],t,n):"object"==typeof e[".sv"]?Sr(e[".sv"],t):void(0,i.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},Er=function(e,t,n){switch(e){case"timestamp":return n.timestamp;default:(0,i.assert)(!1,"Unexpected server value: "+e)}},Sr=function(e,t,n){e.hasOwnProperty("increment")||(0,i.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const s=e.increment;"number"!=typeof s&&(0,i.assert)(!1,"Unexpected increment value: "+s);const r=t.node();if((0,i.assert)(null!=r,"Expected ChildrenNode.EMPTY_NODE for nulls"),!r.isLeafNode())return s;const o=r.getValue();return"number"!=typeof o?s:o+s},xr=function(e,t,n,i){return Nr(t,new Ir(n,e),i)},Pr=function(e,t,n){return Nr(e,new Tr(t),n)};function Nr(e,t,n){const i=e.getPriority().val(),s=kr(i,t.getImmediateChild(".priority"),n);let r;if(e.isLeafNode()){const i=e,r=kr(i.getValue(),t,n);return r!==i.getValue()||s!==i.getPriority().val()?new en(r,gn(s)):e}{const i=e;return r=i,s!==i.getPriority().val()&&(r=r.updatePriority(new en(s))),i.forEachChild(rn,(e,i)=>{const s=Nr(i,t.getImmediateChild(e),n);s!==i&&(r=r.updateImmediateChild(e,s))}),r}}class Rr{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function Dr(e,t){let n=t instanceof at?t:new at(t),s=e,r=ht(n);for(;null!==r;){const e=(0,i.safeGet)(s.node.children,r)||{children:{},childCount:0};s=new Rr(r,s,e),r=ht(n=ut(n))}return s}function Ar(e){return e.node.value}function Mr(e,t){e.node.value=t,Br(e)}function qr(e){return e.node.childCount>0}function Fr(e){return void 0===Ar(e)&&!qr(e)}function Lr(e,t){F(e.node.children,(n,i)=>{t(new Rr(n,e,i))})}function Or(e,t,n,i){n&&!i&&t(e),Lr(e,e=>{Or(e,t,!0,i)}),n&&i&&t(e)}function Wr(e,t,n){let i=n?e:e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}return!1}function Ur(e){return new at(null===e.parent?e.name:Ur(e.parent)+"/"+e.name)}function Br(e){null!==e.parent&&jr(e.parent,e.name,e)}function jr(e,t,n){const s=Fr(n),r=(0,i.contains)(e.node.children,t);s&&r?(delete e.node.children[t],e.node.childCount--,Br(e)):s||r||(e.node.children[t]=n.node,e.node.childCount++,Br(e))}const Hr=/[\[\].#$\/\u0000-\u001F\u007F]/,Vr=/[\[\].#$\u0000-\u001F\u007F]/,zr=10485760,Yr=function(e){return"string"==typeof e&&0!==e.length&&!Hr.test(e)},Qr=function(e){return"string"==typeof e&&0!==e.length&&!Vr.test(e)},Kr=function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),Qr(e)},Gr=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!S(e)||e&&"object"==typeof e&&(0,i.contains)(e,".sv")},$r=function(e,t,n,s){s&&void 0===t||Xr((0,i.errorPrefix)(e,"value"),t,n)},Xr=function(e,t,n){const s=n instanceof at?new Tt(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+Et(s));if("function"==typeof t)throw new Error(e+"contains a function "+Et(s)+" with contents = "+t.toString());if(S(t))throw new Error(e+"contains "+t.toString()+" "+Et(s));if("string"==typeof t&&t.length>10485760/3&&(0,i.stringLength)(t)>10485760)throw new Error(e+"contains a string greater than 10485760 utf8 bytes "+Et(s)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,i=!1;if(F(t,(t,r)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(i=!0,!Yr(t)))throw new Error(e+" contains an invalid key ("+t+") "+Et(s)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');It(s,t),Xr(e,r,s),bt(s)}),n&&i)throw new Error(e+' contains ".value" child '+Et(s)+" in addition to actual children.")}},Jr=function(e,t){let n,i;for(n=0;n<t.length;n++){const s=pt(i=t[n]);for(let t=0;t<s.length;t++)if(".priority"===s[t]&&t===s.length-1);else if(!Yr(s[t]))throw new Error(e+"contains an invalid key ("+s[t]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(vt);let s=null;for(n=0;n<t.length;n++){if(i=t[n],null!==s&&wt(s,i))throw new Error(e+"contains a path "+s.toString()+" that is ancestor of another path "+i.toString());s=i}},Zr=function(e,t,n,s){if(s&&void 0===t)return;const r=(0,i.errorPrefix)(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(r+" must be an object containing the children to replace.");const o=[];F(t,(e,t)=>{const i=new at(e);if(Xr(r,t,mt(n,i)),".priority"===dt(i)&&!Gr(t))throw new Error(r+"contains an invalid value for '"+i.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(i)}),Jr(r,o)},eo=function(e,t,n){if(!n||void 0!==t){if(S(t))throw new Error((0,i.errorPrefix)(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Gr(t))throw new Error((0,i.errorPrefix)(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},to=function(e,t,n,s){if(!(s&&void 0===n||Yr(n)))throw new Error((0,i.errorPrefix)(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},no=function(e,t,n,s){if(!(s&&void 0===n||Qr(n)))throw new Error((0,i.errorPrefix)(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')};exports._validatePathString=no;const io=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),no(e,t,n,i)},so=function(e,t){if(".info"===ht(t))throw new Error(e+" failed = Can't modify data under /.info/")};exports._validateWritablePath=so;const ro=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Yr(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Kr(n))throw new Error((0,i.errorPrefix)(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class oo{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function ao(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i],r=s.getPath();null===n||Ct(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function lo(e,t,n){ao(e,n),co(e,e=>Ct(e,t))}function ho(e,t,n){ao(e,n),co(e,e=>wt(e,t)||wt(t,e))}function co(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){const s=e.eventLists_[i];if(s){t(s.path)?(uo(e.eventLists_[i]),e.eventLists_[i]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function uo(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const i=n.getEventRunner();y&&w("event: "+n.toString()),z(i)}}}const _o="repo_interrupt",po=25;class fo{constructor(e,t,n,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new oo,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=jn(),this.transactionQueueTree_=new Rr,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function mo(e,t,n){if(e.stats_=pe(e.repoInfo_),e.forceRestClient_||Y())e.server_=new Un(e.repoInfo_,(t,n,i,s)=>{vo(e,t,n,i,s)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>Co(e,!0),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{(0,i.stringify)(n)}catch(s){throw new Error("Invalid authOverride provided: "+s)}}e.persistentConnection_=new qt(e.repoInfo_,t,(t,n,i,s)=>{vo(e,t,n,i,s)},t=>{Co(e,t)},t=>{wo(e,t)},e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener(t=>{e.server_.refreshAuthToken(t)}),e.appCheckProvider_.addTokenChangeListener(t=>{e.server_.refreshAppCheckToken(t.token)}),e.statsReporter_=fe(e.repoInfo_,()=>new Xn(e.stats_,e.server_)),e.infoData_=new Bn,e.infoSyncTree_=new Ks({startListening:(t,n,i,s)=>{let r=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(r=Js(e.infoSyncTree_,t._path,o),setTimeout(()=>{s("ok")},0)),r},stopListening:()=>{}}),To(e,"connected",!1),e.serverSyncTree_=new Ks({startListening:(t,n,i,s)=>(e.server_.listen(t,i,n,(n,i)=>{const r=s(n,i);ho(e.eventQueue_,t._path,r)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function go(e){const t=e.infoData_.getNode(new at(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function yo(e){return br({timestamp:go(e)})}function vo(e,t,n,s,r){e.dataUpdateCount++;const o=new at(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let a=[];if(r)if(s){const t=(0,i.map)(n,e=>gn(e));a=sr(e.serverSyncTree_,o,t,r)}else{const t=gn(n);a=ir(e.serverSyncTree_,o,t,r)}else if(s){const t=(0,i.map)(n,e=>gn(e));a=Zs(e.serverSyncTree_,o,t)}else{const t=gn(n);a=Js(e.serverSyncTree_,o,t)}let l=o;a.length>0&&(l=jo(e,o)),ho(e.eventQueue_,l,a)}function Co(e,t){To(e,"connected",t),!1===t&&So(e)}function wo(e,t){F(t,(t,n)=>{To(e,t,n)})}function To(e,t,n){const i=new at("/.info/"+t),s=gn(n);e.infoData_.updateSnapshot(i,s);const r=Js(e.infoSyncTree_,i,s);ho(e.eventQueue_,i,r)}function Io(e){return e.nextWriteId_++}function bo(e,t,n){const s=ar(e.serverSyncTree_,t);return null!=s?Promise.resolve(s):e.server_.get(t).then(i=>{const s=gn(i).withIndex(t._queryParams.getIndex());let r;if(rr(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())r=Js(e.serverSyncTree_,t._path,s);else{const n=dr(e.serverSyncTree_,t);r=ir(e.serverSyncTree_,t._path,s,n)}return ho(e.eventQueue_,t._path,r),nr(e.serverSyncTree_,t,n,null,!0),s},n=>(Fo(e,"get for query "+(0,i.stringify)(t)+" failed: "+n),Promise.reject(new Error(n))))}function ko(e,t,n,i,s){Fo(e,"set",{path:t.toString(),value:n,priority:i});const r=yo(e),o=gn(n,i),a=or(e.serverSyncTree_,t),l=Pr(o,a,r),h=Io(e),c=Gs(e.serverSyncTree_,t,l,h,!0);ao(e.eventQueue_,c),e.server_.put(t.toString(),o.val(!0),(n,i)=>{const r="ok"===n;r||k("set at "+t+" failed: "+n);const o=Xs(e.serverSyncTree_,h,!r);ho(e.eventQueue_,t,o),Lo(e,s,n,i)});const u=Ko(e,t);jo(e,u),ho(e.eventQueue_,u,[])}function Eo(e,t,n,i){Fo(e,"update",{path:t.toString(),value:n});let s=!0;const r=yo(e),o={};if(F(n,(n,i)=>{s=!1,o[n]=xr(mt(t,n),gn(i),e.serverSyncTree_,r)}),s)w("update() called with empty data. Don't do anything."),Lo(e,i,"ok",void 0);else{const s=Io(e),r=$s(e.serverSyncTree_,t,o,s);ao(e.eventQueue_,r),e.server_.merge(t.toString(),n,(n,r)=>{const o="ok"===n;o||k("update at "+t+" failed: "+n);const a=Xs(e.serverSyncTree_,s,!o),l=a.length>0?jo(e,t):t;ho(e.eventQueue_,l,a),Lo(e,i,n,r)}),F(n,n=>{const i=Ko(e,mt(t,n));jo(e,i)}),ho(e.eventQueue_,t,[])}}function So(e){Fo(e,"onDisconnectEvents");const t=yo(e),n=jn();zn(e.onDisconnect_,lt(),(i,s)=>{const r=xr(i,s,e.serverSyncTree_,t);Hn(n,i,r)});let i=[];zn(n,lt(),(t,n)=>{i=i.concat(Js(e.serverSyncTree_,t,n));const s=Ko(e,t);jo(e,s)}),e.onDisconnect_=jn(),ho(e.eventQueue_,lt(),i)}function xo(e,t,n){e.server_.onDisconnectCancel(t.toString(),(i,s)=>{"ok"===i&&Vn(e.onDisconnect_,t),Lo(e,n,i,s)})}function Po(e,t,n,i){const s=gn(n);e.server_.onDisconnectPut(t.toString(),s.val(!0),(n,r)=>{"ok"===n&&Hn(e.onDisconnect_,t,s),Lo(e,i,n,r)})}function No(e,t,n,i,s){const r=gn(n,i);e.server_.onDisconnectPut(t.toString(),r.val(!0),(n,i)=>{"ok"===n&&Hn(e.onDisconnect_,t,r),Lo(e,s,n,i)})}function Ro(e,t,n,s){if((0,i.isEmpty)(n))return w("onDisconnect().update() called with empty data. Don't do anything."),void Lo(e,s,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,(i,r)=>{"ok"===i&&F(n,(n,i)=>{const s=gn(i);Hn(e.onDisconnect_,mt(t,n),s)}),Lo(e,s,i,r)})}function Do(e,t,n){let i;i=".info"===ht(t._path)?rr(e.infoSyncTree_,t,n):rr(e.serverSyncTree_,t,n),lo(e.eventQueue_,t._path,i)}function Ao(e,t,n){let i;i=".info"===ht(t._path)?nr(e.infoSyncTree_,t,n):nr(e.serverSyncTree_,t,n),lo(e.eventQueue_,t._path,i)}function Mo(e){e.persistentConnection_&&e.persistentConnection_.interrupt(_o)}function qo(e){e.persistentConnection_&&e.persistentConnection_.resume(_o)}function Fo(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),w(n,...t)}function Lo(e,t,n,i){t&&z(()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let s=e;i&&(s+=": "+i);const r=new Error(s);r.code=e,t(r)}})}function Oo(e,t,n,s,r,o){Fo(e,"transaction on "+t);const a={path:t,update:n,onComplete:s,status:null,order:f(),applyLocally:o,retryCount:0,unwatcher:r,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},l=Wo(e,t,void 0);a.currentInputSnapshot=l;const h=a.update(l.val());if(void 0===h)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Xr("transaction failed: Data returned ",h,a.path),a.status=0;const n=Dr(e.transactionQueueTree_,t),s=Ar(n)||[];let r;if(s.push(a),Mr(n,s),"object"==typeof h&&null!==h&&(0,i.contains)(h,".priority"))r=(0,i.safeGet)(h,".priority"),(0,i.assert)(Gr(r),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{r=(or(e.serverSyncTree_,t)||_n.EMPTY_NODE).getPriority().val()}const o=yo(e),c=gn(h,r),u=Pr(c,l,o);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=u,a.currentWriteId=Io(e);const d=Gs(e.serverSyncTree_,t,u,a.currentWriteId,a.applyLocally);ho(e.eventQueue_,t,d),Uo(e,e.transactionQueueTree_)}}function Wo(e,t,n){return or(e.serverSyncTree_,t,n)||_n.EMPTY_NODE}function Uo(e,t=e.transactionQueueTree_){if(t||Qo(e,t),Ar(t)){const n=zo(e,t);(0,i.assert)(n.length>0,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&Bo(e,Ur(t),n)}else qr(t)&&Lr(t,t=>{Uo(e,t)})}function Bo(e,t,n){const s=n.map(e=>e.currentWriteId),r=Wo(e,t,s);let o=r;const a=r.hash();for(let c=0;c<n.length;c++){const e=n[c];(0,i.assert)(0===e.status,"tryToSendTransactionQueue_: items in queue should all be run."),e.status=1,e.retryCount++;const s=yt(t,e.path);o=o.updateChild(s,e.currentOutputSnapshotRaw)}const l=o.val(!0),h=t;e.server_.put(h.toString(),l,i=>{Fo(e,"transaction put response",{path:h.toString(),status:i});let s=[];if("ok"===i){const i=[];for(let t=0;t<n.length;t++)n[t].status=2,s=s.concat(Xs(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&i.push(()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved)),n[t].unwatcher();Qo(e,Dr(e.transactionQueueTree_,t)),Uo(e,e.transactionQueueTree_),ho(e.eventQueue_,t,s);for(let e=0;e<i.length;e++)z(i[e])}else{if("datastale"===i)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{k("transaction at "+h.toString()+" failed: "+i);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=i}jo(e,t)}},a)}function jo(e,t){const n=Vo(e,t),i=Ur(n);return Ho(e,zo(e,n),i),i}function Ho(e,t,n){if(0===t.length)return;const s=[];let r=[];const o=t.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let l=0;l<t.length;l++){const h=t[l],c=yt(n,h.path);let u,d=!1;if((0,i.assert)(null!==c,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)d=!0,u=h.abortReason,r=r.concat(Xs(e.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=po)d=!0,u="maxretry",r=r.concat(Xs(e.serverSyncTree_,h.currentWriteId,!0));else{const n=Wo(e,h.path,o);h.currentInputSnapshot=n;const s=t[l].update(n.val());if(void 0!==s){Xr("transaction failed: Data returned ",s,h.path);let t=gn(s);"object"==typeof s&&null!=s&&(0,i.contains)(s,".priority")||(t=t.updatePriority(n.getPriority()));const a=h.currentWriteId,l=yo(e),c=Pr(t,n,l);h.currentOutputSnapshotRaw=t,h.currentOutputSnapshotResolved=c,h.currentWriteId=Io(e),o.splice(o.indexOf(a),1),r=(r=r.concat(Gs(e.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally))).concat(Xs(e.serverSyncTree_,a,!0))}else d=!0,u="nodata",r=r.concat(Xs(e.serverSyncTree_,h.currentWriteId,!0))}ho(e.eventQueue_,n,r),r=[],d&&(t[l].status=2,a=t[l].unwatcher,setTimeout(a,Math.floor(0)),t[l].onComplete&&("nodata"===u?s.push(()=>t[l].onComplete(null,!1,t[l].currentInputSnapshot)):s.push(()=>t[l].onComplete(new Error(u),!1,null))))}var a;Qo(e,e.transactionQueueTree_);for(let i=0;i<s.length;i++)z(s[i]);Uo(e,e.transactionQueueTree_)}function Vo(e,t){let n,i=e.transactionQueueTree_;for(n=ht(t);null!==n&&void 0===Ar(i);)i=Dr(i,n),n=ht(t=ut(t));return i}function zo(e,t){const n=[];return Yo(e,t,n),n.sort((e,t)=>e.order-t.order),n}function Yo(e,t,n){const i=Ar(t);if(i)for(let s=0;s<i.length;s++)n.push(i[s]);Lr(t,t=>{Yo(e,t,n)})}function Qo(e,t){const n=Ar(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,Mr(t,n.length>0?n:void 0)}Lr(t,t=>{Qo(e,t)})}function Ko(e,t){const n=Ur(Vo(e,t)),i=Dr(e.transactionQueueTree_,t);return Wr(i,t=>{Go(e,t)}),Go(e,i),Or(i,t=>{Go(e,t)}),n}function Go(e,t){const n=Ar(t);if(n){const s=[];let r=[],o=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?((0,i.assert)(o===t-1,"All SENT items should be at beginning of queue."),o=t,n[t].status=3,n[t].abortReason="set"):((0,i.assert)(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),r=r.concat(Xs(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&s.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===o?Mr(t,void 0):n.length=o+1,ho(e.eventQueue_,Ur(t),r);for(let e=0;e<s.length;e++)z(s[e])}}function $o(e){let t="";const n=e.split("/");for(let s=0;s<n.length;s++)if(n[s].length>0){let e=n[s];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(i){}t+="/"+e}return t}function Xo(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):k(`Invalid query segment '${n}' in query '${e}'`)}return t}const Jo=function(e,t){const n=Zo(e),i=n.namespace;"firebase.com"===n.domain&&b(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||b("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&k("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new le(n.host,n.secure,i,s,t,"",i!==n.subdomain),path:new at(n.pathString)}},Zo=function(e){let t="",n="",i="",s="",r="",o=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(c,u)),c<u&&(s=$o(e.substring(c,u)));const d=Xo(e.substring(Math.min(e.length,u)));(h=t.indexOf(":"))>=0?(o="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;const _=t.slice(0,h);if("localhost"===_.toLowerCase())n="localhost";else if(_.split(".").length<=2)n=_;else{const e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),r=i}"ns"in d&&(r=d.ns)}return{host:t,port:l,domain:n,subdomain:i,secure:o,scheme:a,pathString:s,namespace:r}},ea="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ta=function(){let e=0;const t=[];return function(n){const s=n===e;let r;e=n;const o=new Array(8);for(r=7;r>=0;r--)o[r]=ea.charAt(n%64),n=Math.floor(n/64);(0,i.assert)(0===n,"Cannot push at time == 0");let a=o.join("");if(s){for(r=11;r>=0&&63===t[r];r--)t[r]=0;t[r]++}else for(r=0;r<12;r++)t[r]=Math.floor(64*Math.random());for(r=0;r<12;r++)a+=ea.charAt(t[r]);return(0,i.assert)(20===a.length,"nextPushId: Length should be 20."),a}}();class na{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+(0,i.stringify)(this.snapshot.exportVal())}}class ia{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class sa{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return(0,i.assert)(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class ra{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new i.Deferred;return xo(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){so("OnDisconnect.remove",this._path);const e=new i.Deferred;return Po(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){so("OnDisconnect.set",this._path),$r("OnDisconnect.set",e,this._path,!1);const t=new i.Deferred;return Po(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){so("OnDisconnect.setWithPriority",this._path),$r("OnDisconnect.setWithPriority",e,this._path,!1),eo("OnDisconnect.setWithPriority",t,!1);const n=new i.Deferred;return No(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){so("OnDisconnect.update",this._path),Zr("OnDisconnect.update",e,this._path,!1);const t=new i.Deferred;return Ro(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}exports.OnDisconnect=ra;class oa{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return gt(this._path)?null:dt(this._path)}get ref(){return new ca(this._repo,this._path)}get _queryIdentifier(){const e=Wn(this._queryParams),t=M(e);return"{}"===t?"default":t}get _queryObject(){return Wn(this._queryParams)}isEqual(e){if(!((e=(0,i.getModularInstance)(e))instanceof oa))return!1;const t=this._repo===e._repo,n=Ct(this._path,e._path),s=this._queryIdentifier===e._queryIdentifier;return t&&n&&s}toJSON(){return this.toString()}toString(){return this._repo.toString()+_t(this._path)}}function aa(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function la(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===Ut){const i="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",s="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==P)throw new Error(i);if("string"!=typeof t)throw new Error(s)}if(e.hasEnd()){if(e.getIndexEndName()!==N)throw new Error(i);if("string"!=typeof n)throw new Error(s)}}else if(e.getIndex()===rn){if(null!=t&&!Gr(t)||null!=n&&!Gr(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if((0,i.assert)(e.getIndex()instanceof yn||e.getIndex()===Cn,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function ha(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}exports._QueryImpl=oa;class ca extends oa{constructor(e,t){super(e,t,new Pn,!1)}get parent(){const e=ft(this._path);return null===e?null:new ca(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}exports._ReferenceImpl=ca;class ua{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new at(e),n=pa(this.ref,e);return new ua(this._node.getChild(t),n,rn)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,(t,n)=>e(new ua(n,pa(this.ref,t),rn)))}hasChild(e){const t=new at(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function da(e,t){return(e=(0,i.getModularInstance)(e))._checkNotDeleted("ref"),void 0!==t?pa(e._root,t):e._root}function _a(e,t){(e=(0,i.getModularInstance)(e))._checkNotDeleted("refFromURL");const n=Jo(t,e._repo.repoInfo_.nodeAdmin);ro("refFromURL",n);const s=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||s.host===e._repo.repoInfo_.host||b("refFromURL: Host name does not match the current database: (found "+s.host+" but expected "+e._repo.repoInfo_.host+")"),da(e,n.path.toString())}function pa(e,t){return null===ht((e=(0,i.getModularInstance)(e))._path)?io("child","path",t,!1):no("child","path",t,!1),new ca(e._repo,mt(e._path,t))}function fa(e){return e=(0,i.getModularInstance)(e),new ra(e._repo,e._path)}function ma(e,t){e=(0,i.getModularInstance)(e),so("push",e._path),$r("push",t,e._path,!0);const n=go(e._repo),s=ta(n),r=pa(e,s),o=pa(e,s);let a;return a=null!=t?ya(o,t).then(()=>o):Promise.resolve(o),r.then=a.then.bind(a),r.catch=a.then.bind(a,void 0),r}function ga(e){return so("remove",e._path),ya(e,null)}function ya(e,t){e=(0,i.getModularInstance)(e),so("set",e._path),$r("set",t,e._path,!1);const n=new i.Deferred;return ko(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function va(e,t){e=(0,i.getModularInstance)(e),so("setPriority",e._path),eo("setPriority",t,!1);const n=new i.Deferred;return ko(e._repo,mt(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}function Ca(e,t,n){if(so("setWithPriority",e._path),$r("setWithPriority",t,e._path,!1),eo("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const s=new i.Deferred;return ko(e._repo,e._path,t,n,s.wrapCallback(()=>{})),s.promise}function wa(e,t){Zr("update",t,e._path,!1);const n=new i.Deferred;return Eo(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function Ta(e){e=(0,i.getModularInstance)(e);const t=new sa(()=>{}),n=new Ia(t);return bo(e._repo,e,n).then(t=>new ua(t,new ca(e._repo,e._path),e._queryParams.getIndex()))}exports.DataSnapshot=ua;class Ia{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new na("value",this,new ua(e.snapshotNode,new ca(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ia(this,e,t):null}matches(e){return e instanceof Ia&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ba{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new ia(this,e,t):null}createEvent(e,t){(0,i.assert)(null!=e.childName,"Child events should have a childName.");const n=pa(new ca(t._repo,t._path),e.childName),s=t._queryParams.getIndex();return new na(e.type,this,new ua(e.snapshotNode,n,s),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof ba&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function ka(e,t,n,i,s){let r;if("object"==typeof i&&(r=void 0,s=i),"function"==typeof i&&(r=i),s&&s.onlyOnce){const t=n,i=(n,i)=>{Ao(e._repo,e,a),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}const o=new sa(n,r||void 0),a="value"===t?new Ia(o):new ba(t,o);return Do(e._repo,e,a),()=>Ao(e._repo,e,a)}function Ea(e,t,n,i){return ka(e,"value",t,n,i)}function Sa(e,t,n,i){return ka(e,"child_added",t,n,i)}function xa(e,t,n,i){return ka(e,"child_changed",t,n,i)}function Pa(e,t,n,i){return ka(e,"child_moved",t,n,i)}function Na(e,t,n,i){return ka(e,"child_removed",t,n,i)}function Ra(e,t,n){let i=null;const s=n?new sa(n):null;"value"===t?i=new Ia(s):t&&(i=new ba(t,s)),Ao(e._repo,e,i)}class Da{}exports.QueryConstraint=Da;class Aa extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("endAt",this._value,e._path,!0);const t=qn(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Ma(e,t){return to("endAt","key",t,!0),new Aa(e,t)}class qa extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("endBefore",this._value,e._path,!1);const t=Fn(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Fa(e,t){return to("endBefore","key",t,!0),new qa(e,t)}class La extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("startAt",this._value,e._path,!0);const t=An(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Oa(e=null,t){return to("startAt","key",t,!0),new La(e,t)}class Wa extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){$r("startAfter",this._value,e._path,!1);const t=Mn(e._queryParams,this._value,this._key);if(ha(t),la(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new oa(e._repo,e._path,t,e._orderByCalled)}}function Ua(e,t){return to("startAfter","key",t,!0),new Wa(e,t)}class Ba extends Da{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new oa(e._repo,e._path,Rn(e._queryParams,this._limit),e._orderByCalled)}}function ja(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Ba(e)}class Ha extends Da{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new oa(e._repo,e._path,Dn(e._queryParams,this._limit),e._orderByCalled)}}function Va(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Ha(e)}class za extends Da{constructor(e){super(),this._path=e}_apply(e){aa(e,"orderByChild");const t=new at(this._path);if(gt(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new yn(t),i=Ln(e._queryParams,n);return la(i),new oa(e._repo,e._path,i,!0)}}function Ya(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return no("orderByChild","path",e,!1),new za(e)}class Qa extends Da{_apply(e){aa(e,"orderByKey");const t=Ln(e._queryParams,Ut);return la(t),new oa(e._repo,e._path,t,!0)}}function Ka(){return new Qa}class Ga extends Da{_apply(e){aa(e,"orderByPriority");const t=Ln(e._queryParams,rn);return la(t),new oa(e._repo,e._path,t,!0)}}function $a(){return new Ga}class Xa extends Da{_apply(e){aa(e,"orderByValue");const t=Ln(e._queryParams,Cn);return la(t),new oa(e._repo,e._path,t,!0)}}function Ja(){return new Xa}class Za extends Da{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if($r("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new Aa(this._value,this._key)._apply(new La(this._value,this._key)._apply(e))}}function el(e,t){return to("equalTo","key",t,!0),new Za(e,t)}function tl(e,...t){let n=(0,i.getModularInstance)(e);for(const i of t)n=i._apply(n);return n}Ds(ca),zs(ca);const nl="FIREBASE_DATABASE_EMULATOR_HOST",il={};let sl=!1;function rl(e,t,n,i){e.repoInfo_=new le(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),i&&(e.authTokenProvider_=i)}function ol(t,n,i,s,r){let o=s||t.options.databaseURL;void 0===o&&(t.options.projectId||b("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),w("Using default host for project ",t.options.projectId),o=`${t.options.projectId}-default-rtdb.firebaseio.com`);let a,l=Jo(o,r),h=l.repoInfo,c=void 0;void 0!==e&&e.env&&(c=e.env[nl]),c?(a=!0,o=`http://${c}?ns=${h.namespace}`,h=(l=Jo(o,r)).repoInfo):a=!l.repoInfo.secure;const u=r&&a?new $($.OWNER):new G(t.name,t.options,n);ro("Invalid Firebase Database URL",l),gt(l.path)||b("Database URL must point to the root of a Firebase Database (not including a child path).");const d=ll(h,t,u,new K(t.name,i));return new cl(d,t)}function al(e,t){const n=il[t];n&&n[e.key]===e||b(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Mo(e),delete n[e.key]}function ll(e,t,n,i){let s=il[t.name];s||(s={},il[t.name]=s);let r=s[e.toURLString()];return r&&b("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new fo(e,sl,n,i),s[e.toURLString()]=r,r}function hl(e){sl=e}class cl{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(mo(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ca(this._repo,lt())),this._rootInternal}_delete(){return null!==this._rootInternal&&(al(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&b("Cannot call "+e+" on a deleted database.")}}function ul(){Ue.IS_TRANSPORT_INITIALIZED&&k("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function dl(){ul(),Me.forceDisallow()}function _l(){ul(),We.forceDisallow(),Me.forceAllow()}function pl(e=(0,t.getApp)(),n){const s=(0,t._getProvider)(e,"database").getImmediate({identifier:n});if(!s._instanceStarted){const e=(0,i.getDefaultEmulatorHostnameAndPort)("database");e&&fl(s,...e)}return s}function fl(e,t,n,s={}){(e=(0,i.getModularInstance)(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&b("Cannot call useEmulator() after instance has already been initialized.");const r=e._repoInternal;let o=void 0;if(r.repoInfo_.nodeAdmin)s.mockUserToken&&b('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new $($.OWNER);else if(s.mockUserToken){const t="string"==typeof s.mockUserToken?s.mockUserToken:(0,i.createMockUserToken)(s.mockUserToken,e.app.options.projectId);o=new $(t)}rl(r,t,n,o)}function ml(e){(e=(0,i.getModularInstance)(e))._checkNotDeleted("goOffline"),Mo(e._repo)}function gl(e){(e=(0,i.getModularInstance)(e))._checkNotDeleted("goOnline"),qo(e._repo)}function yl(e,t){C(e,t)}function vl(e){l(t.SDK_VERSION),(0,t._registerComponent)(new n.Component("database",(e,{instanceIdentifier:t})=>{return ol(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),(0,t.registerVersion)(r,o,e),(0,t.registerVersion)(r,o,"esm2017")}exports.Database=cl;const Cl={".sv":"timestamp"};function wl(){return Cl}function Tl(e){return{".sv":{increment:e}}}class Il{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function bl(e,t,n){var s;if(e=(0,i.getModularInstance)(e),so("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const r=null===(s=null==n?void 0:n.applyLocally)||void 0===s||s,o=new i.Deferred,a=Ea(e,()=>{});return Oo(e._repo,e._path,t,(t,n,i)=>{let s=null;t?o.reject(t):(s=new ua(i,new ca(e._repo,e._path),rn),o.resolve(new Il(n,s)))},a,r),o.promise}exports.TransactionResult=Il,qt.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},qt.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};const kl=function(e){const t=qt.prototype.put;return qt.prototype.put=function(n,i,s,r){void 0!==r&&(r=e()),t.call(this,n,i,s,r)},function(){qt.prototype.put=t}};exports._TEST_ACCESS_hijackHash=kl;const El=function(e){hl(e)};exports._TEST_ACCESS_forceRestClient=El,vl();
|
|
482
482
|
},{"@firebase/app":"h2Mb","@firebase/component":"vhY9","@firebase/util":"chA2","@firebase/logger":"JJem","process":"pBGv"}],"sWIc":[function(require,module,exports) {
|
|
483
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerDatabase=m;var e=l(require("@firebase/app-compat")),t=require("@firebase/component"),a=require("@firebase/database"),n=require("@firebase/util"),r=require("@firebase/logger");function l(e){return e&&e.__esModule?e:{default:e}}const i="@firebase/database-compat",o="0.3.3",s=new r.Logger("@firebase/database-compat"),d=function(e){const t="FIREBASE WARNING: "+e;s.warn(t)},c=function(e,t,a,r){if((!r||void 0!==a)&&"boolean"!=typeof a)throw new Error((0,n.errorPrefix)(e,t)+"must be a boolean.")},h=function(e,t,a){if(!a||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error((0,n.errorPrefix)(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}};class u{constructor(e){this._delegate=e}cancel(e){(0,n.validateArgCount)("OnDisconnect.cancel",0,1,arguments.length),(0,n.validateCallback)("OnDisconnect.cancel","onComplete",e,!0);const t=this._delegate.cancel();return e&&t.then(()=>e(null),t=>e(t)),t}remove(e){(0,n.validateArgCount)("OnDisconnect.remove",0,1,arguments.length),(0,n.validateCallback)("OnDisconnect.remove","onComplete",e,!0);const t=this._delegate.remove();return e&&t.then(()=>e(null),t=>e(t)),t}set(e,t){(0,n.validateArgCount)("OnDisconnect.set",1,2,arguments.length),(0,n.validateCallback)("OnDisconnect.set","onComplete",t,!0);const a=this._delegate.set(e);return t&&a.then(()=>t(null),e=>t(e)),a}setWithPriority(e,t,a){(0,n.validateArgCount)("OnDisconnect.setWithPriority",2,3,arguments.length),(0,n.validateCallback)("OnDisconnect.setWithPriority","onComplete",a,!0);const r=this._delegate.setWithPriority(e,t);return a&&r.then(()=>a(null),e=>a(e)),r}update(e,t){if((0,n.validateArgCount)("OnDisconnect.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let a=0;a<e.length;++a)t[""+a]=e[a];e=t,d("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}(0,n.validateCallback)("OnDisconnect.update","onComplete",t,!0);const a=this._delegate.update(e);return t&&a.then(()=>t(null),e=>t(e)),a}}class g{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return(0,n.validateArgCount)("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class v{constructor(e,t){this._database=e,this._delegate=t}val(){return(0,n.validateArgCount)("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return(0,n.validateArgCount)("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return(0,n.validateArgCount)("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return(0,n.validateArgCount)("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return(0,n.validateArgCount)("DataSnapshot.child",0,1,arguments.length),e=String(e),(0,a._validatePathString)("DataSnapshot.child","path",e,!1),new v(this._database,this._delegate.child(e))}hasChild(e){return(0,n.validateArgCount)("DataSnapshot.hasChild",1,1,arguments.length),(0,a._validatePathString)("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return(0,n.validateArgCount)("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(e){return(0,n.validateArgCount)("DataSnapshot.forEach",1,1,arguments.length),(0,n.validateCallback)("DataSnapshot.forEach","action",e,!1),this._delegate.forEach(t=>e(new v(this._database,t)))}hasChildren(){return(0,n.validateArgCount)("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return(0,n.validateArgCount)("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return(0,n.validateArgCount)("DataSnapshot.ref",0,0,arguments.length),new f(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class _{constructor(e,t){this.database=e,this._delegate=t}on(e,t,r,l){var i;(0,n.validateArgCount)("Query.on",2,4,arguments.length),(0,n.validateCallback)("Query.on","callback",t,!1);const o=_.getCancelAndContextArgs_("Query.on",r,l),s=(e,a)=>{t.call(o.context,new v(this.database,e),a)};s.userCallback=t,s.context=o.context;const d=null===(i=o.cancel)||void 0===i?void 0:i.bind(o.context);switch(e){case"value":return(0,a.onValue)(this._delegate,s,d),t;case"child_added":return(0,a.onChildAdded)(this._delegate,s,d),t;case"child_removed":return(0,a.onChildRemoved)(this._delegate,s,d),t;case"child_changed":return(0,a.onChildChanged)(this._delegate,s,d),t;case"child_moved":return(0,a.onChildMoved)(this._delegate,s,d),t;default:throw new Error((0,n.errorPrefix)("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,r){if((0,n.validateArgCount)("Query.off",0,3,arguments.length),h("Query.off",e,!0),(0,n.validateCallback)("Query.off","callback",t,!0),(0,n.validateContextObject)("Query.off","context",r,!0),t){const n=()=>{};n.userCallback=t,n.context=r,(0,a.off)(this._delegate,e,n)}else(0,a.off)(this._delegate,e)}get(){return(0,a.get)(this._delegate).then(e=>new v(this.database,e))}once(e,t,r,l){(0,n.validateArgCount)("Query.once",1,4,arguments.length),(0,n.validateCallback)("Query.once","callback",t,!0);const i=_.getCancelAndContextArgs_("Query.once",r,l),o=new n.Deferred,s=(e,a)=>{const n=new v(this.database,e);t&&t.call(i.context,n,a),o.resolve(n)};s.userCallback=t,s.context=i.context;const d=e=>{i.cancel&&i.cancel.call(i.context,e),o.reject(e)};switch(e){case"value":(0,a.onValue)(this._delegate,s,d,{onlyOnce:!0});break;case"child_added":(0,a.onChildAdded)(this._delegate,s,d,{onlyOnce:!0});break;case"child_removed":(0,a.onChildRemoved)(this._delegate,s,d,{onlyOnce:!0});break;case"child_changed":(0,a.onChildChanged)(this._delegate,s,d,{onlyOnce:!0});break;case"child_moved":(0,a.onChildMoved)(this._delegate,s,d,{onlyOnce:!0});break;default:throw new Error((0,n.errorPrefix)("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return o.promise}limitToFirst(e){return(0,n.validateArgCount)("Query.limitToFirst",1,1,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.limitToFirst)(e)))}limitToLast(e){return(0,n.validateArgCount)("Query.limitToLast",1,1,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.limitToLast)(e)))}orderByChild(e){return(0,n.validateArgCount)("Query.orderByChild",1,1,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByChild)(e)))}orderByKey(){return(0,n.validateArgCount)("Query.orderByKey",0,0,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByKey)()))}orderByPriority(){return(0,n.validateArgCount)("Query.orderByPriority",0,0,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByPriority)()))}orderByValue(){return(0,n.validateArgCount)("Query.orderByValue",0,0,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByValue)()))}startAt(e=null,t){return(0,n.validateArgCount)("Query.startAt",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.startAt)(e,t)))}startAfter(e=null,t){return(0,n.validateArgCount)("Query.startAfter",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.startAfter)(e,t)))}endAt(e=null,t){return(0,n.validateArgCount)("Query.endAt",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.endAt)(e,t)))}endBefore(e=null,t){return(0,n.validateArgCount)("Query.endBefore",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.endBefore)(e,t)))}equalTo(e,t){return(0,n.validateArgCount)("Query.equalTo",1,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.equalTo)(e,t)))}toString(){return(0,n.validateArgCount)("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return(0,n.validateArgCount)("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if((0,n.validateArgCount)("Query.isEqual",1,1,arguments.length),!(e instanceof _)){throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,a){const r={cancel:void 0,context:void 0};if(t&&a)r.cancel=t,(0,n.validateCallback)(e,"cancel",r.cancel,!0),r.context=a,(0,n.validateContextObject)(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error((0,n.errorPrefix)(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new f(this.database,new a._ReferenceImpl(this._delegate._repo,this._delegate._path))}}class f extends _{constructor(e,t){super(e,new a._QueryImpl(t._repo,t._path,new a._QueryParams,!1)),this.database=e,this._delegate=t}getKey(){return(0,n.validateArgCount)("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return(0,n.validateArgCount)("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new f(this.database,(0,a.child)(this._delegate,e))}getParent(){(0,n.validateArgCount)("Reference.parent",0,0,arguments.length);const e=this._delegate.parent;return e?new f(this.database,e):null}getRoot(){return(0,n.validateArgCount)("Reference.root",0,0,arguments.length),new f(this.database,this._delegate.root)}set(e,t){(0,n.validateArgCount)("Reference.set",1,2,arguments.length),(0,n.validateCallback)("Reference.set","onComplete",t,!0);const r=(0,a.set)(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}update(e,t){if((0,n.validateArgCount)("Reference.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let a=0;a<e.length;++a)t[""+a]=e[a];e=t,d("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}(0,a._validateWritablePath)("Reference.update",this._delegate._path),(0,n.validateCallback)("Reference.update","onComplete",t,!0);const r=(0,a.update)(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}setWithPriority(e,t,r){(0,n.validateArgCount)("Reference.setWithPriority",2,3,arguments.length),(0,n.validateCallback)("Reference.setWithPriority","onComplete",r,!0);const l=(0,a.setWithPriority)(this._delegate,e,t);return r&&l.then(()=>r(null),e=>r(e)),l}remove(e){(0,n.validateArgCount)("Reference.remove",0,1,arguments.length),(0,n.validateCallback)("Reference.remove","onComplete",e,!0);const t=(0,a.remove)(this._delegate);return e&&t.then(()=>e(null),t=>e(t)),t}transaction(e,t,r){(0,n.validateArgCount)("Reference.transaction",1,3,arguments.length),(0,n.validateCallback)("Reference.transaction","transactionUpdate",e,!1),(0,n.validateCallback)("Reference.transaction","onComplete",t,!0),c("Reference.transaction","applyLocally",r,!0);const l=(0,a.runTransaction)(this._delegate,e,{applyLocally:r}).then(e=>new g(e.committed,new v(this.database,e.snapshot)));return t&&l.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),l}setPriority(e,t){(0,n.validateArgCount)("Reference.setPriority",1,2,arguments.length),(0,n.validateCallback)("Reference.setPriority","onComplete",t,!0);const r=(0,a.setPriority)(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}push(e,t){(0,n.validateArgCount)("Reference.push",0,2,arguments.length),(0,n.validateCallback)("Reference.push","onComplete",t,!0);const r=(0,a.push)(this._delegate,e),l=r.then(e=>new f(this.database,e));t&&l.then(()=>t(null),e=>t(e));const i=new f(this.database,r);return i.then=l.then.bind(l),i.catch=l.catch.bind(l,void 0),i}onDisconnect(){return(0,a._validateWritablePath)("Reference.onDisconnect",this._delegate._path),new u(new a.OnDisconnect(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class C{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:a.forceWebSockets,forceLongPolling:a.forceLongPolling}}useEmulator(e,t,n={}){(0,a.connectDatabaseEmulator)(this._delegate,e,t,n)}ref(e){if((0,n.validateArgCount)("database.ref",0,1,arguments.length),e instanceof f){const t=(0,a.refFromURL)(this._delegate,e.toString());return new f(this,t)}{const t=(0,a.ref)(this._delegate,e);return new f(this,t)}}refFromURL(e){(0,n.validateArgCount)("database.refFromURL",1,1,arguments.length);const t=(0,a.refFromURL)(this._delegate,e);return new f(this,t)}goOffline(){return(0,n.validateArgCount)("database.goOffline",0,0,arguments.length),(0,a.goOffline)(this._delegate)}goOnline(){return(0,n.validateArgCount)("database.goOnline",0,0,arguments.length),(0,a.goOnline)(this._delegate)}}function p({app:e,url:n,version:r,customAuthImpl:l,namespace:i,nodeAdmin:o=!1}){(0,a._setSDKVersion)(r);const s=new t.Provider("auth-internal",new t.ComponentContainer("database-standalone"));return s.setComponent(new t.Component("auth-internal",()=>l,"PRIVATE")),{instance:new C((0,a._repoManagerDatabaseFromApp)(e,s,void 0,n,o),e),namespace:i}}C.ServerValue={TIMESTAMP:(0,a.serverTimestamp)(),increment:e=>(0,a.increment)(e)};var y=Object.freeze({__proto__:null,initStandalone:p});const b=C.ServerValue;function m(e){e.INTERNAL.registerComponent(new t.Component("database-compat",(e,{instanceIdentifier:t})=>{const a=e.getProvider("app-compat").getImmediate(),n=e.getProvider("database").getImmediate({identifier:t});return new C(n,a)},"PUBLIC").setServiceProps({Reference:f,Query:_,Database:C,DataSnapshot:v,enableLogging:a.enableLogging,INTERNAL:y,ServerValue:b}).setMultipleInstances(!0)),e.registerVersion(i,o)}m(e.default);
|
|
483
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerDatabase=m;var e=l(require("@firebase/app-compat")),t=require("@firebase/component"),a=require("@firebase/database"),n=require("@firebase/util"),r=require("@firebase/logger");function l(e){return e&&e.__esModule?e:{default:e}}const i="@firebase/database-compat",o="0.3.4",s=new r.Logger("@firebase/database-compat"),d=function(e){const t="FIREBASE WARNING: "+e;s.warn(t)},c=function(e,t,a,r){if((!r||void 0!==a)&&"boolean"!=typeof a)throw new Error((0,n.errorPrefix)(e,t)+"must be a boolean.")},h=function(e,t,a){if(!a||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error((0,n.errorPrefix)(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}};class u{constructor(e){this._delegate=e}cancel(e){(0,n.validateArgCount)("OnDisconnect.cancel",0,1,arguments.length),(0,n.validateCallback)("OnDisconnect.cancel","onComplete",e,!0);const t=this._delegate.cancel();return e&&t.then(()=>e(null),t=>e(t)),t}remove(e){(0,n.validateArgCount)("OnDisconnect.remove",0,1,arguments.length),(0,n.validateCallback)("OnDisconnect.remove","onComplete",e,!0);const t=this._delegate.remove();return e&&t.then(()=>e(null),t=>e(t)),t}set(e,t){(0,n.validateArgCount)("OnDisconnect.set",1,2,arguments.length),(0,n.validateCallback)("OnDisconnect.set","onComplete",t,!0);const a=this._delegate.set(e);return t&&a.then(()=>t(null),e=>t(e)),a}setWithPriority(e,t,a){(0,n.validateArgCount)("OnDisconnect.setWithPriority",2,3,arguments.length),(0,n.validateCallback)("OnDisconnect.setWithPriority","onComplete",a,!0);const r=this._delegate.setWithPriority(e,t);return a&&r.then(()=>a(null),e=>a(e)),r}update(e,t){if((0,n.validateArgCount)("OnDisconnect.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let a=0;a<e.length;++a)t[""+a]=e[a];e=t,d("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}(0,n.validateCallback)("OnDisconnect.update","onComplete",t,!0);const a=this._delegate.update(e);return t&&a.then(()=>t(null),e=>t(e)),a}}class g{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return(0,n.validateArgCount)("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class v{constructor(e,t){this._database=e,this._delegate=t}val(){return(0,n.validateArgCount)("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return(0,n.validateArgCount)("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return(0,n.validateArgCount)("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return(0,n.validateArgCount)("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return(0,n.validateArgCount)("DataSnapshot.child",0,1,arguments.length),e=String(e),(0,a._validatePathString)("DataSnapshot.child","path",e,!1),new v(this._database,this._delegate.child(e))}hasChild(e){return(0,n.validateArgCount)("DataSnapshot.hasChild",1,1,arguments.length),(0,a._validatePathString)("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return(0,n.validateArgCount)("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(e){return(0,n.validateArgCount)("DataSnapshot.forEach",1,1,arguments.length),(0,n.validateCallback)("DataSnapshot.forEach","action",e,!1),this._delegate.forEach(t=>e(new v(this._database,t)))}hasChildren(){return(0,n.validateArgCount)("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return(0,n.validateArgCount)("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return(0,n.validateArgCount)("DataSnapshot.ref",0,0,arguments.length),new f(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class _{constructor(e,t){this.database=e,this._delegate=t}on(e,t,r,l){var i;(0,n.validateArgCount)("Query.on",2,4,arguments.length),(0,n.validateCallback)("Query.on","callback",t,!1);const o=_.getCancelAndContextArgs_("Query.on",r,l),s=(e,a)=>{t.call(o.context,new v(this.database,e),a)};s.userCallback=t,s.context=o.context;const d=null===(i=o.cancel)||void 0===i?void 0:i.bind(o.context);switch(e){case"value":return(0,a.onValue)(this._delegate,s,d),t;case"child_added":return(0,a.onChildAdded)(this._delegate,s,d),t;case"child_removed":return(0,a.onChildRemoved)(this._delegate,s,d),t;case"child_changed":return(0,a.onChildChanged)(this._delegate,s,d),t;case"child_moved":return(0,a.onChildMoved)(this._delegate,s,d),t;default:throw new Error((0,n.errorPrefix)("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,r){if((0,n.validateArgCount)("Query.off",0,3,arguments.length),h("Query.off",e,!0),(0,n.validateCallback)("Query.off","callback",t,!0),(0,n.validateContextObject)("Query.off","context",r,!0),t){const n=()=>{};n.userCallback=t,n.context=r,(0,a.off)(this._delegate,e,n)}else(0,a.off)(this._delegate,e)}get(){return(0,a.get)(this._delegate).then(e=>new v(this.database,e))}once(e,t,r,l){(0,n.validateArgCount)("Query.once",1,4,arguments.length),(0,n.validateCallback)("Query.once","callback",t,!0);const i=_.getCancelAndContextArgs_("Query.once",r,l),o=new n.Deferred,s=(e,a)=>{const n=new v(this.database,e);t&&t.call(i.context,n,a),o.resolve(n)};s.userCallback=t,s.context=i.context;const d=e=>{i.cancel&&i.cancel.call(i.context,e),o.reject(e)};switch(e){case"value":(0,a.onValue)(this._delegate,s,d,{onlyOnce:!0});break;case"child_added":(0,a.onChildAdded)(this._delegate,s,d,{onlyOnce:!0});break;case"child_removed":(0,a.onChildRemoved)(this._delegate,s,d,{onlyOnce:!0});break;case"child_changed":(0,a.onChildChanged)(this._delegate,s,d,{onlyOnce:!0});break;case"child_moved":(0,a.onChildMoved)(this._delegate,s,d,{onlyOnce:!0});break;default:throw new Error((0,n.errorPrefix)("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return o.promise}limitToFirst(e){return(0,n.validateArgCount)("Query.limitToFirst",1,1,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.limitToFirst)(e)))}limitToLast(e){return(0,n.validateArgCount)("Query.limitToLast",1,1,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.limitToLast)(e)))}orderByChild(e){return(0,n.validateArgCount)("Query.orderByChild",1,1,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByChild)(e)))}orderByKey(){return(0,n.validateArgCount)("Query.orderByKey",0,0,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByKey)()))}orderByPriority(){return(0,n.validateArgCount)("Query.orderByPriority",0,0,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByPriority)()))}orderByValue(){return(0,n.validateArgCount)("Query.orderByValue",0,0,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.orderByValue)()))}startAt(e=null,t){return(0,n.validateArgCount)("Query.startAt",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.startAt)(e,t)))}startAfter(e=null,t){return(0,n.validateArgCount)("Query.startAfter",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.startAfter)(e,t)))}endAt(e=null,t){return(0,n.validateArgCount)("Query.endAt",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.endAt)(e,t)))}endBefore(e=null,t){return(0,n.validateArgCount)("Query.endBefore",0,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.endBefore)(e,t)))}equalTo(e,t){return(0,n.validateArgCount)("Query.equalTo",1,2,arguments.length),new _(this.database,(0,a.query)(this._delegate,(0,a.equalTo)(e,t)))}toString(){return(0,n.validateArgCount)("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return(0,n.validateArgCount)("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if((0,n.validateArgCount)("Query.isEqual",1,1,arguments.length),!(e instanceof _)){throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,a){const r={cancel:void 0,context:void 0};if(t&&a)r.cancel=t,(0,n.validateCallback)(e,"cancel",r.cancel,!0),r.context=a,(0,n.validateContextObject)(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error((0,n.errorPrefix)(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new f(this.database,new a._ReferenceImpl(this._delegate._repo,this._delegate._path))}}class f extends _{constructor(e,t){super(e,new a._QueryImpl(t._repo,t._path,new a._QueryParams,!1)),this.database=e,this._delegate=t}getKey(){return(0,n.validateArgCount)("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return(0,n.validateArgCount)("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new f(this.database,(0,a.child)(this._delegate,e))}getParent(){(0,n.validateArgCount)("Reference.parent",0,0,arguments.length);const e=this._delegate.parent;return e?new f(this.database,e):null}getRoot(){return(0,n.validateArgCount)("Reference.root",0,0,arguments.length),new f(this.database,this._delegate.root)}set(e,t){(0,n.validateArgCount)("Reference.set",1,2,arguments.length),(0,n.validateCallback)("Reference.set","onComplete",t,!0);const r=(0,a.set)(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}update(e,t){if((0,n.validateArgCount)("Reference.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let a=0;a<e.length;++a)t[""+a]=e[a];e=t,d("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}(0,a._validateWritablePath)("Reference.update",this._delegate._path),(0,n.validateCallback)("Reference.update","onComplete",t,!0);const r=(0,a.update)(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}setWithPriority(e,t,r){(0,n.validateArgCount)("Reference.setWithPriority",2,3,arguments.length),(0,n.validateCallback)("Reference.setWithPriority","onComplete",r,!0);const l=(0,a.setWithPriority)(this._delegate,e,t);return r&&l.then(()=>r(null),e=>r(e)),l}remove(e){(0,n.validateArgCount)("Reference.remove",0,1,arguments.length),(0,n.validateCallback)("Reference.remove","onComplete",e,!0);const t=(0,a.remove)(this._delegate);return e&&t.then(()=>e(null),t=>e(t)),t}transaction(e,t,r){(0,n.validateArgCount)("Reference.transaction",1,3,arguments.length),(0,n.validateCallback)("Reference.transaction","transactionUpdate",e,!1),(0,n.validateCallback)("Reference.transaction","onComplete",t,!0),c("Reference.transaction","applyLocally",r,!0);const l=(0,a.runTransaction)(this._delegate,e,{applyLocally:r}).then(e=>new g(e.committed,new v(this.database,e.snapshot)));return t&&l.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),l}setPriority(e,t){(0,n.validateArgCount)("Reference.setPriority",1,2,arguments.length),(0,n.validateCallback)("Reference.setPriority","onComplete",t,!0);const r=(0,a.setPriority)(this._delegate,e);return t&&r.then(()=>t(null),e=>t(e)),r}push(e,t){(0,n.validateArgCount)("Reference.push",0,2,arguments.length),(0,n.validateCallback)("Reference.push","onComplete",t,!0);const r=(0,a.push)(this._delegate,e),l=r.then(e=>new f(this.database,e));t&&l.then(()=>t(null),e=>t(e));const i=new f(this.database,r);return i.then=l.then.bind(l),i.catch=l.catch.bind(l,void 0),i}onDisconnect(){return(0,a._validateWritablePath)("Reference.onDisconnect",this._delegate._path),new u(new a.OnDisconnect(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class C{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:a.forceWebSockets,forceLongPolling:a.forceLongPolling}}useEmulator(e,t,n={}){(0,a.connectDatabaseEmulator)(this._delegate,e,t,n)}ref(e){if((0,n.validateArgCount)("database.ref",0,1,arguments.length),e instanceof f){const t=(0,a.refFromURL)(this._delegate,e.toString());return new f(this,t)}{const t=(0,a.ref)(this._delegate,e);return new f(this,t)}}refFromURL(e){(0,n.validateArgCount)("database.refFromURL",1,1,arguments.length);const t=(0,a.refFromURL)(this._delegate,e);return new f(this,t)}goOffline(){return(0,n.validateArgCount)("database.goOffline",0,0,arguments.length),(0,a.goOffline)(this._delegate)}goOnline(){return(0,n.validateArgCount)("database.goOnline",0,0,arguments.length),(0,a.goOnline)(this._delegate)}}function p({app:e,url:n,version:r,customAuthImpl:l,namespace:i,nodeAdmin:o=!1}){(0,a._setSDKVersion)(r);const s=new t.Provider("auth-internal",new t.ComponentContainer("database-standalone"));return s.setComponent(new t.Component("auth-internal",()=>l,"PRIVATE")),{instance:new C((0,a._repoManagerDatabaseFromApp)(e,s,void 0,n,o),e),namespace:i}}C.ServerValue={TIMESTAMP:(0,a.serverTimestamp)(),increment:e=>(0,a.increment)(e)};var y=Object.freeze({__proto__:null,initStandalone:p});const b=C.ServerValue;function m(e){e.INTERNAL.registerComponent(new t.Component("database-compat",(e,{instanceIdentifier:t})=>{const a=e.getProvider("app-compat").getImmediate(),n=e.getProvider("database").getImmediate({identifier:t});return new C(n,a)},"PUBLIC").setServiceProps({Reference:f,Query:_,Database:C,DataSnapshot:v,enableLogging:a.enableLogging,INTERNAL:y,ServerValue:b}).setMultipleInstances(!0)),e.registerVersion(i,o)}m(e.default);
|
|
484
484
|
},{"@firebase/app-compat":"CMFQ","@firebase/component":"vhY9","@firebase/database":"Q6BU","@firebase/util":"chA2","@firebase/logger":"JJem"}],"h3PO":[function(require,module,exports) {
|
|
485
485
|
"use strict";require("@firebase/database-compat");
|
|
486
|
-
},{"@firebase/database-compat":"sWIc"}],"
|
|
487
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.$=Ht,exports.D=exports.C=exports.B=exports.A=void 0,exports.E=b,exports.F=void 0,exports.G=Ue,exports.W=exports.V=exports.U=exports.T=exports.S=exports.R=exports.Q=exports.P=exports.O=exports.N=exports.M=exports.L=exports.K=exports.J=exports.I=exports.H=void 0,exports.X=St,exports.Y=Ft,exports.Z=Vt,exports._=qt,exports.a=void 0,exports.a0=Kt,exports.a1=Bt,exports.a2=Jt,exports.a3=$t,exports.a4=Yt,exports.a5=Xt,exports.a6=Qt,exports.a7=Zt,exports.a8=en,exports.a9=tn,exports.aA=ge,exports.aB=_r,exports.aC=ur,exports.aD=cr,exports.aE=Me,exports.aG=exports.aF=void 0,exports.aH=De,exports.aI=Jn,exports.aL=exports.aK=exports.aJ=void 0,exports.aa=rn,exports.ab=sn,exports.ac=on,exports.ad=void 0,exports.ae=pt,exports.af=cn,exports.ag=un,exports.ah=dn,exports.ai=X,exports.aj=Q,exports.ak=Ct,exports.al=_n,exports.am=ae,exports.an=On,exports.ao=xn,exports.ap=A,exports.aq=Re,exports.ar=Ee,exports.as=I,exports.at=Zr,exports.au=Rr,exports.av=Ne,exports.aw=_,exports.ax=E,exports.ay=void 0,exports.az=N,exports.b=void 0,exports.c=Zi,exports.d=tr,exports.e=er,exports.f=hr,exports.g=gr,exports.h=mr,exports.i=void 0,exports.j=Ir,exports.k=void 0,exports.l=ji,exports.m=void 0,exports.n=gs,exports.o=void 0,exports.p=yn,exports.q=Tn,exports.r=Hi,exports.s=qi,exports.t=wn,exports.u=Gi,exports.v=En,exports.w=kn,exports.x=An,exports.y=Rn,exports.z=Nn;var e=require("@firebase/util"),t=require("@firebase/app"),n=require("@firebase/logger"),i=require("tslib"),r=require("@firebase/component");const s={PHONE:"phone"};exports.F=s;const o={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"};exports.o=o;const a={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password",FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PHONE:"phone",TWITTER:"twitter.com"};exports.S=a;const c={LINK:"link",REAUTHENTICATE:"reauthenticate",SIGN_IN:"signIn"};exports.O=c;const u={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function d(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance."}}function l(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}exports.A=u;const h=d;exports.B=h;const p=l;exports.C=p;const m=new e.ErrorFactory("auth","Firebase",l()),f={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized"};exports.D=f;const g=new n.Logger("@firebase/auth");function v(e,...i){g.logLevel<=n.LogLevel.ERROR&&g.error(`Auth (${t.SDK_VERSION}): ${e}`,...i)}function I(e,...t){throw w(e,...t)}function _(e,...t){return w(e,...t)}function y(t,n,i){const r=Object.assign(Object.assign({},p()),{[n]:i});return new e.ErrorFactory("auth","Firebase",r).create(n,{appName:t.name})}function T(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&I(e,"argument-error"),y(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function w(e,...t){if("string"!=typeof e){const n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return m.create(e,...t)}function E(e,t,...n){if(!e)throw w(t,...n)}function k(e){const t="INTERNAL ASSERTION FAILED: "+e;throw v(t),new Error(t)}function A(e,t){e||k(t)}const R=new Map;function N(e){A(e instanceof Function,"Expected a class definition");let t=R.get(e);return t?(A(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,R.set(e,t),t)}function b(n,i){const r=(0,t._getProvider)(n,"auth");if(r.isInitialized()){const t=r.getImmediate(),n=r.getOptions();if((0,e.deepEqual)(n,null!=i?i:{}))return t;I(t,"already-initialized")}return r.initialize({options:i})}function S(e,t){const n=(null==t?void 0:t.persistence)||[],i=(Array.isArray(n)?n:[n]).map(N);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(i,null==t?void 0:t.popupRedirectResolver)}function O(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function P(){return"http:"===D()||"https:"===D()}function D(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}function C(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(P()||(0,e.isBrowserExtension)()||"connection"in navigator))||navigator.onLine}function L(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}class M{constructor(t,n){this.shortDelay=t,this.longDelay=n,A(n>t,"Short delay should be less than long delay!"),this.isMobile=(0,e.isMobileCordova)()||(0,e.isReactNative)()}get(){return C()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function x(e,t){A(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class U{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 k("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 k("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 k("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}exports.aK=U;const F={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"},V=new M(3e4,6e4);function q(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function j(t,n,i,r,s={}){return H(t,s,async()=>{let s={},o={};r&&("GET"===n?o=r:s={body:JSON.stringify(r)});const a=(0,e.querystring)(Object.assign({key:t.config.apiKey},o)).slice(1),c=await t._getAdditionalHeaders();return c["Content-Type"]="application/json",t.languageCode&&(c["X-Firebase-Locale"]=t.languageCode),U.fetch()(G(t,t.config.apiHost,i,a),Object.assign({method:n,headers:c,referrerPolicy:"no-referrer"},s))})}async function H(t,n,i){t._canInitEmulator=!1;const r=Object.assign(Object.assign({},F),n);try{const n=new W(t),o=await Promise.race([i(),n.promise]);n.clearNetworkTimeout();const a=await o.json();if("needConfirmation"in a)throw K(t,"account-exists-with-different-credential",a);if(o.ok&&!("errorMessage"in a))return a;{const e=o.ok?a.errorMessage:a.error.message,[n,i]=e.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw K(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===n)throw K(t,"email-already-in-use",a);if("USER_DISABLED"===n)throw K(t,"user-disabled",a);const s=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(i)throw y(t,s,i);I(t,s)}}catch(s){if(s instanceof e.FirebaseError)throw s;I(t,"network-request-failed")}}async function z(e,t,n,i,r={}){const s=await j(e,t,n,i,r);return"mfaPendingCredential"in s&&I(e,"multi-factor-auth-required",{_serverResponse:s}),s}function G(e,t,n,i){const r=`${t}${n}?${i}`;return e.config.emulator?x(e.config,r):`${e.config.apiScheme}://${r}`}class W{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(_(this.auth,"network-request-failed")),V.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function K(e,t,n){const i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);const r=_(e,t,i);return r.customData._tokenResponse=n,r}async function B(e,t){return j(e,"POST","/v1/accounts:delete",t)}async function J(e,t){return j(e,"POST","/v1/accounts:update",t)}async function $(e,t){return j(e,"POST","/v1/accounts:lookup",t)}function Y(e){if(e)try{const n=new Date(Number(e));if(!isNaN(n.getTime()))return n.toUTCString()}catch(t){}}function X(t,n=!1){return(0,e.getModularInstance)(t).getIdToken(n)}async function Q(t,n=!1){const i=(0,e.getModularInstance)(t),r=await i.getIdToken(n),s=ee(r);E(s&&s.exp&&s.auth_time&&s.iat,i.auth,"internal-error");const o="object"==typeof s.firebase?s.firebase:void 0,a=null==o?void 0:o.sign_in_provider;return{claims:s,token:r,authTime:Y(Z(s.auth_time)),issuedAtTime:Y(Z(s.iat)),expirationTime:Y(Z(s.exp)),signInProvider:a||null,signInSecondFactor:(null==o?void 0:o.sign_in_second_factor)||null}}function Z(e){return 1e3*Number(e)}function ee(t){const[n,i,r]=t.split(".");if(void 0===n||void 0===i||void 0===r)return v("JWT malformed, contained fewer than 3 sections"),null;try{const t=(0,e.base64Decode)(i);return t?JSON.parse(t):(v("Failed to decode base64 JWT payload"),null)}catch(s){return v("Caught error parsing JWT payload as JSON",null==s?void 0:s.toString()),null}}function te(e){const t=ee(e);return E(t,"internal-error"),E(void 0!==t.exp,"internal-error"),E(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function ne(t,n,i=!1){if(i)return n;try{return await n}catch(r){throw r instanceof e.FirebaseError&&ie(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function ie({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}class re{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class se{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Y(this.lastLoginAt),this.creationTime=Y(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function oe(e){var t;const n=e.auth,i=await e.getIdToken(),r=await ne(e,$(n,{idToken:i}));E(null==r?void 0:r.users.length,n,"internal-error");const s=r.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?ue(s.providerUserInfo):[],a=ce(e.providerData,o),c=e.isAnonymous,u=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!c&&u,l={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 se(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,l)}async function ae(t){const n=(0,e.getModularInstance)(t);await oe(n),await n.auth._persistUserIfCurrent(n),n.auth._notifyListenersIfCurrent(n)}function ce(e,t){return[...e.filter(e=>!t.some(t=>t.providerId===e.providerId)),...t]}function ue(e){return e.map(e=>{var{providerId:t}=e,n=(0,i.__rest)(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})}async function de(t,n){const i=await H(t,{},async()=>{const i=(0,e.querystring)({grant_type:"refresh_token",refresh_token:n}).slice(1),{tokenApiHost:r,apiKey:s}=t.config,o=G(t,r,"/v1/token",`key=${s}`),a=await t._getAdditionalHeaders();return a["Content-Type"]="application/x-www-form-urlencoded",U.fetch()(o,{method:"POST",headers:a,body:i})});return{accessToken:i.access_token,expiresIn:i.expires_in,refreshToken:i.refresh_token}}class le{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){E(e.idToken,"internal-error"),E(void 0!==e.idToken,"internal-error"),E(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):te(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e,t=!1){return E(!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:i,expiresIn:r}=await de(e,t);this.updateTokensAndExpiration(n,i,Number(r))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:i,expirationTime:r}=t,s=new le;return n&&(E("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),i&&(E("string"==typeof i,"internal-error",{appName:e}),s.accessToken=i),r&&(E("number"==typeof r,"internal-error",{appName:e}),s.expirationTime=r),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new le,this.toJSON())}_performRefresh(){return k("not implemented")}}function he(e,t){E("string"==typeof e||void 0===e,"internal-error",{appName:t})}class pe{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,s=(0,i.__rest)(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new re(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new se(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await ne(this,this.stsTokenManager.getToken(this.auth,e));return E(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return Q(this,e)}reload(){return ae(this)}_assign(e){this!==e&&(E(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 pe(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){E(!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 oe(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await ne(this,B(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,i,r,s,o,a,c,u;const d=null!==(n=t.displayName)&&void 0!==n?n:void 0,l=null!==(i=t.email)&&void 0!==i?i:void 0,h=null!==(r=t.phoneNumber)&&void 0!==r?r:void 0,p=null!==(s=t.photoURL)&&void 0!==s?s:void 0,m=null!==(o=t.tenantId)&&void 0!==o?o:void 0,f=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=t.createdAt)&&void 0!==c?c:void 0,v=null!==(u=t.lastLoginAt)&&void 0!==u?u:void 0,{uid:I,emailVerified:_,isAnonymous:y,providerData:T,stsTokenManager:w}=t;E(I&&w,e,"internal-error");const k=le.fromJSON(this.name,w);E("string"==typeof I,e,"internal-error"),he(d,e.name),he(l,e.name),E("boolean"==typeof _,e,"internal-error"),E("boolean"==typeof y,e,"internal-error"),he(h,e.name),he(p,e.name),he(m,e.name),he(f,e.name),he(g,e.name),he(v,e.name);const A=new pe({uid:I,auth:e,email:l,emailVerified:_,displayName:d,isAnonymous:y,photoURL:p,phoneNumber:h,tenantId:m,stsTokenManager:k,createdAt:g,lastLoginAt:v});return T&&Array.isArray(T)&&(A.providerData=T.map(e=>Object.assign({},e))),f&&(A._redirectEventId=f),A}static async _fromIdTokenResponse(e,t,n=!1){const i=new le;i.updateFromServerResponse(t);const r=new pe({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await oe(r),r}}exports.aF=pe;class me{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){}}me.type="NONE";const fe=me;function ge(e,t,n){return`firebase:${e}:${t}:${n}`}exports.L=fe;class ve{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:i,name:r}=this.auth;this.fullUserKey=ge(this.userKey,i.apiKey,r),this.fullPersistenceKey=ge("persistence",i.apiKey,r),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?pe._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 ve(N(fe),e,n);const i=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let r=i[0]||N(fe);const s=ge(n,e.config.apiKey,e.name);let o=null;for(const u of t)try{const t=await u._get(s);if(t){const n=pe._fromJSON(e,t);u!==r&&(o=n),r=u;break}}catch(c){}const a=i.filter(e=>e._shouldAllowMigration);return r._shouldAllowMigration&&a.length?(r=a[0],o&&await r._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==r)try{await e._remove(s)}catch(c){}})),new ve(r,e,n)):new ve(r,e,n)}}function Ie(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(we(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(_e(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(ke(t))return"Blackberry";if(Ae(t))return"Webos";if(ye(t))return"Safari";if((t.includes("chrome/")||Te(t))&&!t.includes("edge/"))return"Chrome";if(Ee(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 _e(t=(0,e.getUA)()){return/firefox\//i.test(t)}function ye(t=(0,e.getUA)()){const n=t.toLowerCase();return n.includes("safari/")&&!n.includes("chrome/")&&!n.includes("crios/")&&!n.includes("android")}function Te(t=(0,e.getUA)()){return/crios\//i.test(t)}function we(t=(0,e.getUA)()){return/iemobile/i.test(t)}function Ee(t=(0,e.getUA)()){return/android/i.test(t)}function ke(t=(0,e.getUA)()){return/blackberry/i.test(t)}function Ae(t=(0,e.getUA)()){return/webos/i.test(t)}function Re(t=(0,e.getUA)()){return/iphone|ipad|ipod/i.test(t)||/macintosh/i.test(t)&&/mobile/i.test(t)}function Ne(t=(0,e.getUA)()){return/(iPad|iPhone|iPod).*OS 7_\d/i.test(t)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(t)}function be(t=(0,e.getUA)()){var n;return Re(t)&&!!(null===(n=window.navigator)||void 0===n?void 0:n.standalone)}function Se(){return(0,e.isIE)()&&10===document.documentMode}function Oe(t=(0,e.getUA)()){return Re(t)||Ee(t)||Ae(t)||ke(t)||/windows phone/i.test(t)||we(t)}function Pe(){try{return!(!window||window===window.top)}catch(e){return!1}}function De(n,i=[]){let r;switch(n){case"Browser":r=Ie((0,e.getUA)());break;case"Worker":r=`${Ie((0,e.getUA)())}-${n}`;break;default:r=n}const s=i.length?i.join(","):"FirebaseCore-web";return`${r}/JsCore/${t.SDK_VERSION}/${s}`}class Ce{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise((n,i)=>{try{n(e(t))}catch(r){i(r)}});n.onAbort=t,this.queue.push(n);const i=this.queue.length-1;return()=>{this.queue[i]=(()=>Promise.resolve())}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(n){t.reverse();for(const e of t)try{e()}catch(i){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==n?void 0:n.message})}}}class Le{constructor(e,t,n){this.app=e,this.heartbeatServiceProvider=t,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new xe(this),this.idTokenSubscription=new xe(this),this.beforeStateQueue=new Ce(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=m,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=N(t)),this._initializationPromise=this.queue(async()=>{var n,i;if(!this._deleted&&(this.persistenceManager=await ve.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(r){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void(await this.currentUser.getIdToken())):void(await this._updateCurrentUser(e,!0)):void 0}async initializeCurrentUser(e){var t;const n=await this.assertedPersistence.getCurrentUser();let i=n,r=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(e);n&&n!==s||null==o||!o.user||(i=o.user,r=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(r)try{await this.beforeStateQueue.runMiddleware(i)}catch(s){i=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(s))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return E(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(n){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await oe(e)}catch(t){if("auth/network-request-failed"!==(null==t?void 0:t.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=L()}async _delete(){this._deleted=!0}async updateCurrentUser(t){const n=t?(0,e.getModularInstance)(t):null;return n&&E(n.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(n&&n._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&E(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(N(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(t){this._errorFactory=new e.ErrorFactory("auth","Firebase",t())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&N(e)||this._popupRedirectResolver;E(t,this,"argument-error"),this.redirectPersistenceManager=await ve.create(this,[N(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};const r="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return E(s,this,"internal-error"),s.then(()=>r(this.currentUser)),"function"==typeof t?e.addObserver(t,n,i):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 E(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=De(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());return n&&(t["X-Firebase-Client"]=n),t}}function Me(t){return(0,e.getModularInstance)(t)}exports.aG=Le;class xe{constructor(t){this.auth=t,this.observer=null,this.addObserver=(0,e.createSubscribe)(e=>this.observer=e)}get next(){return E(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function Ue(e,t,n){const i=Me(e);E(i._canInitEmulator,i,"emulator-config-failed"),E(/^https?:\/\//.test(t),i,"invalid-emulator-scheme");const r=!!(null==n?void 0:n.disableWarnings),s=Fe(t),{host:o,port:a}=Ve(t),c=null===a?"":`:${a}`;i.config.emulator={url:`${s}//${o}${c}/`},i.settings.appVerificationDisabledForTesting=!0,i.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:r})}),r||je()}function Fe(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Ve(e){const t=Fe(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const i=n[2].split("@").pop()||"",r=/^(\[[^\]]+\])(:|$)/.exec(i);if(r){const e=r[1];return{host:e,port:qe(i.substr(e.length+1))}}{const[e,t]=i.split(":");return{host:e,port:qe(t)}}}function qe(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}function je(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}class He{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return k("not implemented")}_getIdTokenResponse(e){return k("not implemented")}_linkToIdToken(e,t){return k("not implemented")}_getReauthenticationResolver(e){return k("not implemented")}}async function ze(e,t){return j(e,"POST","/v1/accounts:resetPassword",q(e,t))}async function Ge(e,t){return j(e,"POST","/v1/accounts:update",t)}async function We(e,t){return j(e,"POST","/v1/accounts:update",q(e,t))}async function Ke(e,t){return z(e,"POST","/v1/accounts:signInWithPassword",q(e,t))}async function Be(e,t){return j(e,"POST","/v1/accounts:sendOobCode",q(e,t))}async function Je(e,t){return Be(e,t)}async function $e(e,t){return Be(e,t)}async function Ye(e,t){return Be(e,t)}async function Xe(e,t){return Be(e,t)}async function Qe(e,t){return z(e,"POST","/v1/accounts:signInWithEmailLink",q(e,t))}async function Ze(e,t){return z(e,"POST","/v1/accounts:signInWithEmailLink",q(e,t))}exports.H=He;class et extends He{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new et(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new et(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 Ke(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return Qe(e,{email:this._email,oobCode:this._password});default:I(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ge(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return Ze(e,{idToken:t,email:this._email,oobCode:this._password});default:I(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function tt(e,t){return z(e,"POST","/v1/accounts:signInWithIdp",q(e,t))}exports.I=et;const nt="http://localhost";class it extends He{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new it(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):I("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,s=(0,i.__rest)(t,["providerId","signInMethod"]);if(!n||!r)return null;const o=new it(n,r);return o.idToken=s.idToken||void 0,o.accessToken=s.accessToken||void 0,o.secret=s.secret,o.nonce=s.nonce,o.pendingToken=s.pendingToken||null,o}_getIdTokenResponse(e){return tt(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,tt(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,tt(e,t)}buildRequest(){const t={requestUri:nt,returnSecureToken:!0};if(this.pendingToken)t.pendingToken=this.pendingToken;else{const n={};this.idToken&&(n.id_token=this.idToken),this.accessToken&&(n.access_token=this.accessToken),this.secret&&(n.oauth_token_secret=this.secret),n.providerId=this.providerId,this.nonce&&!this.pendingToken&&(n.nonce=this.nonce),t.postBody=(0,e.querystring)(n)}return t}}async function rt(e,t){return j(e,"POST","/v1/accounts:sendVerificationCode",q(e,t))}async function st(e,t){return z(e,"POST","/v1/accounts:signInWithPhoneNumber",q(e,t))}async function ot(e,t){const n=await z(e,"POST","/v1/accounts:signInWithPhoneNumber",q(e,t));if(n.temporaryProof)throw K(e,"account-exists-with-different-credential",n);return n}exports.J=it;const at={USER_NOT_FOUND:"user-not-found"};async function ct(e,t){return z(e,"POST","/v1/accounts:signInWithPhoneNumber",q(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),at)}class ut extends He{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new ut({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new ut({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return st(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return ot(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return ct(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:i}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}=e;return n||t||i||r?new ut({verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}):null}}function dt(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}}function lt(t){const n=(0,e.querystringDecode)((0,e.extractQuerystring)(t)).link,i=n?(0,e.querystringDecode)((0,e.extractQuerystring)(n)).deep_link_id:null,r=(0,e.querystringDecode)((0,e.extractQuerystring)(t)).deep_link_id;return(r?(0,e.querystringDecode)((0,e.extractQuerystring)(r)).link:null)||r||i||n||t}exports.K=ut;class ht{constructor(t){var n,i,r,s,o,a;const c=(0,e.querystringDecode)((0,e.extractQuerystring)(t)),u=null!==(n=c.apiKey)&&void 0!==n?n:null,d=null!==(i=c.oobCode)&&void 0!==i?i:null,l=dt(null!==(r=c.mode)&&void 0!==r?r:null);E(u&&d&&l,"argument-error"),this.apiKey=u,this.operation=l,this.code=d,this.continueUrl=null!==(s=c.continueUrl)&&void 0!==s?s:null,this.languageCode=null!==(o=c.languageCode)&&void 0!==o?o:null,this.tenantId=null!==(a=c.tenantId)&&void 0!==a?a:null}static parseLink(e){const t=lt(e);try{return new ht(t)}catch(n){return null}}}function pt(e){return ht.parseLink(e)}exports.ad=ht;class mt{constructor(){this.providerId=mt.PROVIDER_ID}static credential(e,t){return et._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=ht.parseLink(t);return E(n,"argument-error"),et._fromEmailAndCode(e,n.code,n.tenantId)}}exports.M=mt,mt.PROVIDER_ID="password",mt.EMAIL_PASSWORD_SIGN_IN_METHOD="password",mt.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class ft{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 gt extends ft{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class vt extends gt{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return E("providerId"in t&&"signInMethod"in t,"argument-error"),it._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return E(e.idToken||e.accessToken,"argument-error"),it._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return vt.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return vt.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:i,pendingToken:r,nonce:s,providerId:o}=e;if(!(n||i||t||r))return null;if(!o)return null;try{return new vt(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:r})}catch(a){return null}}}exports.U=vt;class It extends gt{constructor(){super("facebook.com")}static credential(e){return it._fromParams({providerId:It.PROVIDER_ID,signInMethod:It.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return It.credentialFromTaggedObject(e)}static credentialFromError(e){return It.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return It.credential(e.oauthAccessToken)}catch(t){return null}}}exports.N=It,It.FACEBOOK_SIGN_IN_METHOD="facebook.com",It.PROVIDER_ID="facebook.com";class _t extends gt{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return it._fromParams({providerId:_t.PROVIDER_ID,signInMethod:_t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return _t.credentialFromTaggedObject(e)}static credentialFromError(e){return _t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return _t.credential(t,n)}catch(i){return null}}}exports.Q=_t,_t.GOOGLE_SIGN_IN_METHOD="google.com",_t.PROVIDER_ID="google.com";class yt extends gt{constructor(){super("github.com")}static credential(e){return it._fromParams({providerId:yt.PROVIDER_ID,signInMethod:yt.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return yt.credentialFromTaggedObject(e)}static credentialFromError(e){return yt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return yt.credential(e.oauthAccessToken)}catch(t){return null}}}exports.T=yt,yt.GITHUB_SIGN_IN_METHOD="github.com",yt.PROVIDER_ID="github.com";const Tt="http://localhost";class wt extends He{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return tt(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,tt(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,tt(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i,pendingToken:r}=t;return n&&i&&r&&n===i?new wt(n,r):null}static _create(e,t){return new wt(e,t)}buildRequest(){return{requestUri:Tt,returnSecureToken:!0,pendingToken:this.pendingToken}}}exports.aL=wt;const Et="saml.";class kt extends ft{constructor(e){E(e.startsWith(Et),"argument-error"),super(e)}static credentialFromResult(e){return kt.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return kt.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=wt.fromJSON(e);return E(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return wt._create(n,t)}catch(i){return null}}}exports.V=kt;class At extends gt{constructor(){super("twitter.com")}static credential(e,t){return it._fromParams({providerId:At.PROVIDER_ID,signInMethod:At.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return At.credentialFromTaggedObject(e)}static credentialFromError(e){return At.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return At.credential(t,n)}catch(i){return null}}}async function Rt(e,t){return z(e,"POST","/v1/accounts:signUp",q(e,t))}exports.W=At,At.TWITTER_SIGN_IN_METHOD="twitter.com",At.PROVIDER_ID="twitter.com";class Nt{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){const r=await pe._fromIdTokenResponse(e,n,i),s=bt(n);return new Nt({user:r,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const i=bt(n);return new Nt({user:e,providerId:i,_tokenResponse:n,operationType:t})}}function bt(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}async function St(e){var t;const n=Me(e);if(await n._initializationPromise,null===(t=n.currentUser)||void 0===t?void 0:t.isAnonymous)return new Nt({user:n.currentUser,providerId:null,operationType:"signIn"});const i=await Rt(n,{returnSecureToken:!0}),r=await Nt._fromIdTokenResponse(n,"signIn",i,!0);return await n._updateCurrentUser(r.user),r}class Ot extends e.FirebaseError{constructor(e,t,n,i){var r;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,Ot.prototype),this.customData={appName:e.name,tenantId:null!==(r=e.tenantId)&&void 0!==r?r:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new Ot(e,t,n,i)}}function Pt(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch(n=>{if("auth/multi-factor-auth-required"===n.code)throw Ot._fromErrorAndOperation(e,n,t,i);throw n})}function Dt(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Ct(t,n){const i=(0,e.getModularInstance)(t);await Mt(!0,i,n);const{providerUserInfo:r}=await J(i.auth,{idToken:await i.getIdToken(),deleteProvider:[n]}),s=Dt(r||[]);return i.providerData=i.providerData.filter(e=>s.has(e.providerId)),s.has("phone")||(i.phoneNumber=null),await i.auth._persistUserIfCurrent(i),i}async function Lt(e,t,n=!1){const i=await ne(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Nt._forOperation(e,"link",i)}async function Mt(e,t,n){await oe(t);const i=!1===e?"provider-already-linked":"no-such-provider";E(Dt(t.providerData).has(n)===e,t.auth,i)}async function xt(e,t,n=!1){const{auth:i}=e;try{const s=await ne(e,Pt(i,"reauthenticate",t,e),n);E(s.idToken,i,"internal-error");const o=ee(s.idToken);E(o,i,"internal-error");const{sub:a}=o;return E(e.uid===a,i,"user-mismatch"),Nt._forOperation(e,"reauthenticate",s)}catch(r){throw"auth/user-not-found"===(null==r?void 0:r.code)&&I(i,"user-mismatch"),r}}async function Ut(e,t,n=!1){const i=await Pt(e,"signIn",t),r=await Nt._fromIdTokenResponse(e,"signIn",i);return n||await e._updateCurrentUser(r.user),r}async function Ft(e,t){return Ut(Me(e),t)}async function Vt(t,n){const i=(0,e.getModularInstance)(t);return await Mt(!1,i,n.providerId),Lt(i,n)}async function qt(t,n){return xt((0,e.getModularInstance)(t),n)}async function jt(e,t){return z(e,"POST","/v1/accounts:signInWithCustomToken",q(e,t))}async function Ht(e,t){const n=Me(e),i=await jt(n,{token:t,returnSecureToken:!0}),r=await Nt._fromIdTokenResponse(n,"signIn",i);return await n._updateCurrentUser(r.user),r}class zt{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?Gt._fromServerResponse(e,t):I(e,"internal-error")}}class Gt extends zt{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new Gt(t)}}function Wt(e,t,n){var i;E((null===(i=n.url)||void 0===i?void 0:i.length)>0,e,"invalid-continue-uri"),E(void 0===n.dynamicLinkDomain||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(E(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(E(n.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function Kt(t,n,i){const r=(0,e.getModularInstance)(t),s={requestType:"PASSWORD_RESET",email:n};i&&Wt(r,s,i),await $e(r,s)}async function Bt(t,n,i){await ze((0,e.getModularInstance)(t),{oobCode:n,newPassword:i})}async function Jt(t,n){await We((0,e.getModularInstance)(t),{oobCode:n})}async function $t(t,n){const i=(0,e.getModularInstance)(t),r=await ze(i,{oobCode:n}),s=r.requestType;switch(E(s,i,"internal-error"),s){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":E(r.newEmail,i,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":E(r.mfaInfo,i,"internal-error");default:E(r.email,i,"internal-error")}let o=null;return r.mfaInfo&&(o=zt._fromServerResponse(Me(i),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:o},operation:s}}async function Yt(t,n){const{data:i}=await $t((0,e.getModularInstance)(t),n);return i.email}async function Xt(e,t,n){const i=Me(e),r=await Rt(i,{returnSecureToken:!0,email:t,password:n}),s=await Nt._fromIdTokenResponse(i,"signIn",r);return await i._updateCurrentUser(s.user),s}function Qt(t,n,i){return Ft((0,e.getModularInstance)(t),mt.credential(n,i))}async function Zt(t,n,i){const r=(0,e.getModularInstance)(t),s={requestType:"EMAIL_SIGNIN",email:n};E(i.handleCodeInApp,r,"argument-error"),i&&Wt(r,s,i),await Ye(r,s)}function en(e,t){const n=ht.parseLink(t);return"EMAIL_SIGNIN"===(null==n?void 0:n.operation)}async function tn(t,n,i){const r=(0,e.getModularInstance)(t),s=mt.credentialWithLink(n,i||O());return E(s._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),Ft(r,s)}async function nn(e,t){return j(e,"POST","/v1/accounts:createAuthUri",q(e,t))}async function rn(t,n){const i={identifier:n,continueUri:P()?O():"http://localhost"},{signinMethods:r}=await nn((0,e.getModularInstance)(t),i);return r||[]}async function sn(t,n){const i=(0,e.getModularInstance)(t),r={requestType:"VERIFY_EMAIL",idToken:await t.getIdToken()};n&&Wt(i.auth,r,n);const{email:s}=await Je(i.auth,r);s!==t.email&&await t.reload()}async function on(t,n,i){const r=(0,e.getModularInstance)(t),s={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await t.getIdToken(),newEmail:n};i&&Wt(r.auth,s,i);const{email:o}=await Xe(r.auth,s);o!==t.email&&await t.reload()}async function an(e,t){return j(e,"POST","/v1/accounts:update",t)}async function cn(t,{displayName:n,photoURL:i}){if(void 0===n&&void 0===i)return;const r=(0,e.getModularInstance)(t),s={idToken:await r.getIdToken(),displayName:n,photoUrl:i,returnSecureToken:!0},o=await ne(r,an(r.auth,s));r.displayName=o.displayName||null,r.photoURL=o.photoUrl||null;const a=r.providerData.find(({providerId:e})=>"password"===e);a&&(a.displayName=r.displayName,a.photoURL=r.photoURL),await r._updateTokensIfNecessary(o)}function un(t,n){return ln((0,e.getModularInstance)(t),n,null)}function dn(t,n){return ln((0,e.getModularInstance)(t),null,n)}async function ln(e,t,n){const{auth:i}=e,r={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(r.email=t),n&&(r.password=n);const s=await ne(e,Ge(i,r));await e._updateTokensIfNecessary(s,!0)}function hn(e){var t,n;if(!e)return null;const{providerId:i}=e,r=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},s=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!i&&(null==e?void 0:e.idToken)){const i=null===(n=null===(t=ee(e.idToken))||void 0===t?void 0:t.firebase)||void 0===n?void 0:n.sign_in_provider;if(i){return new pn(s,"anonymous"!==i&&"custom"!==i?i:null)}}if(!i)return null;switch(i){case"facebook.com":return new fn(s,r);case"github.com":return new gn(s,r);case"google.com":return new vn(s,r);case"twitter.com":return new In(s,r,e.screenName||null);case"custom":case"anonymous":return new pn(s,null);default:return new pn(s,i,r)}}class pn{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class mn extends pn{constructor(e,t,n,i){super(e,t,n),this.username=i}}class fn extends pn{constructor(e,t){super(e,"facebook.com",t)}}class gn extends mn{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class vn extends pn{constructor(e,t){super(e,"google.com",t)}}class In extends mn{constructor(e,t,n){super(e,"twitter.com",t,n)}}function _n(e){const{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:hn(n)}function yn(t,n){return(0,e.getModularInstance)(t).setPersistence(n)}function Tn(t,n,i,r){return(0,e.getModularInstance)(t).onIdTokenChanged(n,i,r)}function wn(t,n,i){return(0,e.getModularInstance)(t).beforeAuthStateChanged(n,i)}function En(t,n,i,r){return(0,e.getModularInstance)(t).onAuthStateChanged(n,i,r)}function kn(t){(0,e.getModularInstance)(t).useDeviceLanguage()}function An(t,n){return(0,e.getModularInstance)(t).updateCurrentUser(n)}function Rn(t){return(0,e.getModularInstance)(t).signOut()}async function Nn(t){return(0,e.getModularInstance)(t).delete()}class bn{constructor(e,t,n){this.type=e,this.credential=t,this.auth=n}static _fromIdtoken(e,t){return new bn("enroll",e,t)}static _fromMfaPendingCredential(e){return new bn("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t,n;if(null==e?void 0:e.multiFactorSession){if(null===(t=e.multiFactorSession)||void 0===t?void 0:t.pendingCredential)return bn._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null===(n=e.multiFactorSession)||void 0===n?void 0:n.idToken)return bn._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Sn{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,t){const n=Me(e),i=t.customData._serverResponse,r=(i.mfaInfo||[]).map(e=>zt._fromServerResponse(n,e));E(i.mfaPendingCredential,n,"internal-error");const s=bn._fromMfaPendingCredential(i.mfaPendingCredential);return new Sn(s,r,async e=>{const r=await e._process(n,s);delete i.mfaInfo,delete i.mfaPendingCredential;const o=Object.assign(Object.assign({},i),{idToken:r.idToken,refreshToken:r.refreshToken});switch(t.operationType){case"signIn":const e=await Nt._fromIdTokenResponse(n,t.operationType,o);return await n._updateCurrentUser(e.user),e;case"reauthenticate":return E(t.user,n,"internal-error"),Nt._forOperation(t.user,t.operationType,o);default:I(n,"internal-error")}})}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function On(t,n){var i;const r=(0,e.getModularInstance)(t),s=n;return E(n.customData.operationType,r,"argument-error"),E(null===(i=s.customData._serverResponse)||void 0===i?void 0:i.mfaPendingCredential,r,"argument-error"),Sn._fromError(r,s)}function Pn(e,t){return j(e,"POST","/v2/accounts/mfaEnrollment:start",q(e,t))}function Dn(e,t){return j(e,"POST","/v2/accounts/mfaEnrollment:finalize",q(e,t))}function Cn(e,t){return j(e,"POST","/v2/accounts/mfaEnrollment:withdraw",q(e,t))}class Ln{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload(t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map(t=>zt._fromServerResponse(e.auth,t)))})}static _fromUser(e){return new Ln(e)}async getSession(){return bn._fromIdtoken(await this.user.getIdToken(),this.user.auth)}async enroll(e,t){const n=e,i=await this.getSession(),r=await ne(this.user,n._process(this.user.auth,i,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,n=await this.user.getIdToken();try{const e=await ne(this.user,Cn(this.user.auth,{idToken:n,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(i){throw i}}}const Mn=new WeakMap;function xn(t){const n=(0,e.getModularInstance)(t);return Mn.has(n)||Mn.set(n,Ln._fromUser(n)),Mn.get(n)}const Un="__sak";class Fn{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Un,"1"),this.storage.removeItem(Un),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()}}function Vn(){const t=(0,e.getUA)();return ye(t)||Re(t)}const qn=1e3,jn=10;class Hn extends Fn{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=((e,t)=>this.onStorageEvent(e,t)),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=Vn()&&Pe(),this.fallbackToPolling=Oe(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)});const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(n);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const i=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},r=this.storage.getItem(n);Se()&&r!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,jn):i()}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const i of Array.from(n))i(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)})},qn)}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]}}Hn.type="LOCAL";const zn=Hn;exports.b=zn;class Gn extends Fn{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Gn.type="SESSION";const Wn=Gn;function Kn(e){return Promise.all(e.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}exports.a=Wn;class Bn{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 Bn(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:i,data:r}=t.data,s=this.handlersMap[i];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:i});const o=Array.from(s).map(async e=>e(t.origin,r)),a=await Kn(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:i,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function Jn(e="",t=10){let n="";for(let i=0;i<t;i++)n+=Math.floor(10*Math.random());return e+n}Bn.receivers=[];class $n{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,n=50){const i="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!i)throw new Error("connection_unavailable");let r,s;return new Promise((o,a)=>{const c=Jn("",20);i.port1.start();const u=setTimeout(()=>{a(new Error("unsupported_event"))},n);s={messageChannel:i,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),r=setTimeout(()=>{a(new Error("timeout"))},3e3);break;case"done":clearTimeout(r),o(t.data.response);break;default:clearTimeout(u),clearTimeout(r),a(new Error("invalid_response"))}}},this.handlers.add(s),i.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[i.port2])}).finally(()=>{s&&this.removeMessageHandler(s)})}}function Yn(){return window}function Xn(e){Yn().location.href=e}function Qn(){return void 0!==Yn().WorkerGlobalScope&&"function"==typeof Yn().importScripts}async function Zn(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}function ei(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}function ti(){return Qn()?self:null}const ni="firebaseLocalStorageDb",ii=1,ri="firebaseLocalStorage",si="fbase_key";class oi{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 ai(e,t){return e.transaction([ri],t?"readwrite":"readonly").objectStore(ri)}function ci(){const e=indexedDB.deleteDatabase(ni);return new oi(e).toPromise()}function ui(){const e=indexedDB.open(ni,ii);return new Promise((t,n)=>{e.addEventListener("error",()=>{n(e.error)}),e.addEventListener("upgradeneeded",()=>{const t=e.result;try{t.createObjectStore(ri,{keyPath:si})}catch(i){n(i)}}),e.addEventListener("success",async()=>{const n=e.result;n.objectStoreNames.contains(ri)?t(n):(n.close(),await ci(),t(await ui()))})})}async function di(e,t,n){const i=ai(e,!0).put({[si]:t,value:n});return new oi(i).toPromise()}async function li(e,t){const n=ai(e,!1).get(t),i=await new oi(n).toPromise();return void 0===i?null:i.value}function hi(e,t){const n=ai(e,!0).delete(t);return new oi(n).toPromise()}const pi=800,mi=3;class fi{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db?this.db:(this.db=await ui(),this.db)}async _withRetries(e){let t=0;for(;;)try{const i=await this._openDb();return await e(i)}catch(n){if(t++>mi)throw n;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Qn()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Bn._getInstance(ti()),this.receiver._subscribe("keyChanged",async(e,t)=>{return{keyProcessed:(await this._poll()).includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t;if(this.activeServiceWorker=await Zn(),!this.activeServiceWorker)return;this.sender=new $n(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&&ei()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const t=await ui();return await di(t,Un,"1"),await hi(t,Un),!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=>di(n,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(t=>li(t,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>hi(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(e=>{const t=ai(e,!1).getAll();return new oi(t).toPromise()});if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:i,value:r}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(r)&&(this.notifyListeners(i,r),t.push(i));for(const i of Object.keys(this.localCache))this.localCache[i]&&!n.has(i)&&(this.notifyListeners(i,null),t.push(i));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const i of Array.from(n))i(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),pi)}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()}}fi.type="LOCAL";const gi=fi;function vi(e,t){return j(e,"POST","/v2/accounts/mfaSignIn:start",q(e,t))}function Ii(e,t){return j(e,"POST","/v2/accounts/mfaSignIn:finalize",q(e,t))}async function _i(e){return(await j(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}function yi(){var e,t;return null!==(t=null===(e=document.getElementsByTagName("head"))||void 0===e?void 0:e[0])&&void 0!==t?t:document}function Ti(e){return new Promise((t,n)=>{const i=document.createElement("script");i.setAttribute("src",e),i.onload=t,i.onerror=(e=>{const t=_("internal-error");t.customData=e,n(t)}),i.type="text/javascript",i.charset="UTF-8",yi().appendChild(i)})}function wi(e){return`__${e}${Math.floor(1e6*Math.random())}`}exports.i=gi;const Ei=500,ki=6e4,Ai=1e12;class Ri{constructor(e){this.auth=e,this.counter=Ai,this._widgets=new Map}render(e,t){const n=this.counter;return this._widgets.set(n,new Ni(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t;const n=e||Ai;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;const n=e||Ai;return(null===(t=this._widgets.get(n))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;const n=e||Ai;return null===(t=this._widgets.get(n))||void 0===t||t.execute(),""}}class Ni{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=(()=>{this.execute()});const i="string"==typeof e?document.getElementById(e):e;E(i,"argument-error",{appName:t}),this.container=i,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=bi(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(n){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(n){}this.isVisible&&this.execute()},ki)},Ei))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}function bi(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let i=0;i<e;i++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}const Si=wi("rcb"),Oi=new M(3e4,6e4),Pi="https://www.google.com/recaptcha/api.js?";class Di{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!(null===(e=Yn().grecaptcha)||void 0===e?void 0:e.render)}load(t,n=""){return E(Ci(n),t,"argument-error"),this.shouldResolveImmediately(n)?Promise.resolve(Yn().grecaptcha):new Promise((i,r)=>{const s=Yn().setTimeout(()=>{r(_(t,"network-request-failed"))},Oi.get());Yn()[Si]=(()=>{Yn().clearTimeout(s),delete Yn()[Si];const e=Yn().grecaptcha;if(!e)return void r(_(t,"internal-error"));const o=e.render;e.render=((e,t)=>{const n=o(e,t);return this.counter++,n}),this.hostLanguage=n,i(e)}),Ti(`${Pi}?${(0,e.querystring)({onload:Si,render:"explicit",hl:n})}`).catch(()=>{clearTimeout(s),r(_(t,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!!(null===(t=Yn().grecaptcha)||void 0===t?void 0:t.render)&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}function Ci(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}class Li{async load(e){return new Ri(e)}clearedOneInstance(){}}const Mi="recaptcha",xi={theme:"light",type:"image"};class Ui{constructor(e,t=Object.assign({},xi),n){this.parameters=t,this.type=Mi,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Me(n),this.isInvisible="invisible"===this.parameters.size,E("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");const i="string"==typeof e?document.getElementById(e):e;E(i,this.auth,"argument-error"),this.container=i,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new Li:new Di,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha(),n=t.getResponse(e);return n||new Promise(n=>{const i=e=>{e&&(this.tokenChangeListeners.delete(i),n(e))};this.tokenChangeListeners.add(i),this.isInvisible&&t.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise?this.renderPromise:(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){E(!this.parameters.sitekey,this.auth,"argument-error"),E(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),E("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof e)e(t);else if("string"==typeof e){const n=Yn()[e];"function"==typeof n&&n(t)}}}assertNotDestroyed(){E(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){E(P()&&!Qn(),this.auth,"internal-error"),await Fi(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await _i(this.auth);E(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return E(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}function Fi(){let e=null;return new Promise(t=>{"complete"!==document.readyState?(e=(()=>t()),window.addEventListener("load",e)):t()}).catch(t=>{throw e&&window.removeEventListener("load",e),t})}exports.R=Ui;class Vi{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=ut._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function qi(t,n,i){const r=Me(t),s=await zi(r,n,(0,e.getModularInstance)(i));return new Vi(s,e=>Ft(r,e))}async function ji(t,n,i){const r=(0,e.getModularInstance)(t);await Mt(!1,r,"phone");const s=await zi(r.auth,n,(0,e.getModularInstance)(i));return new Vi(s,e=>Vt(r,e))}async function Hi(t,n,i){const r=(0,e.getModularInstance)(t),s=await zi(r.auth,n,(0,e.getModularInstance)(i));return new Vi(s,e=>qt(r,e))}async function zi(e,t,n){var i;const r=await n.verify();try{let s;if(E("string"==typeof r,e,"argument-error"),E(n.type===Mi,e,"argument-error"),"session"in(s="string"==typeof t?{phoneNumber:t}:t)){const t=s.session;if("phoneNumber"in s){return E("enroll"===t.type,e,"internal-error"),(await Pn(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:r}})).phoneSessionInfo.sessionInfo}{E("signin"===t.type,e,"internal-error");const n=(null===(i=s.multiFactorHint)||void 0===i?void 0:i.uid)||s.multiFactorUid;return E(n,e,"missing-multi-factor-info"),(await vi(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:r}})).phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await rt(e,{phoneNumber:s.phoneNumber,recaptchaToken:r});return t}}finally{n._reset()}}async function Gi(t,n){await Lt((0,e.getModularInstance)(t),n)}class Wi{constructor(e){this.providerId=Wi.PROVIDER_ID,this.auth=Me(e)}verifyPhoneNumber(t,n){return zi(this.auth,t,(0,e.getModularInstance)(n))}static credential(e,t){return ut._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Wi.credentialFromTaggedObject(t)}static credentialFromError(e){return Wi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?ut._fromTokenResponse(t,n):null}}function Ki(e,t){return t?N(t):(E(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}exports.P=Wi,Wi.PROVIDER_ID="phone",Wi.PHONE_SIGN_IN_METHOD="phone";class Bi extends He{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return tt(e,this._buildIdpRequest())}_linkToIdToken(e,t){return tt(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return tt(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 Ji(e){return Ut(e.auth,new Bi(e),e.bypassAuthState)}function $i(e){const{auth:t,user:n}=e;return E(n,t,"internal-error"),xt(n,new Bi(e),e.bypassAuthState)}async function Yi(e){const{auth:t,user:n}=e;return E(n,t,"internal-error"),Lt(n,new Bi(e),e.bypassAuthState)}class Xi{constructor(e,t,n,i,r=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(n){this.reject(n)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:i,tenantId:r,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:r||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(c){this.reject(c)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Ji;case"linkViaPopup":case"linkViaRedirect":return Yi;case"reauthViaPopup":case"reauthViaRedirect":return $i;default:I(this.auth,"internal-error")}}resolve(e){A(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){A(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 Qi=new M(2e3,1e4);async function Zi(e,t,n){const i=Me(e);T(e,t,ft);const r=Ki(i,n);return new nr(i,"signInViaPopup",t,r).executeNotNull()}async function er(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft);const s=Ki(r.auth,i);return new nr(r.auth,"reauthViaPopup",n,s,r).executeNotNull()}async function tr(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft);const s=Ki(r.auth,i);return new nr(r.auth,"linkViaPopup",n,s,r).executeNotNull()}class nr extends Xi{constructor(e,t,n,i,r){super(e,t,i,r),this.provider=n,this.authWindow=null,this.pollId=null,nr.currentPopupAction&&nr.currentPopupAction.cancel(),nr.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return E(e,this.auth,"internal-error"),e}async onExecution(){A(1===this.filter.length,"Popup operations only handle one event");const e=Jn();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(_(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(_(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,nr.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;null!==(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)&&void 0!==n&&n.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(_(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(e,Qi.get())};e()}}nr.currentPopupAction=null;const ir="pendingRedirect",rr=new Map;class sr extends Xi{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=rr.get(this.auth._key());if(!e){try{const n=await or(this.resolver,this.auth)?await super.execute():null;e=(()=>Promise.resolve(n))}catch(t){e=(()=>Promise.reject(t))}rr.set(this.auth._key(),e)}return this.bypassAuthState||rr.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 or(e,t){const n=lr(t),i=dr(e);if(!(await i._isAvailable()))return!1;const r="true"===await i._get(n);return await i._remove(n),r}async function ar(e,t){return dr(e)._set(lr(t),"true")}function cr(){rr.clear()}function ur(e,t){rr.set(e._key(),t)}function dr(e){return N(e._redirectPersistence)}function lr(e){return ge(ir,e.config.apiKey,e.name)}function hr(e,t,n){return pr(e,t,n)}async function pr(e,t,n){const i=Me(e);T(e,t,ft),await i._initializationPromise;const r=Ki(i,n);return await ar(r,i),r._openRedirect(i,t,"signInViaRedirect")}function mr(e,t,n){return fr(e,t,n)}async function fr(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft),await r.auth._initializationPromise;const s=Ki(r.auth,i);await ar(s,r.auth);const o=await yr(r);return s._openRedirect(r.auth,n,"reauthViaRedirect",o)}function gr(e,t,n){return vr(e,t,n)}async function vr(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft),await r.auth._initializationPromise;const s=Ki(r.auth,i);await Mt(!1,r,n.providerId),await ar(s,r.auth);const o=await yr(r);return s._openRedirect(r.auth,n,"linkViaRedirect",o)}async function Ir(e,t){return await Me(e)._initializationPromise,_r(e,t,!1)}async function _r(e,t,n=!1){const i=Me(e),r=Ki(i,t),s=new sr(i,r,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await i._persistUserIfCurrent(o.user),await i._setRedirectUser(null,t)),o}async function yr(e){const t=Jn(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}const Tr=6e5;class wr{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||!Ar(e)?t:(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0),t)}sendToConsumer(e,t){var n;if(e.error&&!kr(e)){const i=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(_(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=Tr&&this.cachedEventUids.clear(),this.cachedEventUids.has(Er(e))}saveEventToCache(e){this.cachedEventUids.add(Er(e)),this.lastProcessedEventTime=Date.now()}}function Er(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function kr({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}function Ar(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return kr(e);default:return!1}}async function Rr(e,t={}){return j(e,"GET","/v1/projects",t)}exports.ay=wr;const Nr=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,br=/^https?/;async function Sr(e){if(e.config.emulator)return;const{authorizedDomains:t}=await Rr(e);for(const i of t)try{if(Or(i))return}catch(n){}I(e,"unauthorized-domain")}function Or(e){const t=O(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){const r=new URL(e);return""===r.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===i}if(!br.test(n))return!1;if(Nr.test(e))return i===e;const r=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+r+"|"+r+")$","i").test(i)}const Pr=new M(3e4,6e4);function Dr(){const e=Yn().___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 n=0;n<e.CP.length;n++)e.CP[n]=null}function Cr(e){return new Promise((t,n)=>{var i,r,s;function o(){Dr(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{Dr(),n(_(e,"network-request-failed"))},timeout:Pr.get()})}if(null===(r=null===(i=Yn().gapi)||void 0===i?void 0:i.iframes)||void 0===r?void 0:r.Iframe)t(gapi.iframes.getContext());else{if(null===(s=Yn().gapi)||void 0===s||!s.load){const t=wi("iframefcb");return Yn()[t]=(()=>{gapi.load?o():n(_(e,"network-request-failed"))}),Ti(`https://apis.google.com/js/api.js?onload=${t}`).catch(e=>n(e))}o()}}).catch(e=>{throw Lr=null,e})}let Lr=null;function Mr(e){return Lr=Lr||Cr(e)}const xr=new M(5e3,15e3),Ur="__/auth/iframe",Fr="emulator/auth/iframe",Vr={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},qr=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function jr(n){const i=n.config;E(i.authDomain,n,"auth-domain-config-required");const r=i.emulator?x(i,Fr):`https://${n.config.authDomain}/${Ur}`,s={apiKey:i.apiKey,appName:n.name,v:t.SDK_VERSION},o=qr.get(n.config.apiHost);o&&(s.eid=o);const a=n._getFrameworks();return a.length&&(s.fw=a.join(",")),`${r}?${(0,e.querystring)(s).slice(1)}`}async function Hr(e){const t=await Mr(e),n=Yn().gapi;return E(n,e,"internal-error"),t.open({where:document.body,url:jr(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Vr,dontclear:!0},t=>new Promise(async(n,i)=>{await t.restyle({setHideOnLeave:!1});const r=_(e,"network-request-failed"),s=Yn().setTimeout(()=>{i(r)},xr.get());function o(){Yn().clearTimeout(s),n(t)}t.ping(o).then(o,()=>{i(r)})}))}const zr={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},Gr=500,Wr=600,Kr="_blank",Br="http://localhost";class Jr{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function $r(t,n,i,r=Gr,s=Wr){const o=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const u=Object.assign(Object.assign({},zr),{width:r.toString(),height:s.toString(),top:o,left:a}),d=(0,e.getUA)().toLowerCase();i&&(c=Te(d)?Kr:i),_e(d)&&(n=n||Br,u.scrollbars="yes");const l=Object.entries(u).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if(be(d)&&"_self"!==c)return Yr(n||"",c),new Jr(null);const h=window.open(n||"",c,l);E(h,t,"popup-blocked");try{h.focus()}catch(p){}return new Jr(h)}function Yr(e,t){const n=document.createElement("a");n.href=e,n.target=t;const i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(i)}exports.aJ=Jr;const Xr="__/auth/handler",Qr="emulator/auth/handler";function Zr(n,i,r,s,o,a){E(n.config.authDomain,n,"auth-domain-config-required"),E(n.config.apiKey,n,"invalid-api-key");const c={apiKey:n.config.apiKey,appName:n.name,authType:r,redirectUrl:s,v:t.SDK_VERSION,eventId:o};if(i instanceof ft){i.setDefaultLanguage(n.languageCode),c.providerId=i.providerId||"",(0,e.isEmpty)(i.getCustomParameters())||(c.customParameters=JSON.stringify(i.getCustomParameters()));for(const[e,t]of Object.entries(a||{}))c[e]=t}if(i instanceof gt){const e=i.getScopes().filter(e=>""!==e);e.length>0&&(c.scopes=e.join(","))}n.tenantId&&(c.tid=n.tenantId);const u=c;for(const e of Object.keys(u))void 0===u[e]&&delete u[e];return`${es(n)}?${(0,e.querystring)(u).slice(1)}`}function es({config:e}){return e.emulator?x(e,Qr):`https://${e.authDomain}/${Xr}`}const ts="webStorageSupport";class ns{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Wn,this._completeRedirectFn=_r,this._overrideRedirectResult=ur}async _openPopup(e,t,n,i){var r;return A(null===(r=this.eventManagers[e._key()])||void 0===r?void 0:r.manager,"_initialize() not called before _openPopup()"),$r(e,Zr(e,t,n,O(),i),Jn())}async _openRedirect(e,t,n,i){return await this._originValidation(e),Xn(Zr(e,t,n,O(),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):(A(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 Hr(e),n=new wr(e);return t.register("authEvent",t=>{return E(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(ts,{type:ts},n=>{var i;const r=null===(i=null==n?void 0:n[0])||void 0===i?void 0:i[ts];void 0!==r&&t(!!r),I(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Sr(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Oe()||ye()||Re()}}const is=ns;exports.k=is;class rs{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return k("unexpected MultiFactorSessionType")}}}class ss extends rs{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ss(e)}_finalizeEnroll(e,t,n){return Dn(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return Ii(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class os{constructor(){}static assertion(e){return ss._fromCredential(e)}}exports.m=os,os.FACTOR_ID="phone";var as="@firebase/auth",cs="0.21.3";class us{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){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){E(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function ds(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}function ls(e){(0,t._registerComponent)(new r.Component("auth",(t,{options:n})=>{const i=t.getProvider("app").getImmediate(),r=t.getProvider("heartbeat"),{apiKey:s,authDomain:o}=i.options;return((t,i)=>{E(s&&!s.includes(":"),"invalid-api-key",{appName:t.name}),E(!(null==o?void 0:o.includes(":")),"argument-error",{appName:t.name});const r={apiKey:s,authDomain:o,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:De(e)},a=new Le(t,i,r);return S(a,n),a})(i,r)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider("auth-internal").initialize()})),(0,t._registerComponent)(new r.Component("auth-internal",e=>{return(e=>new us(e))(Me(e.getProvider("auth").getImmediate()))},"PRIVATE").setInstantiationMode("EXPLICIT")),(0,t.registerVersion)(as,cs,ds(e)),(0,t.registerVersion)(as,cs,"esm2017")}const hs=300,ps=(0,e.getExperimentalSetting)("authIdTokenMaxAge")||300;let ms=null;const fs=e=>async t=>{const n=t&&await t.getIdTokenResult(),i=n&&((new Date).getTime()-Date.parse(n.issuedAtTime))/1e3;if(i&&i>ps)return;const r=null==n?void 0:n.token;ms!==r&&(ms=r,await fetch(e,{method:r?"POST":"DELETE",headers:r?{Authorization:`Bearer ${r}`}:{}}))};function gs(n=(0,t.getApp)()){const i=(0,t._getProvider)(n,"auth");if(i.isInitialized())return i.getImmediate();const r=b(n,{popupRedirectResolver:is,persistence:[gi,zn,Wn]}),s=(0,e.getExperimentalSetting)("authTokenSyncURL");if(s){const e=fs(s);wn(r,e,()=>e(r.currentUser)),Tn(r,t=>e(t))}const o=(0,e.getDefaultEmulatorHost)("auth");return o&&Ue(r,`http://${o}`),r}ls("Browser");
|
|
486
|
+
},{"@firebase/database-compat":"sWIc"}],"z5kx":[function(require,module,exports) {
|
|
487
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.$=Ht,exports.D=exports.C=exports.B=exports.A=void 0,exports.E=b,exports.F=void 0,exports.G=Ue,exports.W=exports.V=exports.U=exports.T=exports.S=exports.R=exports.Q=exports.P=exports.O=exports.N=exports.M=exports.L=exports.K=exports.J=exports.I=exports.H=void 0,exports.X=St,exports.Y=Ft,exports.Z=Vt,exports._=qt,exports.a=void 0,exports.a0=Kt,exports.a1=Bt,exports.a2=Jt,exports.a3=$t,exports.a4=Yt,exports.a5=Xt,exports.a6=Qt,exports.a7=Zt,exports.a8=en,exports.a9=tn,exports.aA=ge,exports.aB=_r,exports.aC=ur,exports.aD=cr,exports.aE=Me,exports.aG=exports.aF=void 0,exports.aH=De,exports.aI=Jn,exports.aL=exports.aK=exports.aJ=void 0,exports.aa=rn,exports.ab=sn,exports.ac=on,exports.ad=void 0,exports.ae=pt,exports.af=cn,exports.ag=un,exports.ah=dn,exports.ai=X,exports.aj=Q,exports.ak=Ct,exports.al=_n,exports.am=ae,exports.an=On,exports.ao=xn,exports.ap=A,exports.aq=Re,exports.ar=Ee,exports.as=I,exports.at=Zr,exports.au=Rr,exports.av=Ne,exports.aw=_,exports.ax=E,exports.ay=void 0,exports.az=N,exports.b=void 0,exports.c=Zi,exports.d=tr,exports.e=er,exports.f=hr,exports.g=gr,exports.h=mr,exports.i=void 0,exports.j=Ir,exports.k=void 0,exports.l=ji,exports.m=void 0,exports.n=gs,exports.o=void 0,exports.p=yn,exports.q=Tn,exports.r=Hi,exports.s=qi,exports.t=wn,exports.u=Gi,exports.v=En,exports.w=kn,exports.x=An,exports.y=Rn,exports.z=Nn;var e=require("@firebase/util"),t=require("@firebase/app"),n=require("@firebase/logger"),i=require("tslib"),r=require("@firebase/component");const s={PHONE:"phone"};exports.F=s;const o={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"};exports.o=o;const a={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password",FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PHONE:"phone",TWITTER:"twitter.com"};exports.S=a;const c={LINK:"link",REAUTHENTICATE:"reauthenticate",SIGN_IN:"signIn"};exports.O=c;const u={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function d(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance."}}function l(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}exports.A=u;const h=d;exports.B=h;const p=l;exports.C=p;const m=new e.ErrorFactory("auth","Firebase",l()),f={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized"};exports.D=f;const g=new n.Logger("@firebase/auth");function v(e,...i){g.logLevel<=n.LogLevel.ERROR&&g.error(`Auth (${t.SDK_VERSION}): ${e}`,...i)}function I(e,...t){throw w(e,...t)}function _(e,...t){return w(e,...t)}function y(t,n,i){const r=Object.assign(Object.assign({},p()),{[n]:i});return new e.ErrorFactory("auth","Firebase",r).create(n,{appName:t.name})}function T(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&I(e,"argument-error"),y(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function w(e,...t){if("string"!=typeof e){const n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return m.create(e,...t)}function E(e,t,...n){if(!e)throw w(t,...n)}function k(e){const t="INTERNAL ASSERTION FAILED: "+e;throw v(t),new Error(t)}function A(e,t){e||k(t)}const R=new Map;function N(e){A(e instanceof Function,"Expected a class definition");let t=R.get(e);return t?(A(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,R.set(e,t),t)}function b(n,i){const r=(0,t._getProvider)(n,"auth");if(r.isInitialized()){const t=r.getImmediate(),n=r.getOptions();if((0,e.deepEqual)(n,null!=i?i:{}))return t;I(t,"already-initialized")}return r.initialize({options:i})}function S(e,t){const n=(null==t?void 0:t.persistence)||[],i=(Array.isArray(n)?n:[n]).map(N);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(i,null==t?void 0:t.popupRedirectResolver)}function O(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function P(){return"http:"===D()||"https:"===D()}function D(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}function C(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(P()||(0,e.isBrowserExtension)()||"connection"in navigator))||navigator.onLine}function L(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}class M{constructor(t,n){this.shortDelay=t,this.longDelay=n,A(n>t,"Short delay should be less than long delay!"),this.isMobile=(0,e.isMobileCordova)()||(0,e.isReactNative)()}get(){return C()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function x(e,t){A(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class U{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 k("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 k("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 k("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}exports.aK=U;const F={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"},V=new M(3e4,6e4);function q(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function j(t,n,i,r,s={}){return H(t,s,async()=>{let s={},o={};r&&("GET"===n?o=r:s={body:JSON.stringify(r)});const a=(0,e.querystring)(Object.assign({key:t.config.apiKey},o)).slice(1),c=await t._getAdditionalHeaders();return c["Content-Type"]="application/json",t.languageCode&&(c["X-Firebase-Locale"]=t.languageCode),U.fetch()(G(t,t.config.apiHost,i,a),Object.assign({method:n,headers:c,referrerPolicy:"no-referrer"},s))})}async function H(t,n,i){t._canInitEmulator=!1;const r=Object.assign(Object.assign({},F),n);try{const n=new W(t),o=await Promise.race([i(),n.promise]);n.clearNetworkTimeout();const a=await o.json();if("needConfirmation"in a)throw K(t,"account-exists-with-different-credential",a);if(o.ok&&!("errorMessage"in a))return a;{const e=o.ok?a.errorMessage:a.error.message,[n,i]=e.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw K(t,"credential-already-in-use",a);if("EMAIL_EXISTS"===n)throw K(t,"email-already-in-use",a);if("USER_DISABLED"===n)throw K(t,"user-disabled",a);const s=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(i)throw y(t,s,i);I(t,s)}}catch(s){if(s instanceof e.FirebaseError)throw s;I(t,"internal-error",{message:String(s)})}}async function z(e,t,n,i,r={}){const s=await j(e,t,n,i,r);return"mfaPendingCredential"in s&&I(e,"multi-factor-auth-required",{_serverResponse:s}),s}function G(e,t,n,i){const r=`${t}${n}?${i}`;return e.config.emulator?x(e.config,r):`${e.config.apiScheme}://${r}`}class W{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(_(this.auth,"network-request-failed")),V.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function K(e,t,n){const i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);const r=_(e,t,i);return r.customData._tokenResponse=n,r}async function B(e,t){return j(e,"POST","/v1/accounts:delete",t)}async function J(e,t){return j(e,"POST","/v1/accounts:update",t)}async function $(e,t){return j(e,"POST","/v1/accounts:lookup",t)}function Y(e){if(e)try{const n=new Date(Number(e));if(!isNaN(n.getTime()))return n.toUTCString()}catch(t){}}function X(t,n=!1){return(0,e.getModularInstance)(t).getIdToken(n)}async function Q(t,n=!1){const i=(0,e.getModularInstance)(t),r=await i.getIdToken(n),s=ee(r);E(s&&s.exp&&s.auth_time&&s.iat,i.auth,"internal-error");const o="object"==typeof s.firebase?s.firebase:void 0,a=null==o?void 0:o.sign_in_provider;return{claims:s,token:r,authTime:Y(Z(s.auth_time)),issuedAtTime:Y(Z(s.iat)),expirationTime:Y(Z(s.exp)),signInProvider:a||null,signInSecondFactor:(null==o?void 0:o.sign_in_second_factor)||null}}function Z(e){return 1e3*Number(e)}function ee(t){const[n,i,r]=t.split(".");if(void 0===n||void 0===i||void 0===r)return v("JWT malformed, contained fewer than 3 sections"),null;try{const t=(0,e.base64Decode)(i);return t?JSON.parse(t):(v("Failed to decode base64 JWT payload"),null)}catch(s){return v("Caught error parsing JWT payload as JSON",null==s?void 0:s.toString()),null}}function te(e){const t=ee(e);return E(t,"internal-error"),E(void 0!==t.exp,"internal-error"),E(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function ne(t,n,i=!1){if(i)return n;try{return await n}catch(r){throw r instanceof e.FirebaseError&&ie(r)&&t.auth.currentUser===t&&await t.auth.signOut(),r}}function ie({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}class re{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class se{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Y(this.lastLoginAt),this.creationTime=Y(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function oe(e){var t;const n=e.auth,i=await e.getIdToken(),r=await ne(e,$(n,{idToken:i}));E(null==r?void 0:r.users.length,n,"internal-error");const s=r.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?ue(s.providerUserInfo):[],a=ce(e.providerData,o),c=e.isAnonymous,u=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!c&&u,l={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 se(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,l)}async function ae(t){const n=(0,e.getModularInstance)(t);await oe(n),await n.auth._persistUserIfCurrent(n),n.auth._notifyListenersIfCurrent(n)}function ce(e,t){return[...e.filter(e=>!t.some(t=>t.providerId===e.providerId)),...t]}function ue(e){return e.map(e=>{var{providerId:t}=e,n=(0,i.__rest)(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})}async function de(t,n){const i=await H(t,{},async()=>{const i=(0,e.querystring)({grant_type:"refresh_token",refresh_token:n}).slice(1),{tokenApiHost:r,apiKey:s}=t.config,o=G(t,r,"/v1/token",`key=${s}`),a=await t._getAdditionalHeaders();return a["Content-Type"]="application/x-www-form-urlencoded",U.fetch()(o,{method:"POST",headers:a,body:i})});return{accessToken:i.access_token,expiresIn:i.expires_in,refreshToken:i.refresh_token}}class le{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){E(e.idToken,"internal-error"),E(void 0!==e.idToken,"internal-error"),E(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):te(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e,t=!1){return E(!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:i,expiresIn:r}=await de(e,t);this.updateTokensAndExpiration(n,i,Number(r))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:i,expirationTime:r}=t,s=new le;return n&&(E("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),i&&(E("string"==typeof i,"internal-error",{appName:e}),s.accessToken=i),r&&(E("number"==typeof r,"internal-error",{appName:e}),s.expirationTime=r),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new le,this.toJSON())}_performRefresh(){return k("not implemented")}}function he(e,t){E("string"==typeof e||void 0===e,"internal-error",{appName:t})}class pe{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,s=(0,i.__rest)(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new re(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new se(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await ne(this,this.stsTokenManager.getToken(this.auth,e));return E(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return Q(this,e)}reload(){return ae(this)}_assign(e){this!==e&&(E(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new pe(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){E(!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 oe(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await ne(this,B(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,i,r,s,o,a,c,u;const d=null!==(n=t.displayName)&&void 0!==n?n:void 0,l=null!==(i=t.email)&&void 0!==i?i:void 0,h=null!==(r=t.phoneNumber)&&void 0!==r?r:void 0,p=null!==(s=t.photoURL)&&void 0!==s?s:void 0,m=null!==(o=t.tenantId)&&void 0!==o?o:void 0,f=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=t.createdAt)&&void 0!==c?c:void 0,v=null!==(u=t.lastLoginAt)&&void 0!==u?u:void 0,{uid:I,emailVerified:_,isAnonymous:y,providerData:T,stsTokenManager:w}=t;E(I&&w,e,"internal-error");const k=le.fromJSON(this.name,w);E("string"==typeof I,e,"internal-error"),he(d,e.name),he(l,e.name),E("boolean"==typeof _,e,"internal-error"),E("boolean"==typeof y,e,"internal-error"),he(h,e.name),he(p,e.name),he(m,e.name),he(f,e.name),he(g,e.name),he(v,e.name);const A=new pe({uid:I,auth:e,email:l,emailVerified:_,displayName:d,isAnonymous:y,photoURL:p,phoneNumber:h,tenantId:m,stsTokenManager:k,createdAt:g,lastLoginAt:v});return T&&Array.isArray(T)&&(A.providerData=T.map(e=>Object.assign({},e))),f&&(A._redirectEventId=f),A}static async _fromIdTokenResponse(e,t,n=!1){const i=new le;i.updateFromServerResponse(t);const r=new pe({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await oe(r),r}}exports.aF=pe;class me{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){}}me.type="NONE";const fe=me;function ge(e,t,n){return`firebase:${e}:${t}:${n}`}exports.L=fe;class ve{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:i,name:r}=this.auth;this.fullUserKey=ge(this.userKey,i.apiKey,r),this.fullPersistenceKey=ge("persistence",i.apiKey,r),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?pe._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 ve(N(fe),e,n);const i=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let r=i[0]||N(fe);const s=ge(n,e.config.apiKey,e.name);let o=null;for(const u of t)try{const t=await u._get(s);if(t){const n=pe._fromJSON(e,t);u!==r&&(o=n),r=u;break}}catch(c){}const a=i.filter(e=>e._shouldAllowMigration);return r._shouldAllowMigration&&a.length?(r=a[0],o&&await r._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==r)try{await e._remove(s)}catch(c){}})),new ve(r,e,n)):new ve(r,e,n)}}function Ie(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(we(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(_e(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(ke(t))return"Blackberry";if(Ae(t))return"Webos";if(ye(t))return"Safari";if((t.includes("chrome/")||Te(t))&&!t.includes("edge/"))return"Chrome";if(Ee(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 _e(t=(0,e.getUA)()){return/firefox\//i.test(t)}function ye(t=(0,e.getUA)()){const n=t.toLowerCase();return n.includes("safari/")&&!n.includes("chrome/")&&!n.includes("crios/")&&!n.includes("android")}function Te(t=(0,e.getUA)()){return/crios\//i.test(t)}function we(t=(0,e.getUA)()){return/iemobile/i.test(t)}function Ee(t=(0,e.getUA)()){return/android/i.test(t)}function ke(t=(0,e.getUA)()){return/blackberry/i.test(t)}function Ae(t=(0,e.getUA)()){return/webos/i.test(t)}function Re(t=(0,e.getUA)()){return/iphone|ipad|ipod/i.test(t)||/macintosh/i.test(t)&&/mobile/i.test(t)}function Ne(t=(0,e.getUA)()){return/(iPad|iPhone|iPod).*OS 7_\d/i.test(t)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(t)}function be(t=(0,e.getUA)()){var n;return Re(t)&&!!(null===(n=window.navigator)||void 0===n?void 0:n.standalone)}function Se(){return(0,e.isIE)()&&10===document.documentMode}function Oe(t=(0,e.getUA)()){return Re(t)||Ee(t)||Ae(t)||ke(t)||/windows phone/i.test(t)||we(t)}function Pe(){try{return!(!window||window===window.top)}catch(e){return!1}}function De(n,i=[]){let r;switch(n){case"Browser":r=Ie((0,e.getUA)());break;case"Worker":r=`${Ie((0,e.getUA)())}-${n}`;break;default:r=n}const s=i.length?i.join(","):"FirebaseCore-web";return`${r}/JsCore/${t.SDK_VERSION}/${s}`}class Ce{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise((n,i)=>{try{n(e(t))}catch(r){i(r)}});n.onAbort=t,this.queue.push(n);const i=this.queue.length-1;return()=>{this.queue[i]=(()=>Promise.resolve())}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(n){t.reverse();for(const e of t)try{e()}catch(i){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==n?void 0:n.message})}}}class Le{constructor(e,t,n){this.app=e,this.heartbeatServiceProvider=t,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new xe(this),this.idTokenSubscription=new xe(this),this.beforeStateQueue=new Ce(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=m,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=N(t)),this._initializationPromise=this.queue(async()=>{var n,i;if(!this._deleted&&(this.persistenceManager=await ve.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(r){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void(await this.currentUser.getIdToken())):void(await this._updateCurrentUser(e,!0)):void 0}async initializeCurrentUser(e){var t;const n=await this.assertedPersistence.getCurrentUser();let i=n,r=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(e);n&&n!==s||null==o||!o.user||(i=o.user,r=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(r)try{await this.beforeStateQueue.runMiddleware(i)}catch(s){i=n,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(s))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return E(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(n){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await oe(e)}catch(t){if("auth/network-request-failed"!==(null==t?void 0:t.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=L()}async _delete(){this._deleted=!0}async updateCurrentUser(t){const n=t?(0,e.getModularInstance)(t):null;return n&&E(n.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(n&&n._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&E(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(N(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(t){this._errorFactory=new e.ErrorFactory("auth","Firebase",t())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&N(e)||this._popupRedirectResolver;E(t,this,"argument-error"),this.redirectPersistenceManager=await ve.create(this,[N(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};const r="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return E(s,this,"internal-error"),s.then(()=>r(this.currentUser)),"function"==typeof t?e.addObserver(t,n,i):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 E(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=De(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());return n&&(t["X-Firebase-Client"]=n),t}}function Me(t){return(0,e.getModularInstance)(t)}exports.aG=Le;class xe{constructor(t){this.auth=t,this.observer=null,this.addObserver=(0,e.createSubscribe)(e=>this.observer=e)}get next(){return E(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function Ue(e,t,n){const i=Me(e);E(i._canInitEmulator,i,"emulator-config-failed"),E(/^https?:\/\//.test(t),i,"invalid-emulator-scheme");const r=!!(null==n?void 0:n.disableWarnings),s=Fe(t),{host:o,port:a}=Ve(t),c=null===a?"":`:${a}`;i.config.emulator={url:`${s}//${o}${c}/`},i.settings.appVerificationDisabledForTesting=!0,i.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:r})}),r||je()}function Fe(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Ve(e){const t=Fe(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const i=n[2].split("@").pop()||"",r=/^(\[[^\]]+\])(:|$)/.exec(i);if(r){const e=r[1];return{host:e,port:qe(i.substr(e.length+1))}}{const[e,t]=i.split(":");return{host:e,port:qe(t)}}}function qe(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}function je(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}class He{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return k("not implemented")}_getIdTokenResponse(e){return k("not implemented")}_linkToIdToken(e,t){return k("not implemented")}_getReauthenticationResolver(e){return k("not implemented")}}async function ze(e,t){return j(e,"POST","/v1/accounts:resetPassword",q(e,t))}async function Ge(e,t){return j(e,"POST","/v1/accounts:update",t)}async function We(e,t){return j(e,"POST","/v1/accounts:update",q(e,t))}async function Ke(e,t){return z(e,"POST","/v1/accounts:signInWithPassword",q(e,t))}async function Be(e,t){return j(e,"POST","/v1/accounts:sendOobCode",q(e,t))}async function Je(e,t){return Be(e,t)}async function $e(e,t){return Be(e,t)}async function Ye(e,t){return Be(e,t)}async function Xe(e,t){return Be(e,t)}async function Qe(e,t){return z(e,"POST","/v1/accounts:signInWithEmailLink",q(e,t))}async function Ze(e,t){return z(e,"POST","/v1/accounts:signInWithEmailLink",q(e,t))}exports.H=He;class et extends He{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new et(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new et(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 Ke(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return Qe(e,{email:this._email,oobCode:this._password});default:I(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ge(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return Ze(e,{idToken:t,email:this._email,oobCode:this._password});default:I(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function tt(e,t){return z(e,"POST","/v1/accounts:signInWithIdp",q(e,t))}exports.I=et;const nt="http://localhost";class it extends He{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new it(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):I("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,s=(0,i.__rest)(t,["providerId","signInMethod"]);if(!n||!r)return null;const o=new it(n,r);return o.idToken=s.idToken||void 0,o.accessToken=s.accessToken||void 0,o.secret=s.secret,o.nonce=s.nonce,o.pendingToken=s.pendingToken||null,o}_getIdTokenResponse(e){return tt(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,tt(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,tt(e,t)}buildRequest(){const t={requestUri:nt,returnSecureToken:!0};if(this.pendingToken)t.pendingToken=this.pendingToken;else{const n={};this.idToken&&(n.id_token=this.idToken),this.accessToken&&(n.access_token=this.accessToken),this.secret&&(n.oauth_token_secret=this.secret),n.providerId=this.providerId,this.nonce&&!this.pendingToken&&(n.nonce=this.nonce),t.postBody=(0,e.querystring)(n)}return t}}async function rt(e,t){return j(e,"POST","/v1/accounts:sendVerificationCode",q(e,t))}async function st(e,t){return z(e,"POST","/v1/accounts:signInWithPhoneNumber",q(e,t))}async function ot(e,t){const n=await z(e,"POST","/v1/accounts:signInWithPhoneNumber",q(e,t));if(n.temporaryProof)throw K(e,"account-exists-with-different-credential",n);return n}exports.J=it;const at={USER_NOT_FOUND:"user-not-found"};async function ct(e,t){return z(e,"POST","/v1/accounts:signInWithPhoneNumber",q(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),at)}class ut extends He{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new ut({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new ut({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return st(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return ot(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return ct(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:i}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}=e;return n||t||i||r?new ut({verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}):null}}function dt(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}}function lt(t){const n=(0,e.querystringDecode)((0,e.extractQuerystring)(t)).link,i=n?(0,e.querystringDecode)((0,e.extractQuerystring)(n)).deep_link_id:null,r=(0,e.querystringDecode)((0,e.extractQuerystring)(t)).deep_link_id;return(r?(0,e.querystringDecode)((0,e.extractQuerystring)(r)).link:null)||r||i||n||t}exports.K=ut;class ht{constructor(t){var n,i,r,s,o,a;const c=(0,e.querystringDecode)((0,e.extractQuerystring)(t)),u=null!==(n=c.apiKey)&&void 0!==n?n:null,d=null!==(i=c.oobCode)&&void 0!==i?i:null,l=dt(null!==(r=c.mode)&&void 0!==r?r:null);E(u&&d&&l,"argument-error"),this.apiKey=u,this.operation=l,this.code=d,this.continueUrl=null!==(s=c.continueUrl)&&void 0!==s?s:null,this.languageCode=null!==(o=c.languageCode)&&void 0!==o?o:null,this.tenantId=null!==(a=c.tenantId)&&void 0!==a?a:null}static parseLink(e){const t=lt(e);try{return new ht(t)}catch(n){return null}}}function pt(e){return ht.parseLink(e)}exports.ad=ht;class mt{constructor(){this.providerId=mt.PROVIDER_ID}static credential(e,t){return et._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=ht.parseLink(t);return E(n,"argument-error"),et._fromEmailAndCode(e,n.code,n.tenantId)}}exports.M=mt,mt.PROVIDER_ID="password",mt.EMAIL_PASSWORD_SIGN_IN_METHOD="password",mt.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class ft{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 gt extends ft{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class vt extends gt{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return E("providerId"in t&&"signInMethod"in t,"argument-error"),it._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return E(e.idToken||e.accessToken,"argument-error"),it._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return vt.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return vt.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:i,pendingToken:r,nonce:s,providerId:o}=e;if(!(n||i||t||r))return null;if(!o)return null;try{return new vt(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:r})}catch(a){return null}}}exports.U=vt;class It extends gt{constructor(){super("facebook.com")}static credential(e){return it._fromParams({providerId:It.PROVIDER_ID,signInMethod:It.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return It.credentialFromTaggedObject(e)}static credentialFromError(e){return It.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return It.credential(e.oauthAccessToken)}catch(t){return null}}}exports.N=It,It.FACEBOOK_SIGN_IN_METHOD="facebook.com",It.PROVIDER_ID="facebook.com";class _t extends gt{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return it._fromParams({providerId:_t.PROVIDER_ID,signInMethod:_t.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return _t.credentialFromTaggedObject(e)}static credentialFromError(e){return _t.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return _t.credential(t,n)}catch(i){return null}}}exports.Q=_t,_t.GOOGLE_SIGN_IN_METHOD="google.com",_t.PROVIDER_ID="google.com";class yt extends gt{constructor(){super("github.com")}static credential(e){return it._fromParams({providerId:yt.PROVIDER_ID,signInMethod:yt.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return yt.credentialFromTaggedObject(e)}static credentialFromError(e){return yt.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return yt.credential(e.oauthAccessToken)}catch(t){return null}}}exports.T=yt,yt.GITHUB_SIGN_IN_METHOD="github.com",yt.PROVIDER_ID="github.com";const Tt="http://localhost";class wt extends He{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return tt(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,tt(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,tt(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i,pendingToken:r}=t;return n&&i&&r&&n===i?new wt(n,r):null}static _create(e,t){return new wt(e,t)}buildRequest(){return{requestUri:Tt,returnSecureToken:!0,pendingToken:this.pendingToken}}}exports.aL=wt;const Et="saml.";class kt extends ft{constructor(e){E(e.startsWith(Et),"argument-error"),super(e)}static credentialFromResult(e){return kt.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return kt.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=wt.fromJSON(e);return E(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return wt._create(n,t)}catch(i){return null}}}exports.V=kt;class At extends gt{constructor(){super("twitter.com")}static credential(e,t){return it._fromParams({providerId:At.PROVIDER_ID,signInMethod:At.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return At.credentialFromTaggedObject(e)}static credentialFromError(e){return At.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return At.credential(t,n)}catch(i){return null}}}async function Rt(e,t){return z(e,"POST","/v1/accounts:signUp",q(e,t))}exports.W=At,At.TWITTER_SIGN_IN_METHOD="twitter.com",At.PROVIDER_ID="twitter.com";class Nt{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){const r=await pe._fromIdTokenResponse(e,n,i),s=bt(n);return new Nt({user:r,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const i=bt(n);return new Nt({user:e,providerId:i,_tokenResponse:n,operationType:t})}}function bt(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}async function St(e){var t;const n=Me(e);if(await n._initializationPromise,null===(t=n.currentUser)||void 0===t?void 0:t.isAnonymous)return new Nt({user:n.currentUser,providerId:null,operationType:"signIn"});const i=await Rt(n,{returnSecureToken:!0}),r=await Nt._fromIdTokenResponse(n,"signIn",i,!0);return await n._updateCurrentUser(r.user),r}class Ot extends e.FirebaseError{constructor(e,t,n,i){var r;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,Ot.prototype),this.customData={appName:e.name,tenantId:null!==(r=e.tenantId)&&void 0!==r?r:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new Ot(e,t,n,i)}}function Pt(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch(n=>{if("auth/multi-factor-auth-required"===n.code)throw Ot._fromErrorAndOperation(e,n,t,i);throw n})}function Dt(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Ct(t,n){const i=(0,e.getModularInstance)(t);await Mt(!0,i,n);const{providerUserInfo:r}=await J(i.auth,{idToken:await i.getIdToken(),deleteProvider:[n]}),s=Dt(r||[]);return i.providerData=i.providerData.filter(e=>s.has(e.providerId)),s.has("phone")||(i.phoneNumber=null),await i.auth._persistUserIfCurrent(i),i}async function Lt(e,t,n=!1){const i=await ne(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Nt._forOperation(e,"link",i)}async function Mt(e,t,n){await oe(t);const i=!1===e?"provider-already-linked":"no-such-provider";E(Dt(t.providerData).has(n)===e,t.auth,i)}async function xt(e,t,n=!1){const{auth:i}=e;try{const s=await ne(e,Pt(i,"reauthenticate",t,e),n);E(s.idToken,i,"internal-error");const o=ee(s.idToken);E(o,i,"internal-error");const{sub:a}=o;return E(e.uid===a,i,"user-mismatch"),Nt._forOperation(e,"reauthenticate",s)}catch(r){throw"auth/user-not-found"===(null==r?void 0:r.code)&&I(i,"user-mismatch"),r}}async function Ut(e,t,n=!1){const i=await Pt(e,"signIn",t),r=await Nt._fromIdTokenResponse(e,"signIn",i);return n||await e._updateCurrentUser(r.user),r}async function Ft(e,t){return Ut(Me(e),t)}async function Vt(t,n){const i=(0,e.getModularInstance)(t);return await Mt(!1,i,n.providerId),Lt(i,n)}async function qt(t,n){return xt((0,e.getModularInstance)(t),n)}async function jt(e,t){return z(e,"POST","/v1/accounts:signInWithCustomToken",q(e,t))}async function Ht(e,t){const n=Me(e),i=await jt(n,{token:t,returnSecureToken:!0}),r=await Nt._fromIdTokenResponse(n,"signIn",i);return await n._updateCurrentUser(r.user),r}class zt{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?Gt._fromServerResponse(e,t):I(e,"internal-error")}}class Gt extends zt{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new Gt(t)}}function Wt(e,t,n){var i;E((null===(i=n.url)||void 0===i?void 0:i.length)>0,e,"invalid-continue-uri"),E(void 0===n.dynamicLinkDomain||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(E(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(E(n.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function Kt(t,n,i){const r=(0,e.getModularInstance)(t),s={requestType:"PASSWORD_RESET",email:n};i&&Wt(r,s,i),await $e(r,s)}async function Bt(t,n,i){await ze((0,e.getModularInstance)(t),{oobCode:n,newPassword:i})}async function Jt(t,n){await We((0,e.getModularInstance)(t),{oobCode:n})}async function $t(t,n){const i=(0,e.getModularInstance)(t),r=await ze(i,{oobCode:n}),s=r.requestType;switch(E(s,i,"internal-error"),s){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":E(r.newEmail,i,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":E(r.mfaInfo,i,"internal-error");default:E(r.email,i,"internal-error")}let o=null;return r.mfaInfo&&(o=zt._fromServerResponse(Me(i),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:o},operation:s}}async function Yt(t,n){const{data:i}=await $t((0,e.getModularInstance)(t),n);return i.email}async function Xt(e,t,n){const i=Me(e),r=await Rt(i,{returnSecureToken:!0,email:t,password:n}),s=await Nt._fromIdTokenResponse(i,"signIn",r);return await i._updateCurrentUser(s.user),s}function Qt(t,n,i){return Ft((0,e.getModularInstance)(t),mt.credential(n,i))}async function Zt(t,n,i){const r=(0,e.getModularInstance)(t),s={requestType:"EMAIL_SIGNIN",email:n};E(i.handleCodeInApp,r,"argument-error"),i&&Wt(r,s,i),await Ye(r,s)}function en(e,t){const n=ht.parseLink(t);return"EMAIL_SIGNIN"===(null==n?void 0:n.operation)}async function tn(t,n,i){const r=(0,e.getModularInstance)(t),s=mt.credentialWithLink(n,i||O());return E(s._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),Ft(r,s)}async function nn(e,t){return j(e,"POST","/v1/accounts:createAuthUri",q(e,t))}async function rn(t,n){const i={identifier:n,continueUri:P()?O():"http://localhost"},{signinMethods:r}=await nn((0,e.getModularInstance)(t),i);return r||[]}async function sn(t,n){const i=(0,e.getModularInstance)(t),r={requestType:"VERIFY_EMAIL",idToken:await t.getIdToken()};n&&Wt(i.auth,r,n);const{email:s}=await Je(i.auth,r);s!==t.email&&await t.reload()}async function on(t,n,i){const r=(0,e.getModularInstance)(t),s={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await t.getIdToken(),newEmail:n};i&&Wt(r.auth,s,i);const{email:o}=await Xe(r.auth,s);o!==t.email&&await t.reload()}async function an(e,t){return j(e,"POST","/v1/accounts:update",t)}async function cn(t,{displayName:n,photoURL:i}){if(void 0===n&&void 0===i)return;const r=(0,e.getModularInstance)(t),s={idToken:await r.getIdToken(),displayName:n,photoUrl:i,returnSecureToken:!0},o=await ne(r,an(r.auth,s));r.displayName=o.displayName||null,r.photoURL=o.photoUrl||null;const a=r.providerData.find(({providerId:e})=>"password"===e);a&&(a.displayName=r.displayName,a.photoURL=r.photoURL),await r._updateTokensIfNecessary(o)}function un(t,n){return ln((0,e.getModularInstance)(t),n,null)}function dn(t,n){return ln((0,e.getModularInstance)(t),null,n)}async function ln(e,t,n){const{auth:i}=e,r={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(r.email=t),n&&(r.password=n);const s=await ne(e,Ge(i,r));await e._updateTokensIfNecessary(s,!0)}function hn(e){var t,n;if(!e)return null;const{providerId:i}=e,r=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},s=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!i&&(null==e?void 0:e.idToken)){const i=null===(n=null===(t=ee(e.idToken))||void 0===t?void 0:t.firebase)||void 0===n?void 0:n.sign_in_provider;if(i){return new pn(s,"anonymous"!==i&&"custom"!==i?i:null)}}if(!i)return null;switch(i){case"facebook.com":return new fn(s,r);case"github.com":return new gn(s,r);case"google.com":return new vn(s,r);case"twitter.com":return new In(s,r,e.screenName||null);case"custom":case"anonymous":return new pn(s,null);default:return new pn(s,i,r)}}class pn{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class mn extends pn{constructor(e,t,n,i){super(e,t,n),this.username=i}}class fn extends pn{constructor(e,t){super(e,"facebook.com",t)}}class gn extends mn{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class vn extends pn{constructor(e,t){super(e,"google.com",t)}}class In extends mn{constructor(e,t,n){super(e,"twitter.com",t,n)}}function _n(e){const{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:hn(n)}function yn(t,n){return(0,e.getModularInstance)(t).setPersistence(n)}function Tn(t,n,i,r){return(0,e.getModularInstance)(t).onIdTokenChanged(n,i,r)}function wn(t,n,i){return(0,e.getModularInstance)(t).beforeAuthStateChanged(n,i)}function En(t,n,i,r){return(0,e.getModularInstance)(t).onAuthStateChanged(n,i,r)}function kn(t){(0,e.getModularInstance)(t).useDeviceLanguage()}function An(t,n){return(0,e.getModularInstance)(t).updateCurrentUser(n)}function Rn(t){return(0,e.getModularInstance)(t).signOut()}async function Nn(t){return(0,e.getModularInstance)(t).delete()}class bn{constructor(e,t,n){this.type=e,this.credential=t,this.auth=n}static _fromIdtoken(e,t){return new bn("enroll",e,t)}static _fromMfaPendingCredential(e){return new bn("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t,n;if(null==e?void 0:e.multiFactorSession){if(null===(t=e.multiFactorSession)||void 0===t?void 0:t.pendingCredential)return bn._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null===(n=e.multiFactorSession)||void 0===n?void 0:n.idToken)return bn._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Sn{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,t){const n=Me(e),i=t.customData._serverResponse,r=(i.mfaInfo||[]).map(e=>zt._fromServerResponse(n,e));E(i.mfaPendingCredential,n,"internal-error");const s=bn._fromMfaPendingCredential(i.mfaPendingCredential);return new Sn(s,r,async e=>{const r=await e._process(n,s);delete i.mfaInfo,delete i.mfaPendingCredential;const o=Object.assign(Object.assign({},i),{idToken:r.idToken,refreshToken:r.refreshToken});switch(t.operationType){case"signIn":const e=await Nt._fromIdTokenResponse(n,t.operationType,o);return await n._updateCurrentUser(e.user),e;case"reauthenticate":return E(t.user,n,"internal-error"),Nt._forOperation(t.user,t.operationType,o);default:I(n,"internal-error")}})}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function On(t,n){var i;const r=(0,e.getModularInstance)(t),s=n;return E(n.customData.operationType,r,"argument-error"),E(null===(i=s.customData._serverResponse)||void 0===i?void 0:i.mfaPendingCredential,r,"argument-error"),Sn._fromError(r,s)}function Pn(e,t){return j(e,"POST","/v2/accounts/mfaEnrollment:start",q(e,t))}function Dn(e,t){return j(e,"POST","/v2/accounts/mfaEnrollment:finalize",q(e,t))}function Cn(e,t){return j(e,"POST","/v2/accounts/mfaEnrollment:withdraw",q(e,t))}class Ln{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload(t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map(t=>zt._fromServerResponse(e.auth,t)))})}static _fromUser(e){return new Ln(e)}async getSession(){return bn._fromIdtoken(await this.user.getIdToken(),this.user.auth)}async enroll(e,t){const n=e,i=await this.getSession(),r=await ne(this.user,n._process(this.user.auth,i,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,n=await this.user.getIdToken();try{const e=await ne(this.user,Cn(this.user.auth,{idToken:n,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(i){throw i}}}const Mn=new WeakMap;function xn(t){const n=(0,e.getModularInstance)(t);return Mn.has(n)||Mn.set(n,Ln._fromUser(n)),Mn.get(n)}const Un="__sak";class Fn{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Un,"1"),this.storage.removeItem(Un),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()}}function Vn(){const t=(0,e.getUA)();return ye(t)||Re(t)}const qn=1e3,jn=10;class Hn extends Fn{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=((e,t)=>this.onStorageEvent(e,t)),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=Vn()&&Pe(),this.fallbackToPolling=Oe(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)});const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(n);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const i=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},r=this.storage.getItem(n);Se()&&r!==e.newValue&&e.newValue!==e.oldValue?setTimeout(i,jn):i()}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const i of Array.from(n))i(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)})},qn)}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]}}Hn.type="LOCAL";const zn=Hn;exports.b=zn;class Gn extends Fn{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Gn.type="SESSION";const Wn=Gn;function Kn(e){return Promise.all(e.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(t){return{fulfilled:!1,reason:t}}}))}exports.a=Wn;class Bn{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 Bn(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:i,data:r}=t.data,s=this.handlersMap[i];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:i});const o=Array.from(s).map(async e=>e(t.origin,r)),a=await Kn(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:i,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function Jn(e="",t=10){let n="";for(let i=0;i<t;i++)n+=Math.floor(10*Math.random());return e+n}Bn.receivers=[];class $n{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,n=50){const i="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!i)throw new Error("connection_unavailable");let r,s;return new Promise((o,a)=>{const c=Jn("",20);i.port1.start();const u=setTimeout(()=>{a(new Error("unsupported_event"))},n);s={messageChannel:i,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),r=setTimeout(()=>{a(new Error("timeout"))},3e3);break;case"done":clearTimeout(r),o(t.data.response);break;default:clearTimeout(u),clearTimeout(r),a(new Error("invalid_response"))}}},this.handlers.add(s),i.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[i.port2])}).finally(()=>{s&&this.removeMessageHandler(s)})}}function Yn(){return window}function Xn(e){Yn().location.href=e}function Qn(){return void 0!==Yn().WorkerGlobalScope&&"function"==typeof Yn().importScripts}async function Zn(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}function ei(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}function ti(){return Qn()?self:null}const ni="firebaseLocalStorageDb",ii=1,ri="firebaseLocalStorage",si="fbase_key";class oi{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 ai(e,t){return e.transaction([ri],t?"readwrite":"readonly").objectStore(ri)}function ci(){const e=indexedDB.deleteDatabase(ni);return new oi(e).toPromise()}function ui(){const e=indexedDB.open(ni,ii);return new Promise((t,n)=>{e.addEventListener("error",()=>{n(e.error)}),e.addEventListener("upgradeneeded",()=>{const t=e.result;try{t.createObjectStore(ri,{keyPath:si})}catch(i){n(i)}}),e.addEventListener("success",async()=>{const n=e.result;n.objectStoreNames.contains(ri)?t(n):(n.close(),await ci(),t(await ui()))})})}async function di(e,t,n){const i=ai(e,!0).put({[si]:t,value:n});return new oi(i).toPromise()}async function li(e,t){const n=ai(e,!1).get(t),i=await new oi(n).toPromise();return void 0===i?null:i.value}function hi(e,t){const n=ai(e,!0).delete(t);return new oi(n).toPromise()}const pi=800,mi=3;class fi{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db?this.db:(this.db=await ui(),this.db)}async _withRetries(e){let t=0;for(;;)try{const i=await this._openDb();return await e(i)}catch(n){if(t++>mi)throw n;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Qn()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Bn._getInstance(ti()),this.receiver._subscribe("keyChanged",async(e,t)=>{return{keyProcessed:(await this._poll()).includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t;if(this.activeServiceWorker=await Zn(),!this.activeServiceWorker)return;this.sender=new $n(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&&ei()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const t=await ui();return await di(t,Un,"1"),await hi(t,Un),!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=>di(n,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){const t=await this._withRetries(t=>li(t,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>hi(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){const e=await this._withRetries(e=>{const t=ai(e,!1).getAll();return new oi(t).toPromise()});if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:i,value:r}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(r)&&(this.notifyListeners(i,r),t.push(i));for(const i of Object.keys(this.localCache))this.localCache[i]&&!n.has(i)&&(this.notifyListeners(i,null),t.push(i));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const i of Array.from(n))i(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),pi)}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()}}fi.type="LOCAL";const gi=fi;function vi(e,t){return j(e,"POST","/v2/accounts/mfaSignIn:start",q(e,t))}function Ii(e,t){return j(e,"POST","/v2/accounts/mfaSignIn:finalize",q(e,t))}async function _i(e){return(await j(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}function yi(){var e,t;return null!==(t=null===(e=document.getElementsByTagName("head"))||void 0===e?void 0:e[0])&&void 0!==t?t:document}function Ti(e){return new Promise((t,n)=>{const i=document.createElement("script");i.setAttribute("src",e),i.onload=t,i.onerror=(e=>{const t=_("internal-error");t.customData=e,n(t)}),i.type="text/javascript",i.charset="UTF-8",yi().appendChild(i)})}function wi(e){return`__${e}${Math.floor(1e6*Math.random())}`}exports.i=gi;const Ei=500,ki=6e4,Ai=1e12;class Ri{constructor(e){this.auth=e,this.counter=Ai,this._widgets=new Map}render(e,t){const n=this.counter;return this._widgets.set(n,new Ni(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t;const n=e||Ai;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;const n=e||Ai;return(null===(t=this._widgets.get(n))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;const n=e||Ai;return null===(t=this._widgets.get(n))||void 0===t||t.execute(),""}}class Ni{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=(()=>{this.execute()});const i="string"==typeof e?document.getElementById(e):e;E(i,"argument-error",{appName:t}),this.container=i,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=bi(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(n){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(n){}this.isVisible&&this.execute()},ki)},Ei))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}function bi(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let i=0;i<e;i++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}const Si=wi("rcb"),Oi=new M(3e4,6e4),Pi="https://www.google.com/recaptcha/api.js?";class Di{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!(null===(e=Yn().grecaptcha)||void 0===e?void 0:e.render)}load(t,n=""){return E(Ci(n),t,"argument-error"),this.shouldResolveImmediately(n)?Promise.resolve(Yn().grecaptcha):new Promise((i,r)=>{const s=Yn().setTimeout(()=>{r(_(t,"network-request-failed"))},Oi.get());Yn()[Si]=(()=>{Yn().clearTimeout(s),delete Yn()[Si];const e=Yn().grecaptcha;if(!e)return void r(_(t,"internal-error"));const o=e.render;e.render=((e,t)=>{const n=o(e,t);return this.counter++,n}),this.hostLanguage=n,i(e)}),Ti(`${Pi}?${(0,e.querystring)({onload:Si,render:"explicit",hl:n})}`).catch(()=>{clearTimeout(s),r(_(t,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!!(null===(t=Yn().grecaptcha)||void 0===t?void 0:t.render)&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}function Ci(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}class Li{async load(e){return new Ri(e)}clearedOneInstance(){}}const Mi="recaptcha",xi={theme:"light",type:"image"};class Ui{constructor(e,t=Object.assign({},xi),n){this.parameters=t,this.type=Mi,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Me(n),this.isInvisible="invisible"===this.parameters.size,E("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");const i="string"==typeof e?document.getElementById(e):e;E(i,this.auth,"argument-error"),this.container=i,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new Li:new Di,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha(),n=t.getResponse(e);return n||new Promise(n=>{const i=e=>{e&&(this.tokenChangeListeners.delete(i),n(e))};this.tokenChangeListeners.add(i),this.isInvisible&&t.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise?this.renderPromise:(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){E(!this.parameters.sitekey,this.auth,"argument-error"),E(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),E("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof e)e(t);else if("string"==typeof e){const n=Yn()[e];"function"==typeof n&&n(t)}}}assertNotDestroyed(){E(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){E(P()&&!Qn(),this.auth,"internal-error"),await Fi(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await _i(this.auth);E(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return E(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}function Fi(){let e=null;return new Promise(t=>{"complete"!==document.readyState?(e=(()=>t()),window.addEventListener("load",e)):t()}).catch(t=>{throw e&&window.removeEventListener("load",e),t})}exports.R=Ui;class Vi{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=ut._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function qi(t,n,i){const r=Me(t),s=await zi(r,n,(0,e.getModularInstance)(i));return new Vi(s,e=>Ft(r,e))}async function ji(t,n,i){const r=(0,e.getModularInstance)(t);await Mt(!1,r,"phone");const s=await zi(r.auth,n,(0,e.getModularInstance)(i));return new Vi(s,e=>Vt(r,e))}async function Hi(t,n,i){const r=(0,e.getModularInstance)(t),s=await zi(r.auth,n,(0,e.getModularInstance)(i));return new Vi(s,e=>qt(r,e))}async function zi(e,t,n){var i;const r=await n.verify();try{let s;if(E("string"==typeof r,e,"argument-error"),E(n.type===Mi,e,"argument-error"),"session"in(s="string"==typeof t?{phoneNumber:t}:t)){const t=s.session;if("phoneNumber"in s){return E("enroll"===t.type,e,"internal-error"),(await Pn(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:r}})).phoneSessionInfo.sessionInfo}{E("signin"===t.type,e,"internal-error");const n=(null===(i=s.multiFactorHint)||void 0===i?void 0:i.uid)||s.multiFactorUid;return E(n,e,"missing-multi-factor-info"),(await vi(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:r}})).phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await rt(e,{phoneNumber:s.phoneNumber,recaptchaToken:r});return t}}finally{n._reset()}}async function Gi(t,n){await Lt((0,e.getModularInstance)(t),n)}class Wi{constructor(e){this.providerId=Wi.PROVIDER_ID,this.auth=Me(e)}verifyPhoneNumber(t,n){return zi(this.auth,t,(0,e.getModularInstance)(n))}static credential(e,t){return ut._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Wi.credentialFromTaggedObject(t)}static credentialFromError(e){return Wi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?ut._fromTokenResponse(t,n):null}}function Ki(e,t){return t?N(t):(E(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}exports.P=Wi,Wi.PROVIDER_ID="phone",Wi.PHONE_SIGN_IN_METHOD="phone";class Bi extends He{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return tt(e,this._buildIdpRequest())}_linkToIdToken(e,t){return tt(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return tt(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 Ji(e){return Ut(e.auth,new Bi(e),e.bypassAuthState)}function $i(e){const{auth:t,user:n}=e;return E(n,t,"internal-error"),xt(n,new Bi(e),e.bypassAuthState)}async function Yi(e){const{auth:t,user:n}=e;return E(n,t,"internal-error"),Lt(n,new Bi(e),e.bypassAuthState)}class Xi{constructor(e,t,n,i,r=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(n){this.reject(n)}})}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:i,tenantId:r,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:r||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(c){this.reject(c)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Ji;case"linkViaPopup":case"linkViaRedirect":return Yi;case"reauthViaPopup":case"reauthViaRedirect":return $i;default:I(this.auth,"internal-error")}}resolve(e){A(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){A(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 Qi=new M(2e3,1e4);async function Zi(e,t,n){const i=Me(e);T(e,t,ft);const r=Ki(i,n);return new nr(i,"signInViaPopup",t,r).executeNotNull()}async function er(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft);const s=Ki(r.auth,i);return new nr(r.auth,"reauthViaPopup",n,s,r).executeNotNull()}async function tr(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft);const s=Ki(r.auth,i);return new nr(r.auth,"linkViaPopup",n,s,r).executeNotNull()}class nr extends Xi{constructor(e,t,n,i,r){super(e,t,i,r),this.provider=n,this.authWindow=null,this.pollId=null,nr.currentPopupAction&&nr.currentPopupAction.cancel(),nr.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return E(e,this.auth,"internal-error"),e}async onExecution(){A(1===this.filter.length,"Popup operations only handle one event");const e=Jn();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(_(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(_(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,nr.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;null!==(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)&&void 0!==n&&n.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(_(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(e,Qi.get())};e()}}nr.currentPopupAction=null;const ir="pendingRedirect",rr=new Map;class sr extends Xi{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=rr.get(this.auth._key());if(!e){try{const n=await or(this.resolver,this.auth)?await super.execute():null;e=(()=>Promise.resolve(n))}catch(t){e=(()=>Promise.reject(t))}rr.set(this.auth._key(),e)}return this.bypassAuthState||rr.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 or(e,t){const n=lr(t),i=dr(e);if(!(await i._isAvailable()))return!1;const r="true"===await i._get(n);return await i._remove(n),r}async function ar(e,t){return dr(e)._set(lr(t),"true")}function cr(){rr.clear()}function ur(e,t){rr.set(e._key(),t)}function dr(e){return N(e._redirectPersistence)}function lr(e){return ge(ir,e.config.apiKey,e.name)}function hr(e,t,n){return pr(e,t,n)}async function pr(e,t,n){const i=Me(e);T(e,t,ft),await i._initializationPromise;const r=Ki(i,n);return await ar(r,i),r._openRedirect(i,t,"signInViaRedirect")}function mr(e,t,n){return fr(e,t,n)}async function fr(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft),await r.auth._initializationPromise;const s=Ki(r.auth,i);await ar(s,r.auth);const o=await yr(r);return s._openRedirect(r.auth,n,"reauthViaRedirect",o)}function gr(e,t,n){return vr(e,t,n)}async function vr(t,n,i){const r=(0,e.getModularInstance)(t);T(r.auth,n,ft),await r.auth._initializationPromise;const s=Ki(r.auth,i);await Mt(!1,r,n.providerId),await ar(s,r.auth);const o=await yr(r);return s._openRedirect(r.auth,n,"linkViaRedirect",o)}async function Ir(e,t){return await Me(e)._initializationPromise,_r(e,t,!1)}async function _r(e,t,n=!1){const i=Me(e),r=Ki(i,t),s=new sr(i,r,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await i._persistUserIfCurrent(o.user),await i._setRedirectUser(null,t)),o}async function yr(e){const t=Jn(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}const Tr=6e5;class wr{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||!Ar(e)?t:(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0),t)}sendToConsumer(e,t){var n;if(e.error&&!kr(e)){const i=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(_(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=Tr&&this.cachedEventUids.clear(),this.cachedEventUids.has(Er(e))}saveEventToCache(e){this.cachedEventUids.add(Er(e)),this.lastProcessedEventTime=Date.now()}}function Er(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function kr({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}function Ar(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return kr(e);default:return!1}}async function Rr(e,t={}){return j(e,"GET","/v1/projects",t)}exports.ay=wr;const Nr=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,br=/^https?/;async function Sr(e){if(e.config.emulator)return;const{authorizedDomains:t}=await Rr(e);for(const i of t)try{if(Or(i))return}catch(n){}I(e,"unauthorized-domain")}function Or(e){const t=O(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){const r=new URL(e);return""===r.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===i}if(!br.test(n))return!1;if(Nr.test(e))return i===e;const r=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+r+"|"+r+")$","i").test(i)}const Pr=new M(3e4,6e4);function Dr(){const e=Yn().___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 n=0;n<e.CP.length;n++)e.CP[n]=null}function Cr(e){return new Promise((t,n)=>{var i,r,s;function o(){Dr(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{Dr(),n(_(e,"network-request-failed"))},timeout:Pr.get()})}if(null===(r=null===(i=Yn().gapi)||void 0===i?void 0:i.iframes)||void 0===r?void 0:r.Iframe)t(gapi.iframes.getContext());else{if(null===(s=Yn().gapi)||void 0===s||!s.load){const t=wi("iframefcb");return Yn()[t]=(()=>{gapi.load?o():n(_(e,"network-request-failed"))}),Ti(`https://apis.google.com/js/api.js?onload=${t}`).catch(e=>n(e))}o()}}).catch(e=>{throw Lr=null,e})}let Lr=null;function Mr(e){return Lr=Lr||Cr(e)}const xr=new M(5e3,15e3),Ur="__/auth/iframe",Fr="emulator/auth/iframe",Vr={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},qr=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function jr(n){const i=n.config;E(i.authDomain,n,"auth-domain-config-required");const r=i.emulator?x(i,Fr):`https://${n.config.authDomain}/${Ur}`,s={apiKey:i.apiKey,appName:n.name,v:t.SDK_VERSION},o=qr.get(n.config.apiHost);o&&(s.eid=o);const a=n._getFrameworks();return a.length&&(s.fw=a.join(",")),`${r}?${(0,e.querystring)(s).slice(1)}`}async function Hr(e){const t=await Mr(e),n=Yn().gapi;return E(n,e,"internal-error"),t.open({where:document.body,url:jr(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Vr,dontclear:!0},t=>new Promise(async(n,i)=>{await t.restyle({setHideOnLeave:!1});const r=_(e,"network-request-failed"),s=Yn().setTimeout(()=>{i(r)},xr.get());function o(){Yn().clearTimeout(s),n(t)}t.ping(o).then(o,()=>{i(r)})}))}const zr={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},Gr=500,Wr=600,Kr="_blank",Br="http://localhost";class Jr{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function $r(t,n,i,r=Gr,s=Wr){const o=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const u=Object.assign(Object.assign({},zr),{width:r.toString(),height:s.toString(),top:o,left:a}),d=(0,e.getUA)().toLowerCase();i&&(c=Te(d)?Kr:i),_e(d)&&(n=n||Br,u.scrollbars="yes");const l=Object.entries(u).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if(be(d)&&"_self"!==c)return Yr(n||"",c),new Jr(null);const h=window.open(n||"",c,l);E(h,t,"popup-blocked");try{h.focus()}catch(p){}return new Jr(h)}function Yr(e,t){const n=document.createElement("a");n.href=e,n.target=t;const i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(i)}exports.aJ=Jr;const Xr="__/auth/handler",Qr="emulator/auth/handler";function Zr(n,i,r,s,o,a){E(n.config.authDomain,n,"auth-domain-config-required"),E(n.config.apiKey,n,"invalid-api-key");const c={apiKey:n.config.apiKey,appName:n.name,authType:r,redirectUrl:s,v:t.SDK_VERSION,eventId:o};if(i instanceof ft){i.setDefaultLanguage(n.languageCode),c.providerId=i.providerId||"",(0,e.isEmpty)(i.getCustomParameters())||(c.customParameters=JSON.stringify(i.getCustomParameters()));for(const[e,t]of Object.entries(a||{}))c[e]=t}if(i instanceof gt){const e=i.getScopes().filter(e=>""!==e);e.length>0&&(c.scopes=e.join(","))}n.tenantId&&(c.tid=n.tenantId);const u=c;for(const e of Object.keys(u))void 0===u[e]&&delete u[e];return`${es(n)}?${(0,e.querystring)(u).slice(1)}`}function es({config:e}){return e.emulator?x(e,Qr):`https://${e.authDomain}/${Xr}`}const ts="webStorageSupport";class ns{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Wn,this._completeRedirectFn=_r,this._overrideRedirectResult=ur}async _openPopup(e,t,n,i){var r;return A(null===(r=this.eventManagers[e._key()])||void 0===r?void 0:r.manager,"_initialize() not called before _openPopup()"),$r(e,Zr(e,t,n,O(),i),Jn())}async _openRedirect(e,t,n,i){return await this._originValidation(e),Xn(Zr(e,t,n,O(),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):(A(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 Hr(e),n=new wr(e);return t.register("authEvent",t=>{return E(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(ts,{type:ts},n=>{var i;const r=null===(i=null==n?void 0:n[0])||void 0===i?void 0:i[ts];void 0!==r&&t(!!r),I(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Sr(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Oe()||ye()||Re()}}const is=ns;exports.k=is;class rs{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return k("unexpected MultiFactorSessionType")}}}class ss extends rs{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ss(e)}_finalizeEnroll(e,t,n){return Dn(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return Ii(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class os{constructor(){}static assertion(e){return ss._fromCredential(e)}}exports.m=os,os.FACTOR_ID="phone";var as="@firebase/auth",cs="0.21.5";class us{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){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged(t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){E(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function ds(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}function ls(e){(0,t._registerComponent)(new r.Component("auth",(t,{options:n})=>{const i=t.getProvider("app").getImmediate(),r=t.getProvider("heartbeat"),{apiKey:s,authDomain:o}=i.options;return((t,i)=>{E(s&&!s.includes(":"),"invalid-api-key",{appName:t.name}),E(!(null==o?void 0:o.includes(":")),"argument-error",{appName:t.name});const r={apiKey:s,authDomain:o,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:De(e)},a=new Le(t,i,r);return S(a,n),a})(i,r)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider("auth-internal").initialize()})),(0,t._registerComponent)(new r.Component("auth-internal",e=>{return(e=>new us(e))(Me(e.getProvider("auth").getImmediate()))},"PRIVATE").setInstantiationMode("EXPLICIT")),(0,t.registerVersion)(as,cs,ds(e)),(0,t.registerVersion)(as,cs,"esm2017")}const hs=300,ps=(0,e.getExperimentalSetting)("authIdTokenMaxAge")||300;let ms=null;const fs=e=>async t=>{const n=t&&await t.getIdTokenResult(),i=n&&((new Date).getTime()-Date.parse(n.issuedAtTime))/1e3;if(i&&i>ps)return;const r=null==n?void 0:n.token;ms!==r&&(ms=r,await fetch(e,{method:r?"POST":"DELETE",headers:r?{Authorization:`Bearer ${r}`}:{}}))};function gs(n=(0,t.getApp)()){const i=(0,t._getProvider)(n,"auth");if(i.isInitialized())return i.getImmediate();const r=b(n,{popupRedirectResolver:is,persistence:[gi,zn,Wn]}),s=(0,e.getExperimentalSetting)("authTokenSyncURL");if(s){const e=fs(s);wn(r,e,()=>e(r.currentUser)),Tn(r,t=>e(t))}const o=(0,e.getDefaultEmulatorHost)("auth");return o&&Ue(r,`http://${o}`),r}ls("Browser");
|
|
488
488
|
},{"@firebase/util":"chA2","@firebase/app":"h2Mb","@firebase/logger":"JJem","tslib":"vCxL","@firebase/component":"vhY9"}],"eL7N":[function(require,module,exports) {
|
|
489
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"ActionCodeOperation",{enumerable:!0,get:function(){return e.A}}),Object.defineProperty(exports,"ActionCodeURL",{enumerable:!0,get:function(){return e.ad}}),Object.defineProperty(exports,"AuthCredential",{enumerable:!0,get:function(){return e.H}}),Object.defineProperty(exports,"AuthErrorCodes",{enumerable:!0,get:function(){return e.D}}),Object.defineProperty(exports,"AuthImpl",{enumerable:!0,get:function(){return e.aG}}),Object.defineProperty(exports,"AuthPopup",{enumerable:!0,get:function(){return e.aJ}}),Object.defineProperty(exports,"EmailAuthCredential",{enumerable:!0,get:function(){return e.I}}),Object.defineProperty(exports,"EmailAuthProvider",{enumerable:!0,get:function(){return e.M}}),Object.defineProperty(exports,"FacebookAuthProvider",{enumerable:!0,get:function(){return e.N}}),Object.defineProperty(exports,"FactorId",{enumerable:!0,get:function(){return e.F}}),Object.defineProperty(exports,"FetchProvider",{enumerable:!0,get:function(){return e.aK}}),Object.defineProperty(exports,"GithubAuthProvider",{enumerable:!0,get:function(){return e.T}}),Object.defineProperty(exports,"GoogleAuthProvider",{enumerable:!0,get:function(){return e.Q}}),Object.defineProperty(exports,"OAuthCredential",{enumerable:!0,get:function(){return e.J}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return e.U}}),Object.defineProperty(exports,"OperationType",{enumerable:!0,get:function(){return e.O}}),Object.defineProperty(exports,"PhoneAuthCredential",{enumerable:!0,get:function(){return e.K}}),Object.defineProperty(exports,"PhoneAuthProvider",{enumerable:!0,get:function(){return e.P}}),Object.defineProperty(exports,"PhoneMultiFactorGenerator",{enumerable:!0,get:function(){return e.m}}),Object.defineProperty(exports,"ProviderId",{enumerable:!0,get:function(){return e.o}}),Object.defineProperty(exports,"RecaptchaVerifier",{enumerable:!0,get:function(){return e.R}}),Object.defineProperty(exports,"SAMLAuthCredential",{enumerable:!0,get:function(){return e.aL}}),Object.defineProperty(exports,"SAMLAuthProvider",{enumerable:!0,get:function(){return e.V}}),Object.defineProperty(exports,"SignInMethod",{enumerable:!0,get:function(){return e.S}}),Object.defineProperty(exports,"TwitterAuthProvider",{enumerable:!0,get:function(){return e.W}}),Object.defineProperty(exports,"UserImpl",{enumerable:!0,get:function(){return e.aF}}),Object.defineProperty(exports,"_assert",{enumerable:!0,get:function(){return e.ax}}),Object.defineProperty(exports,"_castAuth",{enumerable:!0,get:function(){return e.aE}}),Object.defineProperty(exports,"_fail",{enumerable:!0,get:function(){return e.as}}),Object.defineProperty(exports,"_generateEventId",{enumerable:!0,get:function(){return e.aI}}),Object.defineProperty(exports,"_getClientVersion",{enumerable:!0,get:function(){return e.aH}}),Object.defineProperty(exports,"_getInstance",{enumerable:!0,get:function(){return e.az}}),Object.defineProperty(exports,"_getRedirectResult",{enumerable:!0,get:function(){return e.aB}}),Object.defineProperty(exports,"_overrideRedirectResult",{enumerable:!0,get:function(){return e.aC}}),Object.defineProperty(exports,"_persistenceKeyName",{enumerable:!0,get:function(){return e.aA}}),exports.addFrameworkForLogging=k,Object.defineProperty(exports,"applyActionCode",{enumerable:!0,get:function(){return e.a2}}),Object.defineProperty(exports,"beforeAuthStateChanged",{enumerable:!0,get:function(){return e.t}}),Object.defineProperty(exports,"browserLocalPersistence",{enumerable:!0,get:function(){return e.b}}),Object.defineProperty(exports,"browserPopupRedirectResolver",{enumerable:!0,get:function(){return e.k}}),Object.defineProperty(exports,"browserSessionPersistence",{enumerable:!0,get:function(){return e.a}}),Object.defineProperty(exports,"checkActionCode",{enumerable:!0,get:function(){return e.a3}}),Object.defineProperty(exports,"confirmPasswordReset",{enumerable:!0,get:function(){return e.a1}}),Object.defineProperty(exports,"connectAuthEmulator",{enumerable:!0,get:function(){return e.G}}),exports.cordovaPopupRedirectResolver=void 0,Object.defineProperty(exports,"createUserWithEmailAndPassword",{enumerable:!0,get:function(){return e.a5}}),Object.defineProperty(exports,"debugErrorMap",{enumerable:!0,get:function(){return e.B}}),Object.defineProperty(exports,"deleteUser",{enumerable:!0,get:function(){return e.z}}),Object.defineProperty(exports,"fetchSignInMethodsForEmail",{enumerable:!0,get:function(){return e.aa}}),Object.defineProperty(exports,"getAdditionalUserInfo",{enumerable:!0,get:function(){return e.al}}),Object.defineProperty(exports,"getAuth",{enumerable:!0,get:function(){return e.n}}),Object.defineProperty(exports,"getIdToken",{enumerable:!0,get:function(){return e.ai}}),Object.defineProperty(exports,"getIdTokenResult",{enumerable:!0,get:function(){return e.aj}}),Object.defineProperty(exports,"getMultiFactorResolver",{enumerable:!0,get:function(){return e.an}}),Object.defineProperty(exports,"getRedirectResult",{enumerable:!0,get:function(){return e.j}}),Object.defineProperty(exports,"inMemoryPersistence",{enumerable:!0,get:function(){return e.L}}),Object.defineProperty(exports,"indexedDBLocalPersistence",{enumerable:!0,get:function(){return e.i}}),Object.defineProperty(exports,"initializeAuth",{enumerable:!0,get:function(){return e.E}}),Object.defineProperty(exports,"isSignInWithEmailLink",{enumerable:!0,get:function(){return e.a8}}),Object.defineProperty(exports,"linkWithCredential",{enumerable:!0,get:function(){return e.Z}}),Object.defineProperty(exports,"linkWithPhoneNumber",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(exports,"linkWithPopup",{enumerable:!0,get:function(){return e.d}}),Object.defineProperty(exports,"linkWithRedirect",{enumerable:!0,get:function(){return e.g}}),Object.defineProperty(exports,"multiFactor",{enumerable:!0,get:function(){return e.ao}}),Object.defineProperty(exports,"onAuthStateChanged",{enumerable:!0,get:function(){return e.v}}),Object.defineProperty(exports,"onIdTokenChanged",{enumerable:!0,get:function(){return e.q}}),Object.defineProperty(exports,"parseActionCodeURL",{enumerable:!0,get:function(){return e.ae}}),Object.defineProperty(exports,"prodErrorMap",{enumerable:!0,get:function(){return e.C}}),Object.defineProperty(exports,"reauthenticateWithCredential",{enumerable:!0,get:function(){return e._}}),Object.defineProperty(exports,"reauthenticateWithPhoneNumber",{enumerable:!0,get:function(){return e.r}}),Object.defineProperty(exports,"reauthenticateWithPopup",{enumerable:!0,get:function(){return e.e}}),Object.defineProperty(exports,"reauthenticateWithRedirect",{enumerable:!0,get:function(){return e.h}}),Object.defineProperty(exports,"reload",{enumerable:!0,get:function(){return e.am}}),Object.defineProperty(exports,"sendEmailVerification",{enumerable:!0,get:function(){return e.ab}}),Object.defineProperty(exports,"sendPasswordResetEmail",{enumerable:!0,get:function(){return e.a0}}),Object.defineProperty(exports,"sendSignInLinkToEmail",{enumerable:!0,get:function(){return e.a7}}),Object.defineProperty(exports,"setPersistence",{enumerable:!0,get:function(){return e.p}}),Object.defineProperty(exports,"signInAnonymously",{enumerable:!0,get:function(){return e.X}}),Object.defineProperty(exports,"signInWithCredential",{enumerable:!0,get:function(){return e.Y}}),Object.defineProperty(exports,"signInWithCustomToken",{enumerable:!0,get:function(){return e.$}}),Object.defineProperty(exports,"signInWithEmailAndPassword",{enumerable:!0,get:function(){return e.a6}}),Object.defineProperty(exports,"signInWithEmailLink",{enumerable:!0,get:function(){return e.a9}}),Object.defineProperty(exports,"signInWithPhoneNumber",{enumerable:!0,get:function(){return e.s}}),Object.defineProperty(exports,"signInWithPopup",{enumerable:!0,get:function(){return e.c}}),Object.defineProperty(exports,"signInWithRedirect",{enumerable:!0,get:function(){return e.f}}),Object.defineProperty(exports,"signOut",{enumerable:!0,get:function(){return e.y}}),Object.defineProperty(exports,"unlink",{enumerable:!0,get:function(){return e.ak}}),Object.defineProperty(exports,"updateCurrentUser",{enumerable:!0,get:function(){return e.x}}),Object.defineProperty(exports,"updateEmail",{enumerable:!0,get:function(){return e.ag}}),Object.defineProperty(exports,"updatePassword",{enumerable:!0,get:function(){return e.ah}}),Object.defineProperty(exports,"updatePhoneNumber",{enumerable:!0,get:function(){return e.u}}),Object.defineProperty(exports,"updateProfile",{enumerable:!0,get:function(){return e.af}}),Object.defineProperty(exports,"useDeviceLanguage",{enumerable:!0,get:function(){return e.w}}),Object.defineProperty(exports,"verifyBeforeUpdateEmail",{enumerable:!0,get:function(){return e.ac}}),Object.defineProperty(exports,"verifyPasswordResetCode",{enumerable:!0,get:function(){return e.a4}});var e=require("./index-30f3030e.js"),t=require("@firebase/util");function n(){return window}require("@firebase/app"),require("@firebase/logger"),require("tslib"),require("@firebase/component");const r=2e3;async function o(t,r,o){var i;const{BuildInfo:u}=n();(0,e.ap)(r.sessionId,"AuthEvent did not contain a session ID");const a=await c(r.sessionId),s={};return(0,e.aq)()?s.ibi=u.packageName:(0,e.ar)()?s.apn=u.packageName:(0,e.as)(t,"operation-not-supported-in-this-environment"),u.displayName&&(s.appDisplayName=u.displayName),s.sessionId=a,(0,e.at)(t,o,r.type,void 0,null!==(i=r.eventId)&&void 0!==i?i:void 0,s)}async function i(t){const{BuildInfo:r}=n(),o={};(0,e.aq)()?o.iosBundleId=r.packageName:(0,e.ar)()?o.androidPackageName=r.packageName:(0,e.as)(t,"operation-not-supported-in-this-environment"),await(0,e.au)(t,o)}function u(t){const{cordova:r}=n();return new Promise(n=>{r.plugins.browsertab.isAvailable(o=>{let i=null;o?r.plugins.browsertab.openUrl(t):i=r.InAppBrowser.open(t,(0,e.av)()?"_blank":"_system","location=yes"),n(i)})})}async function a(t,o,i){const{cordova:u}=n();let a=()=>{};try{await new Promise((n,s)=>{let c=null;function l(){var e;n();const t=null===(e=u.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==i?void 0:i.close)&&i.close()}function d(){c||(c=window.setTimeout(()=>{s((0,e.aw)(t,"redirect-cancelled-by-user"))},r))}function p(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&d()}o.addPassiveListener(l),document.addEventListener("resume",d,!1),(0,e.ar)()&&document.addEventListener("visibilitychange",p,!1),a=(()=>{o.removePassiveListener(l),document.removeEventListener("resume",d,!1),document.removeEventListener("visibilitychange",p,!1),c&&window.clearTimeout(c)})})}finally{a()}}function s(t){var r,o,i,u,a,s,c,l,d,p;const f=n();(0,e.ax)("function"==typeof(null===(r=null==f?void 0:f.universalLinks)||void 0===r?void 0:r.subscribe),t,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),(0,e.ax)(void 0!==(null===(o=null==f?void 0:f.BuildInfo)||void 0===o?void 0:o.packageName),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),(0,e.ax)("function"==typeof(null===(a=null===(u=null===(i=null==f?void 0:f.cordova)||void 0===i?void 0:i.plugins)||void 0===u?void 0:u.browsertab)||void 0===a?void 0:a.openUrl),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),(0,e.ax)("function"==typeof(null===(l=null===(c=null===(s=null==f?void 0:f.cordova)||void 0===s?void 0:s.plugins)||void 0===c?void 0:c.browsertab)||void 0===l?void 0:l.isAvailable),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),(0,e.ax)("function"==typeof(null===(p=null===(d=null==f?void 0:f.cordova)||void 0===d?void 0:d.InAppBrowser)||void 0===p?void 0:p.open),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"})}async function c(e){const t=l(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}function l(t){if((0,e.ap)(/[0-9a-zA-Z]+/.test(t),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(t);const n=new ArrayBuffer(t.length),r=new Uint8Array(n);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}const d=20;class p extends e.ay{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(e){return this.resolveInialized(),this.passiveListeners.forEach(t=>t(e)),super.onEvent(e)}async initialized(){await this.initPromise}}function f(t,n,r=null){return{type:n,eventId:r,urlResponse:null,sessionId:y(),postBody:null,tenantId:t.tenantId,error:(0,e.aw)(t,"no-auth-event")}}function b(e,t){return P()._set(v(e),t)}async function g(e){const t=await P()._get(v(e));return t&&await P()._remove(v(e)),t}function m(t,n){var r,o;const i=x(n);if(i.includes("/__/auth/callback")){const n=O(i),u=n.firebaseError?h(decodeURIComponent(n.firebaseError)):null,a=null===(o=null===(r=null==u?void 0:u.code)||void 0===r?void 0:r.split("auth/"))||void 0===o?void 0:o[1],s=a?(0,e.aw)(a):null;return s?{type:t.type,eventId:t.eventId,tenantId:t.tenantId,error:s,urlResponse:null,sessionId:null,postBody:null}:{type:t.type,eventId:t.eventId,tenantId:t.tenantId,sessionId:t.sessionId,urlResponse:i,postBody:null}}return null}function y(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<d;n++){const n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}function P(){return(0,e.az)(e.b)}function v(t){return(0,e.aA)("authEvent",t.config.apiKey,t.name)}function h(e){try{return JSON.parse(e)}catch(t){return null}}function x(e){const t=O(e),n=t.link?decodeURIComponent(t.link):void 0,r=O(n).link,o=t.deep_link_id?decodeURIComponent(t.deep_link_id):void 0;return O(o).link||o||r||n||e}function O(e){if(!(null==e?void 0:e.includes("?")))return{};const[n,...r]=e.split("?");return(0,t.querystringDecode)(r.join("?"))}const j=500;class w{constructor(){this._redirectPersistence=e.a,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=e.aB,this._overrideRedirectResult=e.aC}async _initialize(e){const t=e._key();let n=this.eventManagers.get(t);return n||(n=new p(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(t){(0,e.as)(t,"operation-not-supported-in-this-environment")}async _openRedirect(t,n,r,i){s(t);const c=await this._initialize(t);await c.initialized(),c.resetRedirect(),(0,e.aD)(),await this._originValidation(t);const l=f(t,r,i);await b(t,l);const d=await o(t,l,n);return a(t,c,await u(d))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=i(e)),this.originValidationPromises[t]}attachCallbackListeners(e,t){const{universalLinks:r,handleOpenURL:o,BuildInfo:i}=n(),u=setTimeout(async()=>{await g(e),t.onEvent(A())},j),a=async n=>{clearTimeout(u);const r=await g(e);let o=null;r&&(null==n?void 0:n.url)&&(o=m(r,n.url)),t.onEvent(o||A())};void 0!==r&&"function"==typeof r.subscribe&&r.subscribe(null,a);const s=o,c=`${i.packageName.toLowerCase()}://`;n().handleOpenURL=(async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof s)try{s(e)}catch(t){console.error(t)}})}}const I=w;function A(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:(0,e.aw)("no-auth-event")}}function k(t,n){(0,e.aE)(t)._logFramework(n)}exports.cordovaPopupRedirectResolver=I;
|
|
490
|
-
},{"./index-
|
|
489
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"ActionCodeOperation",{enumerable:!0,get:function(){return e.A}}),Object.defineProperty(exports,"ActionCodeURL",{enumerable:!0,get:function(){return e.ad}}),Object.defineProperty(exports,"AuthCredential",{enumerable:!0,get:function(){return e.H}}),Object.defineProperty(exports,"AuthErrorCodes",{enumerable:!0,get:function(){return e.D}}),Object.defineProperty(exports,"AuthImpl",{enumerable:!0,get:function(){return e.aG}}),Object.defineProperty(exports,"AuthPopup",{enumerable:!0,get:function(){return e.aJ}}),Object.defineProperty(exports,"EmailAuthCredential",{enumerable:!0,get:function(){return e.I}}),Object.defineProperty(exports,"EmailAuthProvider",{enumerable:!0,get:function(){return e.M}}),Object.defineProperty(exports,"FacebookAuthProvider",{enumerable:!0,get:function(){return e.N}}),Object.defineProperty(exports,"FactorId",{enumerable:!0,get:function(){return e.F}}),Object.defineProperty(exports,"FetchProvider",{enumerable:!0,get:function(){return e.aK}}),Object.defineProperty(exports,"GithubAuthProvider",{enumerable:!0,get:function(){return e.T}}),Object.defineProperty(exports,"GoogleAuthProvider",{enumerable:!0,get:function(){return e.Q}}),Object.defineProperty(exports,"OAuthCredential",{enumerable:!0,get:function(){return e.J}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return e.U}}),Object.defineProperty(exports,"OperationType",{enumerable:!0,get:function(){return e.O}}),Object.defineProperty(exports,"PhoneAuthCredential",{enumerable:!0,get:function(){return e.K}}),Object.defineProperty(exports,"PhoneAuthProvider",{enumerable:!0,get:function(){return e.P}}),Object.defineProperty(exports,"PhoneMultiFactorGenerator",{enumerable:!0,get:function(){return e.m}}),Object.defineProperty(exports,"ProviderId",{enumerable:!0,get:function(){return e.o}}),Object.defineProperty(exports,"RecaptchaVerifier",{enumerable:!0,get:function(){return e.R}}),Object.defineProperty(exports,"SAMLAuthCredential",{enumerable:!0,get:function(){return e.aL}}),Object.defineProperty(exports,"SAMLAuthProvider",{enumerable:!0,get:function(){return e.V}}),Object.defineProperty(exports,"SignInMethod",{enumerable:!0,get:function(){return e.S}}),Object.defineProperty(exports,"TwitterAuthProvider",{enumerable:!0,get:function(){return e.W}}),Object.defineProperty(exports,"UserImpl",{enumerable:!0,get:function(){return e.aF}}),Object.defineProperty(exports,"_assert",{enumerable:!0,get:function(){return e.ax}}),Object.defineProperty(exports,"_castAuth",{enumerable:!0,get:function(){return e.aE}}),Object.defineProperty(exports,"_fail",{enumerable:!0,get:function(){return e.as}}),Object.defineProperty(exports,"_generateEventId",{enumerable:!0,get:function(){return e.aI}}),Object.defineProperty(exports,"_getClientVersion",{enumerable:!0,get:function(){return e.aH}}),Object.defineProperty(exports,"_getInstance",{enumerable:!0,get:function(){return e.az}}),Object.defineProperty(exports,"_getRedirectResult",{enumerable:!0,get:function(){return e.aB}}),Object.defineProperty(exports,"_overrideRedirectResult",{enumerable:!0,get:function(){return e.aC}}),Object.defineProperty(exports,"_persistenceKeyName",{enumerable:!0,get:function(){return e.aA}}),exports.addFrameworkForLogging=k,Object.defineProperty(exports,"applyActionCode",{enumerable:!0,get:function(){return e.a2}}),Object.defineProperty(exports,"beforeAuthStateChanged",{enumerable:!0,get:function(){return e.t}}),Object.defineProperty(exports,"browserLocalPersistence",{enumerable:!0,get:function(){return e.b}}),Object.defineProperty(exports,"browserPopupRedirectResolver",{enumerable:!0,get:function(){return e.k}}),Object.defineProperty(exports,"browserSessionPersistence",{enumerable:!0,get:function(){return e.a}}),Object.defineProperty(exports,"checkActionCode",{enumerable:!0,get:function(){return e.a3}}),Object.defineProperty(exports,"confirmPasswordReset",{enumerable:!0,get:function(){return e.a1}}),Object.defineProperty(exports,"connectAuthEmulator",{enumerable:!0,get:function(){return e.G}}),exports.cordovaPopupRedirectResolver=void 0,Object.defineProperty(exports,"createUserWithEmailAndPassword",{enumerable:!0,get:function(){return e.a5}}),Object.defineProperty(exports,"debugErrorMap",{enumerable:!0,get:function(){return e.B}}),Object.defineProperty(exports,"deleteUser",{enumerable:!0,get:function(){return e.z}}),Object.defineProperty(exports,"fetchSignInMethodsForEmail",{enumerable:!0,get:function(){return e.aa}}),Object.defineProperty(exports,"getAdditionalUserInfo",{enumerable:!0,get:function(){return e.al}}),Object.defineProperty(exports,"getAuth",{enumerable:!0,get:function(){return e.n}}),Object.defineProperty(exports,"getIdToken",{enumerable:!0,get:function(){return e.ai}}),Object.defineProperty(exports,"getIdTokenResult",{enumerable:!0,get:function(){return e.aj}}),Object.defineProperty(exports,"getMultiFactorResolver",{enumerable:!0,get:function(){return e.an}}),Object.defineProperty(exports,"getRedirectResult",{enumerable:!0,get:function(){return e.j}}),Object.defineProperty(exports,"inMemoryPersistence",{enumerable:!0,get:function(){return e.L}}),Object.defineProperty(exports,"indexedDBLocalPersistence",{enumerable:!0,get:function(){return e.i}}),Object.defineProperty(exports,"initializeAuth",{enumerable:!0,get:function(){return e.E}}),Object.defineProperty(exports,"isSignInWithEmailLink",{enumerable:!0,get:function(){return e.a8}}),Object.defineProperty(exports,"linkWithCredential",{enumerable:!0,get:function(){return e.Z}}),Object.defineProperty(exports,"linkWithPhoneNumber",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(exports,"linkWithPopup",{enumerable:!0,get:function(){return e.d}}),Object.defineProperty(exports,"linkWithRedirect",{enumerable:!0,get:function(){return e.g}}),Object.defineProperty(exports,"multiFactor",{enumerable:!0,get:function(){return e.ao}}),Object.defineProperty(exports,"onAuthStateChanged",{enumerable:!0,get:function(){return e.v}}),Object.defineProperty(exports,"onIdTokenChanged",{enumerable:!0,get:function(){return e.q}}),Object.defineProperty(exports,"parseActionCodeURL",{enumerable:!0,get:function(){return e.ae}}),Object.defineProperty(exports,"prodErrorMap",{enumerable:!0,get:function(){return e.C}}),Object.defineProperty(exports,"reauthenticateWithCredential",{enumerable:!0,get:function(){return e._}}),Object.defineProperty(exports,"reauthenticateWithPhoneNumber",{enumerable:!0,get:function(){return e.r}}),Object.defineProperty(exports,"reauthenticateWithPopup",{enumerable:!0,get:function(){return e.e}}),Object.defineProperty(exports,"reauthenticateWithRedirect",{enumerable:!0,get:function(){return e.h}}),Object.defineProperty(exports,"reload",{enumerable:!0,get:function(){return e.am}}),Object.defineProperty(exports,"sendEmailVerification",{enumerable:!0,get:function(){return e.ab}}),Object.defineProperty(exports,"sendPasswordResetEmail",{enumerable:!0,get:function(){return e.a0}}),Object.defineProperty(exports,"sendSignInLinkToEmail",{enumerable:!0,get:function(){return e.a7}}),Object.defineProperty(exports,"setPersistence",{enumerable:!0,get:function(){return e.p}}),Object.defineProperty(exports,"signInAnonymously",{enumerable:!0,get:function(){return e.X}}),Object.defineProperty(exports,"signInWithCredential",{enumerable:!0,get:function(){return e.Y}}),Object.defineProperty(exports,"signInWithCustomToken",{enumerable:!0,get:function(){return e.$}}),Object.defineProperty(exports,"signInWithEmailAndPassword",{enumerable:!0,get:function(){return e.a6}}),Object.defineProperty(exports,"signInWithEmailLink",{enumerable:!0,get:function(){return e.a9}}),Object.defineProperty(exports,"signInWithPhoneNumber",{enumerable:!0,get:function(){return e.s}}),Object.defineProperty(exports,"signInWithPopup",{enumerable:!0,get:function(){return e.c}}),Object.defineProperty(exports,"signInWithRedirect",{enumerable:!0,get:function(){return e.f}}),Object.defineProperty(exports,"signOut",{enumerable:!0,get:function(){return e.y}}),Object.defineProperty(exports,"unlink",{enumerable:!0,get:function(){return e.ak}}),Object.defineProperty(exports,"updateCurrentUser",{enumerable:!0,get:function(){return e.x}}),Object.defineProperty(exports,"updateEmail",{enumerable:!0,get:function(){return e.ag}}),Object.defineProperty(exports,"updatePassword",{enumerable:!0,get:function(){return e.ah}}),Object.defineProperty(exports,"updatePhoneNumber",{enumerable:!0,get:function(){return e.u}}),Object.defineProperty(exports,"updateProfile",{enumerable:!0,get:function(){return e.af}}),Object.defineProperty(exports,"useDeviceLanguage",{enumerable:!0,get:function(){return e.w}}),Object.defineProperty(exports,"verifyBeforeUpdateEmail",{enumerable:!0,get:function(){return e.ac}}),Object.defineProperty(exports,"verifyPasswordResetCode",{enumerable:!0,get:function(){return e.a4}});var e=require("./index-3363a72a.js"),t=require("@firebase/util");function n(){return window}require("@firebase/app"),require("@firebase/logger"),require("tslib"),require("@firebase/component");const r=2e3;async function o(t,r,o){var i;const{BuildInfo:u}=n();(0,e.ap)(r.sessionId,"AuthEvent did not contain a session ID");const a=await c(r.sessionId),s={};return(0,e.aq)()?s.ibi=u.packageName:(0,e.ar)()?s.apn=u.packageName:(0,e.as)(t,"operation-not-supported-in-this-environment"),u.displayName&&(s.appDisplayName=u.displayName),s.sessionId=a,(0,e.at)(t,o,r.type,void 0,null!==(i=r.eventId)&&void 0!==i?i:void 0,s)}async function i(t){const{BuildInfo:r}=n(),o={};(0,e.aq)()?o.iosBundleId=r.packageName:(0,e.ar)()?o.androidPackageName=r.packageName:(0,e.as)(t,"operation-not-supported-in-this-environment"),await(0,e.au)(t,o)}function u(t){const{cordova:r}=n();return new Promise(n=>{r.plugins.browsertab.isAvailable(o=>{let i=null;o?r.plugins.browsertab.openUrl(t):i=r.InAppBrowser.open(t,(0,e.av)()?"_blank":"_system","location=yes"),n(i)})})}async function a(t,o,i){const{cordova:u}=n();let a=()=>{};try{await new Promise((n,s)=>{let c=null;function l(){var e;n();const t=null===(e=u.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==i?void 0:i.close)&&i.close()}function d(){c||(c=window.setTimeout(()=>{s((0,e.aw)(t,"redirect-cancelled-by-user"))},r))}function p(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&d()}o.addPassiveListener(l),document.addEventListener("resume",d,!1),(0,e.ar)()&&document.addEventListener("visibilitychange",p,!1),a=(()=>{o.removePassiveListener(l),document.removeEventListener("resume",d,!1),document.removeEventListener("visibilitychange",p,!1),c&&window.clearTimeout(c)})})}finally{a()}}function s(t){var r,o,i,u,a,s,c,l,d,p;const f=n();(0,e.ax)("function"==typeof(null===(r=null==f?void 0:f.universalLinks)||void 0===r?void 0:r.subscribe),t,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),(0,e.ax)(void 0!==(null===(o=null==f?void 0:f.BuildInfo)||void 0===o?void 0:o.packageName),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),(0,e.ax)("function"==typeof(null===(a=null===(u=null===(i=null==f?void 0:f.cordova)||void 0===i?void 0:i.plugins)||void 0===u?void 0:u.browsertab)||void 0===a?void 0:a.openUrl),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),(0,e.ax)("function"==typeof(null===(l=null===(c=null===(s=null==f?void 0:f.cordova)||void 0===s?void 0:s.plugins)||void 0===c?void 0:c.browsertab)||void 0===l?void 0:l.isAvailable),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),(0,e.ax)("function"==typeof(null===(p=null===(d=null==f?void 0:f.cordova)||void 0===d?void 0:d.InAppBrowser)||void 0===p?void 0:p.open),t,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"})}async function c(e){const t=l(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}function l(t){if((0,e.ap)(/[0-9a-zA-Z]+/.test(t),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(t);const n=new ArrayBuffer(t.length),r=new Uint8Array(n);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}const d=20;class p extends e.ay{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(e){return this.resolveInialized(),this.passiveListeners.forEach(t=>t(e)),super.onEvent(e)}async initialized(){await this.initPromise}}function f(t,n,r=null){return{type:n,eventId:r,urlResponse:null,sessionId:y(),postBody:null,tenantId:t.tenantId,error:(0,e.aw)(t,"no-auth-event")}}function b(e,t){return P()._set(v(e),t)}async function g(e){const t=await P()._get(v(e));return t&&await P()._remove(v(e)),t}function m(t,n){var r,o;const i=x(n);if(i.includes("/__/auth/callback")){const n=O(i),u=n.firebaseError?h(decodeURIComponent(n.firebaseError)):null,a=null===(o=null===(r=null==u?void 0:u.code)||void 0===r?void 0:r.split("auth/"))||void 0===o?void 0:o[1],s=a?(0,e.aw)(a):null;return s?{type:t.type,eventId:t.eventId,tenantId:t.tenantId,error:s,urlResponse:null,sessionId:null,postBody:null}:{type:t.type,eventId:t.eventId,tenantId:t.tenantId,sessionId:t.sessionId,urlResponse:i,postBody:null}}return null}function y(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<d;n++){const n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}function P(){return(0,e.az)(e.b)}function v(t){return(0,e.aA)("authEvent",t.config.apiKey,t.name)}function h(e){try{return JSON.parse(e)}catch(t){return null}}function x(e){const t=O(e),n=t.link?decodeURIComponent(t.link):void 0,r=O(n).link,o=t.deep_link_id?decodeURIComponent(t.deep_link_id):void 0;return O(o).link||o||r||n||e}function O(e){if(!(null==e?void 0:e.includes("?")))return{};const[n,...r]=e.split("?");return(0,t.querystringDecode)(r.join("?"))}const j=500;class w{constructor(){this._redirectPersistence=e.a,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=e.aB,this._overrideRedirectResult=e.aC}async _initialize(e){const t=e._key();let n=this.eventManagers.get(t);return n||(n=new p(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(t){(0,e.as)(t,"operation-not-supported-in-this-environment")}async _openRedirect(t,n,r,i){s(t);const c=await this._initialize(t);await c.initialized(),c.resetRedirect(),(0,e.aD)(),await this._originValidation(t);const l=f(t,r,i);await b(t,l);const d=await o(t,l,n);return a(t,c,await u(d))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=i(e)),this.originValidationPromises[t]}attachCallbackListeners(e,t){const{universalLinks:r,handleOpenURL:o,BuildInfo:i}=n(),u=setTimeout(async()=>{await g(e),t.onEvent(A())},j),a=async n=>{clearTimeout(u);const r=await g(e);let o=null;r&&(null==n?void 0:n.url)&&(o=m(r,n.url)),t.onEvent(o||A())};void 0!==r&&"function"==typeof r.subscribe&&r.subscribe(null,a);const s=o,c=`${i.packageName.toLowerCase()}://`;n().handleOpenURL=(async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof s)try{s(e)}catch(t){console.error(t)}})}}const I=w;function A(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:(0,e.aw)("no-auth-event")}}function k(t,n){(0,e.aE)(t)._logFramework(n)}exports.cordovaPopupRedirectResolver=I;
|
|
490
|
+
},{"./index-3363a72a.js":"z5kx","@firebase/util":"chA2","@firebase/app":"h2Mb","@firebase/logger":"JJem","tslib":"vCxL","@firebase/component":"vhY9"}],"h9Y9":[function(require,module,exports) {
|
|
491
491
|
var global = arguments[3];
|
|
492
|
-
var e=arguments[3],t=o(require("@firebase/app-compat")),r=a(require("@firebase/auth/internal")),n=require("@firebase/component"),i=require("@firebase/util");function s(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(s=function(e){return e?r:t})(e)}function a(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=s(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var o=i?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(n,a,o):n[a]=e[a]}return n.default=e,r&&r.set(e,n),n}function o(e){return e&&e.__esModule?e:{default:e}}var d="@firebase/auth-compat",u="0.3.3";const l=1e3;function h(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function c(){return"http:"===h()||"https:"===h()}function g(e=(0,i.getUA)()){return!("file:"!==h()&&"ionic:"!==h()&&"capacitor:"!==h()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function p(){return(0,i.isReactNative)()||(0,i.isNode)()}function _(){return(0,i.isIE)()&&11===(null===document||void 0===document?void 0:document.documentMode)}function v(e=(0,i.getUA)()){return/Edge\/\d+/.test(e)}function f(e=(0,i.getUA)()){return _()||v(e)}function m(){try{const t=self.localStorage,n=r._generateEventId();if(t)return t.setItem(n,"1"),t.removeItem(n),!f()||(0,i.isIndexedDBAvailable)()}catch(e){return P()&&(0,i.isIndexedDBAvailable)()}return!1}function P(){return void 0!==e&&"WorkerGlobalScope"in e&&"importScripts"in e}function I(){return(c()||(0,i.isBrowserExtension)()||g())&&!p()&&m()&&!P()}function A(){return g()&&"undefined"!=typeof document}async function y(){return!!A()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},l);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})}function R(){return"undefined"!=typeof window?window:null}const E={LOCAL:"local",NONE:"none",SESSION:"session"},w=r._assert,N="persistence";function b(e,t){w(Object.values(E).includes(t),e,"invalid-persistence-type"),(0,i.isReactNative)()?w(t!==E.SESSION,e,"unsupported-persistence-type"):(0,i.isNode)()?w(t===E.NONE,e,"unsupported-persistence-type"):P()?w(t===E.NONE||t===E.LOCAL&&(0,i.isIndexedDBAvailable)(),e,"unsupported-persistence-type"):w(t===E.NONE||m(),e,"unsupported-persistence-type")}async function k(e){await e._initializationPromise;const t=O(),n=r._persistenceKeyName(N,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function C(e,t){const n=O();if(!n)return[];const i=r._persistenceKeyName(N,e,t);switch(n.getItem(i)){case E.NONE:return[r.inMemoryPersistence];case E.LOCAL:return[r.indexedDBLocalPersistence,r.browserSessionPersistence];case E.SESSION:return[r.browserSessionPersistence];default:return[]}}function O(){var e;try{return(null===(e=R())||void 0===e?void 0:e.sessionStorage)||null}catch(t){return null}}const S=r._assert;class W{constructor(){this.browserResolver=r._getInstance(r.browserPopupRedirectResolver),this.cordovaResolver=r._getInstance(r.cordovaPopupRedirectResolver),this.underlyingResolver=null,this._redirectPersistence=r.browserSessionPersistence,this._completeRedirectFn=r._getRedirectResult,this._overrideRedirectResult=r._overrideRedirectResult}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,r,n)}async _openRedirect(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,r,n)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return A()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return S(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){if(this.underlyingResolver)return;const e=await y();this.underlyingResolver=e?this.cordovaResolver:this.browserResolver}}function L(e){return e.unwrap()}function T(e){return e.wrapped()}function M(e){return U(e)}function D(e,t){var n;const i=null===(n=t.customData)||void 0===n?void 0:n._tokenResponse;if("auth/multi-factor-auth-required"===(null==t?void 0:t.code)){t.resolver=new G(e,r.getMultiFactorResolver(e,t))}else if(i){const e=U(t),r=t;e&&(r.credential=e,r.tenantId=i.tenantId||void 0,r.email=i.email||void 0,r.phoneNumber=i.phoneNumber||void 0)}}function U(e){const{_tokenResponse:t}=e instanceof i.FirebaseError?e.customData:e;if(!t)return null;if(!(e instanceof i.FirebaseError)&&"temporaryProof"in t&&"phoneNumber"in t)return r.PhoneAuthProvider.credentialFromResult(e);const n=t.providerId;if(!n||n===r.ProviderId.PASSWORD)return null;let s;switch(n){case r.ProviderId.GOOGLE:s=r.GoogleAuthProvider;break;case r.ProviderId.FACEBOOK:s=r.FacebookAuthProvider;break;case r.ProviderId.GITHUB:s=r.GithubAuthProvider;break;case r.ProviderId.TWITTER:s=r.TwitterAuthProvider;break;default:const{oauthIdToken:e,oauthAccessToken:i,oauthTokenSecret:a,pendingToken:o,nonce:d}=t;return i||a||e||o?o?n.startsWith("saml.")?r.SAMLAuthCredential._create(n,o):r.OAuthCredential._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:e,accessToken:i}):new r.OAuthProvider(n).credential({idToken:e,accessToken:i,rawNonce:d}):null}return e instanceof i.FirebaseError?s.credentialFromError(e):s.credentialFromResult(e)}function F(e,t){return t.catch(t=>{throw t instanceof i.FirebaseError&&D(e,t),t}).then(e=>{const t=e.operationType,n=e.user;return{operationType:t,credential:M(e),additionalUserInfo:r.getAdditionalUserInfo(e),user:B.getOrCreate(n)}})}async function V(e,t){const r=await t;return{verificationId:r.verificationId,confirm:t=>F(e,r.confirm(t))}}class G{constructor(e,t){this.resolver=t,this.auth=T(e)}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return F(L(this.auth),this.resolver.resolveSignIn(e))}}class B{constructor(e){this._delegate=e,this.multiFactor=r.multiFactor(e)}static getOrCreate(e){return B.USER_MAP.has(e)||B.USER_MAP.set(e,new B(e)),B.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return F(this.auth,r.linkWithCredential(this._delegate,e))}async linkWithPhoneNumber(e,t){return V(this.auth,r.linkWithPhoneNumber(this._delegate,e,t))}async linkWithPopup(e){return F(this.auth,r.linkWithPopup(this._delegate,e,W))}async linkWithRedirect(e){return await k(r._castAuth(this.auth)),r.linkWithRedirect(this._delegate,e,W)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return F(this.auth,r.reauthenticateWithCredential(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return V(this.auth,r.reauthenticateWithPhoneNumber(this._delegate,e,t))}reauthenticateWithPopup(e){return F(this.auth,r.reauthenticateWithPopup(this._delegate,e,W))}async reauthenticateWithRedirect(e){return await k(r._castAuth(this.auth)),r.reauthenticateWithRedirect(this._delegate,e,W)}sendEmailVerification(e){return r.sendEmailVerification(this._delegate,e)}async unlink(e){return await r.unlink(this._delegate,e),this}updateEmail(e){return r.updateEmail(this._delegate,e)}updatePassword(e){return r.updatePassword(this._delegate,e)}updatePhoneNumber(e){return r.updatePhoneNumber(this._delegate,e)}updateProfile(e){return r.updateProfile(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return r.verifyBeforeUpdateEmail(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}B.USER_MAP=new WeakMap;const x=r._assert;class j{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();const{apiKey:n}=e.options;x(n,"invalid-api-key",{appName:e.name}),x(n,"invalid-api-key",{appName:e.name});const i="undefined"!=typeof window?W:void 0;this._delegate=t.initialize({options:{persistence:K(n,e.name),popupRedirectResolver:i}}),this._delegate._updateErrorMap(r.debugErrorMap),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?B.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){r.connectAuthEmulator(this._delegate,e,t)}applyActionCode(e){return r.applyActionCode(this._delegate,e)}checkActionCode(e){return r.checkActionCode(this._delegate,e)}confirmPasswordReset(e,t){return r.confirmPasswordReset(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return F(this._delegate,r.createUserWithEmailAndPassword(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return r.fetchSignInMethodsForEmail(this._delegate,e)}isSignInWithEmailLink(e){return r.isSignInWithEmailLink(this._delegate,e)}async getRedirectResult(){x(I(),this._delegate,"operation-not-supported-in-this-environment");const e=await r.getRedirectResult(this._delegate,W);return e?F(this._delegate,Promise.resolve(e)):{credential:null,user:null}}addFrameworkForLogging(e){r.addFrameworkForLogging(this._delegate,e)}onAuthStateChanged(e,t,r){const{next:n,error:i,complete:s}=H(e,t,r);return this._delegate.onAuthStateChanged(n,i,s)}onIdTokenChanged(e,t,r){const{next:n,error:i,complete:s}=H(e,t,r);return this._delegate.onIdTokenChanged(n,i,s)}sendSignInLinkToEmail(e,t){return r.sendSignInLinkToEmail(this._delegate,e,t)}sendPasswordResetEmail(e,t){return r.sendPasswordResetEmail(this._delegate,e,t||void 0)}async setPersistence(e){let t;switch(b(this._delegate,e),e){case E.SESSION:t=r.browserSessionPersistence;break;case E.LOCAL:t=await r._getInstance(r.indexedDBLocalPersistence)._isAvailable()?r.indexedDBLocalPersistence:r.browserLocalPersistence;break;case E.NONE:t=r.inMemoryPersistence;break;default:return r._fail("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(t)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return F(this._delegate,r.signInAnonymously(this._delegate))}signInWithCredential(e){return F(this._delegate,r.signInWithCredential(this._delegate,e))}signInWithCustomToken(e){return F(this._delegate,r.signInWithCustomToken(this._delegate,e))}signInWithEmailAndPassword(e,t){return F(this._delegate,r.signInWithEmailAndPassword(this._delegate,e,t))}signInWithEmailLink(e,t){return F(this._delegate,r.signInWithEmailLink(this._delegate,e,t))}signInWithPhoneNumber(e,t){return V(this._delegate,r.signInWithPhoneNumber(this._delegate,e,t))}async signInWithPopup(e){return x(I(),this._delegate,"operation-not-supported-in-this-environment"),F(this._delegate,r.signInWithPopup(this._delegate,e,W))}async signInWithRedirect(e){return x(I(),this._delegate,"operation-not-supported-in-this-environment"),await k(this._delegate),r.signInWithRedirect(this._delegate,e,W)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return r.verifyPasswordResetCode(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=(()=>this)}}function H(e,t,r){let n=e;"function"!=typeof e&&({next:n,error:t,complete:r}=e);const i=n;return{next:e=>i(e&&B.getOrCreate(e)),error:t,complete:r}}function K(e,t){const n=C(e,t);if("undefined"==typeof self||n.includes(r.indexedDBLocalPersistence)||n.push(r.indexedDBLocalPersistence),"undefined"!=typeof window)for(const i of[r.browserLocalPersistence,r.browserSessionPersistence])n.includes(i)||n.push(i);return n.includes(r.inMemoryPersistence)||n.push(r.inMemoryPersistence),n}j.Persistence=E;class q{constructor(){this.providerId="phone",this._delegate=new r.PhoneAuthProvider(L(t.default.auth()))}static credential(e,t){return r.PhoneAuthProvider.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}q.PHONE_SIGN_IN_METHOD=r.PhoneAuthProvider.PHONE_SIGN_IN_METHOD,q.PROVIDER_ID=r.PhoneAuthProvider.PROVIDER_ID;const z=r._assert;class Y{constructor(e,n,i=t.default.app()){var s;z(null===(s=i.options)||void 0===s?void 0:s.apiKey,"invalid-api-key",{appName:i.name}),this._delegate=new r.RecaptchaVerifier(e,n,i.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}const J="auth-compat";function Z(e){e.INTERNAL.registerComponent(new n.Component(J,e=>{const t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new j(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:r.ActionCodeOperation.EMAIL_SIGNIN,PASSWORD_RESET:r.ActionCodeOperation.PASSWORD_RESET,RECOVER_EMAIL:r.ActionCodeOperation.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:r.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:r.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:r.ActionCodeOperation.VERIFY_EMAIL}},EmailAuthProvider:r.EmailAuthProvider,FacebookAuthProvider:r.FacebookAuthProvider,GithubAuthProvider:r.GithubAuthProvider,GoogleAuthProvider:r.GoogleAuthProvider,OAuthProvider:r.OAuthProvider,SAMLAuthProvider:r.SAMLAuthProvider,PhoneAuthProvider:q,PhoneMultiFactorGenerator:r.PhoneMultiFactorGenerator,RecaptchaVerifier:Y,TwitterAuthProvider:r.TwitterAuthProvider,Auth:j,AuthCredential:r.AuthCredential,Error:i.FirebaseError}).setInstantiationMode("LAZY").setMultipleInstances(!1)),e.registerVersion(d,u)}Z(t.default);
|
|
492
|
+
var e=arguments[3],t=o(require("@firebase/app-compat")),r=a(require("@firebase/auth/internal")),n=require("@firebase/component"),i=require("@firebase/util");function s(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(s=function(e){return e?r:t})(e)}function a(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=s(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var o=i?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(n,a,o):n[a]=e[a]}return n.default=e,r&&r.set(e,n),n}function o(e){return e&&e.__esModule?e:{default:e}}var d="@firebase/auth-compat",u="0.3.5";const l=1e3;function h(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function c(){return"http:"===h()||"https:"===h()}function g(e=(0,i.getUA)()){return!("file:"!==h()&&"ionic:"!==h()&&"capacitor:"!==h()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function p(){return(0,i.isReactNative)()||(0,i.isNode)()}function _(){return(0,i.isIE)()&&11===(null===document||void 0===document?void 0:document.documentMode)}function v(e=(0,i.getUA)()){return/Edge\/\d+/.test(e)}function f(e=(0,i.getUA)()){return _()||v(e)}function m(){try{const t=self.localStorage,n=r._generateEventId();if(t)return t.setItem(n,"1"),t.removeItem(n),!f()||(0,i.isIndexedDBAvailable)()}catch(e){return P()&&(0,i.isIndexedDBAvailable)()}return!1}function P(){return void 0!==e&&"WorkerGlobalScope"in e&&"importScripts"in e}function I(){return(c()||(0,i.isBrowserExtension)()||g())&&!p()&&m()&&!P()}function A(){return g()&&"undefined"!=typeof document}async function y(){return!!A()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},l);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})}function R(){return"undefined"!=typeof window?window:null}const E={LOCAL:"local",NONE:"none",SESSION:"session"},w=r._assert,N="persistence";function b(e,t){w(Object.values(E).includes(t),e,"invalid-persistence-type"),(0,i.isReactNative)()?w(t!==E.SESSION,e,"unsupported-persistence-type"):(0,i.isNode)()?w(t===E.NONE,e,"unsupported-persistence-type"):P()?w(t===E.NONE||t===E.LOCAL&&(0,i.isIndexedDBAvailable)(),e,"unsupported-persistence-type"):w(t===E.NONE||m(),e,"unsupported-persistence-type")}async function k(e){await e._initializationPromise;const t=O(),n=r._persistenceKeyName(N,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function C(e,t){const n=O();if(!n)return[];const i=r._persistenceKeyName(N,e,t);switch(n.getItem(i)){case E.NONE:return[r.inMemoryPersistence];case E.LOCAL:return[r.indexedDBLocalPersistence,r.browserSessionPersistence];case E.SESSION:return[r.browserSessionPersistence];default:return[]}}function O(){var e;try{return(null===(e=R())||void 0===e?void 0:e.sessionStorage)||null}catch(t){return null}}const S=r._assert;class W{constructor(){this.browserResolver=r._getInstance(r.browserPopupRedirectResolver),this.cordovaResolver=r._getInstance(r.cordovaPopupRedirectResolver),this.underlyingResolver=null,this._redirectPersistence=r.browserSessionPersistence,this._completeRedirectFn=r._getRedirectResult,this._overrideRedirectResult=r._overrideRedirectResult}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,r,n)}async _openRedirect(e,t,r,n){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,r,n)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return A()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return S(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){if(this.underlyingResolver)return;const e=await y();this.underlyingResolver=e?this.cordovaResolver:this.browserResolver}}function L(e){return e.unwrap()}function T(e){return e.wrapped()}function M(e){return U(e)}function D(e,t){var n;const i=null===(n=t.customData)||void 0===n?void 0:n._tokenResponse;if("auth/multi-factor-auth-required"===(null==t?void 0:t.code)){t.resolver=new G(e,r.getMultiFactorResolver(e,t))}else if(i){const e=U(t),r=t;e&&(r.credential=e,r.tenantId=i.tenantId||void 0,r.email=i.email||void 0,r.phoneNumber=i.phoneNumber||void 0)}}function U(e){const{_tokenResponse:t}=e instanceof i.FirebaseError?e.customData:e;if(!t)return null;if(!(e instanceof i.FirebaseError)&&"temporaryProof"in t&&"phoneNumber"in t)return r.PhoneAuthProvider.credentialFromResult(e);const n=t.providerId;if(!n||n===r.ProviderId.PASSWORD)return null;let s;switch(n){case r.ProviderId.GOOGLE:s=r.GoogleAuthProvider;break;case r.ProviderId.FACEBOOK:s=r.FacebookAuthProvider;break;case r.ProviderId.GITHUB:s=r.GithubAuthProvider;break;case r.ProviderId.TWITTER:s=r.TwitterAuthProvider;break;default:const{oauthIdToken:e,oauthAccessToken:i,oauthTokenSecret:a,pendingToken:o,nonce:d}=t;return i||a||e||o?o?n.startsWith("saml.")?r.SAMLAuthCredential._create(n,o):r.OAuthCredential._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:e,accessToken:i}):new r.OAuthProvider(n).credential({idToken:e,accessToken:i,rawNonce:d}):null}return e instanceof i.FirebaseError?s.credentialFromError(e):s.credentialFromResult(e)}function F(e,t){return t.catch(t=>{throw t instanceof i.FirebaseError&&D(e,t),t}).then(e=>{const t=e.operationType,n=e.user;return{operationType:t,credential:M(e),additionalUserInfo:r.getAdditionalUserInfo(e),user:B.getOrCreate(n)}})}async function V(e,t){const r=await t;return{verificationId:r.verificationId,confirm:t=>F(e,r.confirm(t))}}class G{constructor(e,t){this.resolver=t,this.auth=T(e)}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return F(L(this.auth),this.resolver.resolveSignIn(e))}}class B{constructor(e){this._delegate=e,this.multiFactor=r.multiFactor(e)}static getOrCreate(e){return B.USER_MAP.has(e)||B.USER_MAP.set(e,new B(e)),B.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return F(this.auth,r.linkWithCredential(this._delegate,e))}async linkWithPhoneNumber(e,t){return V(this.auth,r.linkWithPhoneNumber(this._delegate,e,t))}async linkWithPopup(e){return F(this.auth,r.linkWithPopup(this._delegate,e,W))}async linkWithRedirect(e){return await k(r._castAuth(this.auth)),r.linkWithRedirect(this._delegate,e,W)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return F(this.auth,r.reauthenticateWithCredential(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return V(this.auth,r.reauthenticateWithPhoneNumber(this._delegate,e,t))}reauthenticateWithPopup(e){return F(this.auth,r.reauthenticateWithPopup(this._delegate,e,W))}async reauthenticateWithRedirect(e){return await k(r._castAuth(this.auth)),r.reauthenticateWithRedirect(this._delegate,e,W)}sendEmailVerification(e){return r.sendEmailVerification(this._delegate,e)}async unlink(e){return await r.unlink(this._delegate,e),this}updateEmail(e){return r.updateEmail(this._delegate,e)}updatePassword(e){return r.updatePassword(this._delegate,e)}updatePhoneNumber(e){return r.updatePhoneNumber(this._delegate,e)}updateProfile(e){return r.updateProfile(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return r.verifyBeforeUpdateEmail(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}B.USER_MAP=new WeakMap;const x=r._assert;class j{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();const{apiKey:n}=e.options;x(n,"invalid-api-key",{appName:e.name}),x(n,"invalid-api-key",{appName:e.name});const i="undefined"!=typeof window?W:void 0;this._delegate=t.initialize({options:{persistence:K(n,e.name),popupRedirectResolver:i}}),this._delegate._updateErrorMap(r.debugErrorMap),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?B.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){r.connectAuthEmulator(this._delegate,e,t)}applyActionCode(e){return r.applyActionCode(this._delegate,e)}checkActionCode(e){return r.checkActionCode(this._delegate,e)}confirmPasswordReset(e,t){return r.confirmPasswordReset(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return F(this._delegate,r.createUserWithEmailAndPassword(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return r.fetchSignInMethodsForEmail(this._delegate,e)}isSignInWithEmailLink(e){return r.isSignInWithEmailLink(this._delegate,e)}async getRedirectResult(){x(I(),this._delegate,"operation-not-supported-in-this-environment");const e=await r.getRedirectResult(this._delegate,W);return e?F(this._delegate,Promise.resolve(e)):{credential:null,user:null}}addFrameworkForLogging(e){r.addFrameworkForLogging(this._delegate,e)}onAuthStateChanged(e,t,r){const{next:n,error:i,complete:s}=H(e,t,r);return this._delegate.onAuthStateChanged(n,i,s)}onIdTokenChanged(e,t,r){const{next:n,error:i,complete:s}=H(e,t,r);return this._delegate.onIdTokenChanged(n,i,s)}sendSignInLinkToEmail(e,t){return r.sendSignInLinkToEmail(this._delegate,e,t)}sendPasswordResetEmail(e,t){return r.sendPasswordResetEmail(this._delegate,e,t||void 0)}async setPersistence(e){let t;switch(b(this._delegate,e),e){case E.SESSION:t=r.browserSessionPersistence;break;case E.LOCAL:t=await r._getInstance(r.indexedDBLocalPersistence)._isAvailable()?r.indexedDBLocalPersistence:r.browserLocalPersistence;break;case E.NONE:t=r.inMemoryPersistence;break;default:return r._fail("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(t)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return F(this._delegate,r.signInAnonymously(this._delegate))}signInWithCredential(e){return F(this._delegate,r.signInWithCredential(this._delegate,e))}signInWithCustomToken(e){return F(this._delegate,r.signInWithCustomToken(this._delegate,e))}signInWithEmailAndPassword(e,t){return F(this._delegate,r.signInWithEmailAndPassword(this._delegate,e,t))}signInWithEmailLink(e,t){return F(this._delegate,r.signInWithEmailLink(this._delegate,e,t))}signInWithPhoneNumber(e,t){return V(this._delegate,r.signInWithPhoneNumber(this._delegate,e,t))}async signInWithPopup(e){return x(I(),this._delegate,"operation-not-supported-in-this-environment"),F(this._delegate,r.signInWithPopup(this._delegate,e,W))}async signInWithRedirect(e){return x(I(),this._delegate,"operation-not-supported-in-this-environment"),await k(this._delegate),r.signInWithRedirect(this._delegate,e,W)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return r.verifyPasswordResetCode(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=(()=>this)}}function H(e,t,r){let n=e;"function"!=typeof e&&({next:n,error:t,complete:r}=e);const i=n;return{next:e=>i(e&&B.getOrCreate(e)),error:t,complete:r}}function K(e,t){const n=C(e,t);if("undefined"==typeof self||n.includes(r.indexedDBLocalPersistence)||n.push(r.indexedDBLocalPersistence),"undefined"!=typeof window)for(const i of[r.browserLocalPersistence,r.browserSessionPersistence])n.includes(i)||n.push(i);return n.includes(r.inMemoryPersistence)||n.push(r.inMemoryPersistence),n}j.Persistence=E;class q{constructor(){this.providerId="phone",this._delegate=new r.PhoneAuthProvider(L(t.default.auth()))}static credential(e,t){return r.PhoneAuthProvider.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}q.PHONE_SIGN_IN_METHOD=r.PhoneAuthProvider.PHONE_SIGN_IN_METHOD,q.PROVIDER_ID=r.PhoneAuthProvider.PROVIDER_ID;const z=r._assert;class Y{constructor(e,n,i=t.default.app()){var s;z(null===(s=i.options)||void 0===s?void 0:s.apiKey,"invalid-api-key",{appName:i.name}),this._delegate=new r.RecaptchaVerifier(e,n,i.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}const J="auth-compat";function Z(e){e.INTERNAL.registerComponent(new n.Component(J,e=>{const t=e.getProvider("app-compat").getImmediate(),r=e.getProvider("auth");return new j(t,r)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:r.ActionCodeOperation.EMAIL_SIGNIN,PASSWORD_RESET:r.ActionCodeOperation.PASSWORD_RESET,RECOVER_EMAIL:r.ActionCodeOperation.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:r.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:r.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:r.ActionCodeOperation.VERIFY_EMAIL}},EmailAuthProvider:r.EmailAuthProvider,FacebookAuthProvider:r.FacebookAuthProvider,GithubAuthProvider:r.GithubAuthProvider,GoogleAuthProvider:r.GoogleAuthProvider,OAuthProvider:r.OAuthProvider,SAMLAuthProvider:r.SAMLAuthProvider,PhoneAuthProvider:q,PhoneMultiFactorGenerator:r.PhoneMultiFactorGenerator,RecaptchaVerifier:Y,TwitterAuthProvider:r.TwitterAuthProvider,Auth:j,AuthCredential:r.AuthCredential,Error:i.FirebaseError}).setInstantiationMode("LAZY").setMultipleInstances(!1)),e.registerVersion(d,u)}Z(t.default);
|
|
493
493
|
},{"@firebase/app-compat":"CMFQ","@firebase/auth/internal":"eL7N","@firebase/component":"vhY9","@firebase/util":"chA2"}],"hycF":[function(require,module,exports) {
|
|
494
494
|
"use strict";require("@firebase/auth-compat");
|
|
495
495
|
},{"@firebase/auth-compat":"h9Y9"}],"AvWE":[function(require,module,exports) {
|
|
496
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.connectFunctionsEmulator=S,exports.getFunctions=v,exports.httpsCallable=P,exports.httpsCallableFromURL=x;var e=require("@firebase/app"),t=require("@firebase/util"),n=require("@firebase/component");const r="type.googleapis.com/google.protobuf.Int64Value",i="type.googleapis.com/google.protobuf.UInt64Value";function o(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function s(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>s(e));if("function"==typeof e||"object"==typeof e)return o(e,e=>s(e));throw new Error("Data cannot be encoded in JSON: "+e)}function a(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case r:case i:{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>a(e)):"function"==typeof e||"object"==typeof e?o(e,e=>a(e)):e}const u="functions",c={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 l extends t.FirebaseError{constructor(e,t,n){super(`${u}/${e}`,t||""),this.details=n}}function h(e){if(e>=200&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}function d(e,t){let n=h(e),r=n,i=void 0;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!c[t])return new l("internal","internal");n=c[t],r=t}const o=e.message;"string"==typeof o&&(r=o),void 0!==(i=e.details)&&(i=a(i))}}catch(o){}return"ok"===n?null:new l(n,r,i)}class p{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{const t=await this.auth.getToken();return null==t?void 0:t.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){const e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const g="us-central1";function f(e){let t=null;return{promise:new Promise((n,r)=>{t=setTimeout(()=>{r(new l("deadline-exceeded","deadline-exceeded"))},e)}),cancel:()=>{t&&clearTimeout(t)}}}class m{constructor(e,t,n,r,i=g,o){this.app=e,this.fetchImpl=o,this.emulatorOrigin=null,this.contextProvider=new p(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=(()=>Promise.resolve(e()))});try{const e=new URL(i);this.customDomain=e.origin,this.region=g}catch(s){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;if(null!==this.emulatorOrigin){return`${this.emulatorOrigin}/${t}/${this.region}/${e}`}return null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function k(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}function w(e,t,n){return r=>y(e,t,r,n||{})}function T(e,t,n){return r=>I(e,t,r,n||{})}async function E(e,t,n,r){let i;n["Content-Type"]="application/json";try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(s){return{status:0,json:null}}let o=null;try{o=await i.json()}catch(s){}return{status:i.status,json:o}}function y(e,t,n,r){const i=e._url(t);return I(e,i,n,r)}async function I(e,t,n,r){const i={data:n=s(n)},o={},u=await e.contextProvider.getContext();u.authToken&&(o.Authorization="Bearer "+u.authToken),u.messagingToken&&(o["Firebase-Instance-ID-Token"]=u.messagingToken),null!==u.appCheckToken&&(o["X-Firebase-AppCheck"]=u.appCheckToken);const c=f(r.timeout||7e4),h=await Promise.race([E(t,i,o,e.fetchImpl),c.promise,e.cancelAllRequests]);if(c.cancel(),!h)throw new l("cancelled","Firebase Functions instance was deleted.");const p=d(h.status,h.json);if(p)throw p;if(!h.json)throw new l("internal","Response is not valid JSON object.");let g=h.json.data;if(void 0===g&&(g=h.json.result),void 0===g)throw new l("internal","Response is missing data field.");return{data:a(g)}}const A="@firebase/functions",N="0.9.
|
|
496
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.connectFunctionsEmulator=S,exports.getFunctions=v,exports.httpsCallable=P,exports.httpsCallableFromURL=x;var e=require("@firebase/app"),t=require("@firebase/util"),n=require("@firebase/component");const r="type.googleapis.com/google.protobuf.Int64Value",i="type.googleapis.com/google.protobuf.UInt64Value";function o(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function s(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>s(e));if("function"==typeof e||"object"==typeof e)return o(e,e=>s(e));throw new Error("Data cannot be encoded in JSON: "+e)}function a(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case r:case i:{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>a(e)):"function"==typeof e||"object"==typeof e?o(e,e=>a(e)):e}const u="functions",c={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 l extends t.FirebaseError{constructor(e,t,n){super(`${u}/${e}`,t||""),this.details=n}}function h(e){if(e>=200&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}function d(e,t){let n=h(e),r=n,i=void 0;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!c[t])return new l("internal","internal");n=c[t],r=t}const o=e.message;"string"==typeof o&&(r=o),void 0!==(i=e.details)&&(i=a(i))}}catch(o){}return"ok"===n?null:new l(n,r,i)}class p{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{const t=await this.auth.getToken();return null==t?void 0:t.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){const e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const g="us-central1";function f(e){let t=null;return{promise:new Promise((n,r)=>{t=setTimeout(()=>{r(new l("deadline-exceeded","deadline-exceeded"))},e)}),cancel:()=>{t&&clearTimeout(t)}}}class m{constructor(e,t,n,r,i=g,o){this.app=e,this.fetchImpl=o,this.emulatorOrigin=null,this.contextProvider=new p(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=(()=>Promise.resolve(e()))});try{const e=new URL(i);this.customDomain=e.origin,this.region=g}catch(s){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;if(null!==this.emulatorOrigin){return`${this.emulatorOrigin}/${t}/${this.region}/${e}`}return null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}function k(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}function w(e,t,n){return r=>y(e,t,r,n||{})}function T(e,t,n){return r=>I(e,t,r,n||{})}async function E(e,t,n,r){let i;n["Content-Type"]="application/json";try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(s){return{status:0,json:null}}let o=null;try{o=await i.json()}catch(s){}return{status:i.status,json:o}}function y(e,t,n,r){const i=e._url(t);return I(e,i,n,r)}async function I(e,t,n,r){const i={data:n=s(n)},o={},u=await e.contextProvider.getContext();u.authToken&&(o.Authorization="Bearer "+u.authToken),u.messagingToken&&(o["Firebase-Instance-ID-Token"]=u.messagingToken),null!==u.appCheckToken&&(o["X-Firebase-AppCheck"]=u.appCheckToken);const c=f(r.timeout||7e4),h=await Promise.race([E(t,i,o,e.fetchImpl),c.promise,e.cancelAllRequests]);if(c.cancel(),!h)throw new l("cancelled","Firebase Functions instance was deleted.");const p=d(h.status,h.json);if(p)throw p;if(!h.json)throw new l("internal","Response is not valid JSON object.");let g=h.json.data;if(void 0===g&&(g=h.json.result),void 0===g)throw new l("internal","Response is missing data field.");return{data:a(g)}}const A="@firebase/functions",N="0.9.4",b="auth-internal",D="app-check-internal",O="messaging-internal";function C(t,r){(0,e._registerComponent)(new n.Component(u,(e,{instanceIdentifier:n})=>{const r=e.getProvider("app").getImmediate(),i=e.getProvider(b),o=e.getProvider(O),s=e.getProvider(D);return new m(r,i,o,s,n,t)},"PUBLIC").setMultipleInstances(!0)),(0,e.registerVersion)(A,N,r),(0,e.registerVersion)(A,N,"esm2017")}function v(n=(0,e.getApp)(),r=g){const i=(0,e._getProvider)((0,t.getModularInstance)(n),u).getImmediate({identifier:r}),o=(0,t.getDefaultEmulatorHostnameAndPort)("functions");return o&&S(i,...o),i}function S(e,n,r){k((0,t.getModularInstance)(e),n,r)}function P(e,n,r){return w((0,t.getModularInstance)(e),n,r)}function x(e,n,r){return T((0,t.getModularInstance)(e),n,r)}C(fetch.bind(self));
|
|
497
497
|
},{"@firebase/app":"h2Mb","@firebase/util":"chA2","@firebase/component":"vhY9"}],"F0p3":[function(require,module,exports) {
|
|
498
|
-
"use strict";var e=i(require("@firebase/app-compat")),t=require("@firebase/functions"),n=require("@firebase/util"),r=require("@firebase/component");function i(e){return e&&e.__esModule?e:{default:e}}const o="@firebase/functions-compat",s="0.3.
|
|
498
|
+
"use strict";var e=i(require("@firebase/app-compat")),t=require("@firebase/functions"),n=require("@firebase/util"),r=require("@firebase/component");function i(e){return e&&e.__esModule?e:{default:e}}const o="@firebase/functions-compat",s="0.3.4";class a{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,n){return(0,t.httpsCallable)(this._delegate,e,n)}httpsCallableFromURL(e,n){return(0,t.httpsCallableFromURL)(this._delegate,e,n)}useFunctionsEmulator(e){const r=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==r)throw new n.FirebaseError("functions","No origin provided to useFunctionsEmulator()");if(null==r[2])throw new n.FirebaseError("functions","Port missing in origin provided to useFunctionsEmulator()");return(0,t.connectFunctionsEmulator)(this._delegate,r[1],Number(r[2]))}useEmulator(e,n){return(0,t.connectFunctionsEmulator)(this._delegate,e,n)}}const u="us-central1",l=(e,{instanceIdentifier:t})=>{const n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:"us-central1"});return new a(n,r)};function c(){const t={Functions:a};e.default.INTERNAL.registerComponent(new r.Component("functions-compat",l,"PUBLIC").setServiceProps(t).setMultipleInstances(!0))}c(),e.default.registerVersion(o,"0.3.4");
|
|
499
499
|
},{"@firebase/app-compat":"CMFQ","@firebase/functions":"AvWE","@firebase/util":"chA2","@firebase/component":"vhY9"}],"O8Yj":[function(require,module,exports) {
|
|
500
500
|
"use strict";require("@firebase/functions-compat");
|
|
501
501
|
},{"@firebase/functions-compat":"F0p3"}],"qQDx":[function(require,module,exports) {
|
|
@@ -504,9 +504,9 @@ var t=arguments[3];Object.defineProperty(exports,"__esModule",{value:!0}),export
|
|
|
504
504
|
},{}],"lBbe":[function(require,module,exports) {
|
|
505
505
|
var define;
|
|
506
506
|
var process = require("process");
|
|
507
|
-
var e,t=require("process");Object.defineProperty(exports,"__esModule",{value:!0}),exports._FieldPath=exports._EmptyAuthCredentialsProvider=exports._EmptyAppCheckTokenProvider=exports._DocumentKey=exports._DatabaseId=exports.WriteBatch=exports.Transaction=exports.Timestamp=exports.SnapshotMetadata=exports.QueryStartAtConstraint=exports.QuerySnapshot=exports.QueryOrderByConstraint=exports.QueryLimitConstraint=exports.QueryFieldFilterConstraint=exports.QueryEndAtConstraint=exports.QueryDocumentSnapshot=exports.QueryConstraint=exports.QueryCompositeFilterConstraint=exports.Query=exports.LoadBundleTask=exports.GeoPoint=exports.FirestoreError=exports.Firestore=exports.FieldValue=exports.FieldPath=exports.DocumentSnapshot=exports.DocumentReference=exports.CollectionReference=exports.CACHE_SIZE_UNLIMITED=exports.Bytes=exports.AggregateQuerySnapshot=exports.AggregateField=exports.AbstractUserDataWriter=void 0,exports._cast=bc,exports._debugAssert=W,exports._isBase64Available=et,exports._logWarn=K,exports._validateIsNotUsedTogether=gc,exports.addDoc=nh,exports.aggregateQuerySnapshotEqual=oh,exports.and=kf,exports.arrayRemove=mh,exports.arrayUnion=ph,exports.clearIndexedDbPersistence=bl,exports.collection=Nc,exports.collectionGroup=Pc,exports.connectFirestoreEmulator=_c,exports.deleteDoc=th,exports.deleteField=vh,exports.disableNetwork=Tl,exports.doc=Lc,exports.documentId=Pl,exports.enableIndexedDbPersistence=kl,exports.enableMultiTabIndexedDbPersistence=wl,exports.enableNetwork=El,exports.endAt=Cf,exports.endBefore=Af,exports.ensureFirestoreConfigured=ml,exports.executeWrite=ah,exports.getCountFromServer=sh,exports.getDoc=zf,exports.getDocFromCache=Hf,exports.getDocFromServer=Yf,exports.getDocs=Xf,exports.getDocsFromCache=Zf,exports.getDocsFromServer=Jf,exports.getFirestore=pl,exports.increment=gh,exports.initializeFirestore=yl,exports.limit=If,exports.limitToLast=Ef,exports.loadBundle=_l,exports.namedQuery=Dl,exports.onSnapshot=rh,exports.onSnapshotsInSync=ih,exports.or=gf,exports.orderBy=xf,exports.query=vf,exports.queryEqual=Mc,exports.refEqual=Fc,exports.runTransaction=dh,exports.serverTimestamp=yh,exports.setDoc=$f,exports.setIndexConfiguration=wh,exports.setLogLevel=U,exports.snapshotEqual=jf,exports.startAfter=_f,exports.startAt=Sf,exports.terminate=Sl,exports.updateDoc=eh,exports.waitForPendingWrites=Il,exports.where=pf,exports.writeBatch=kh;var n=require("@firebase/app"),r=require("@firebase/component"),i=require("@firebase/logger"),a=require("@firebase/util"),u=require("@firebase/webchannel-wrapper");function o(e,t,n){return(o=x()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&m(i,n.prototype),i}).apply(null,arguments)}function s(){return(s="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=c(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}}).apply(this,arguments)}function c(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=b(e)););return e}function l(e,t){return d(e)||h(e,t)||T(e,t)||f()}function f(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function h(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,u,o=[],s=!0,c=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;s=!1}else for(;!(s=(r=a.call(n)).done)&&(o.push(r.value),o.length!==t);s=!0);}catch(l){c=!0,i=l}finally{try{if(!s&&null!=n.return&&(u=n.return(),Object(u)!==u))return}finally{if(c)throw i}}return o}}function d(e){if(Array.isArray(e))return e}function v(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=T(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,u=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return u=e.done,e},e:function(e){o=!0,a=e},f:function(){try{u||null==n.return||n.return()}finally{if(o)throw a}}}}function y(){"use strict";y=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r=Object.defineProperty||function(e,t,n){e[t]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",o=i.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(C){s=function(e,t,n){return e[t]=n}}function c(e,t,n,i){var a=t&&t.prototype instanceof h?t:h,u=Object.create(a.prototype),o=new S(i||[]);return r(u,"_invoke",{value:b(e,n,o)}),u}function l(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(C){return{type:"throw",arg:C}}}e.wrap=c;var f={};function h(){}function d(){}function v(){}var p={};s(p,a,function(){return this});var m=Object.getPrototypeOf,g=m&&m(m(_([])));g&&g!==t&&n.call(g,a)&&(p=g);var k=v.prototype=h.prototype=Object.create(p);function w(e){["next","throw","return"].forEach(function(t){s(e,t,function(e){return this._invoke(t,e)})})}function x(e,t){var i;r(this,"_invoke",{value:function(r,a){function u(){return new t(function(i,u){!function r(i,a,u,o){var s=l(e[i],e,a);if("throw"!==s.type){var c=s.arg,f=c.value;return f&&"object"==A(f)&&n.call(f,"__await")?t.resolve(f.__await).then(function(e){r("next",e,u,o)},function(e){r("throw",e,u,o)}):t.resolve(f).then(function(e){c.value=e,u(c)},function(e){return r("throw",e,u,o)})}o(s.arg)}(r,a,i,u)})}return i=i?i.then(u,u):u()}})}function b(e,t,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return D()}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var o=I(u,n);if(o){if(o===f)continue;return o}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var s=l(e,t,n);if("normal"===s.type){if(r=n.done?"completed":"suspendedYield",s.arg===f)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(r="completed",n.method="throw",n.arg=s.arg)}}}function I(e,t){var n=t.method,r=e.iterator[n];if(void 0===r)return t.delegate=null,"throw"===n&&e.iterator.return&&(t.method="return",t.arg=void 0,I(e,t),"throw"===t.method)||"return"!==n&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+n+"' method")),f;var i=l(r,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,f;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function E(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function S(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(E,this),this.reset(!0)}function _(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return i.next=i}}return{next:D}}function D(){return{value:void 0,done:!0}}return d.prototype=v,r(k,"constructor",{value:v,configurable:!0}),r(v,"constructor",{value:d,configurable:!0}),d.displayName=s(v,o,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,s(e,o,"GeneratorFunction")),e.prototype=Object.create(k),e},e.awrap=function(e){return{__await:e}},w(x.prototype),s(x.prototype,u,function(){return this}),e.AsyncIterator=x,e.async=function(t,n,r,i,a){void 0===a&&(a=Promise);var u=new x(c(t,n,r,i),a);return e.isGeneratorFunction(n)?u:u.next().then(function(e){return e.done?e.value:u.next()})},w(k),s(k,o,"Generator"),s(k,a,function(){return this}),s(k,"toString",function(){return"[object Generator]"}),e.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},e.values=_,S.prototype={constructor:S,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!e)for(var t in this)"t"===t.charAt(0)&&n.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(n,r){return u.type="throw",u.arg=e,t.next=n,r&&(t.method="next",t.arg=void 0),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var o=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(o&&s){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(o){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var u=a?a.completion:{};return u.type=e,u.arg=t,a?(this.method="next",this.next=a.finallyLoc,f):this.complete(u)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),T(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;T(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:_(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},e}function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&m(e,t)}function m(e,t){return(m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function g(e){var t=x();return function(){var n,r=b(e);if(t){var i=b(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return k(this,n)}}function k(e,t){if(t&&("object"===A(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return w(e)}function w(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function x(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function b(e){return(b=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function I(e){return _(e)||S(e)||T(e)||E()}function E(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function T(e,t){if(e){if("string"==typeof e)return D(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}function S(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _(e){if(Array.isArray(e))return D(e)}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function A(e){return(A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function N(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,L(r.key),r)}}function P(e,t,n){return t&&N(e.prototype,t),n&&N(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e){var t=F(e,"string");return"symbol"===A(t)?t:String(t)}function F(e,t){if("object"!==A(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!==A(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}var M="@firebase/firestore",R=function(){function e(t){C(this,e),this.uid=t}return P(e,[{key:"isAuthenticated",value:function(){return null!=this.uid}},{key:"toKey",value:function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}},{key:"isEqual",value:function(e){return e.uid===this.uid}}]),e}();R.UNAUTHENTICATED=new R(null),R.GOOGLE_CREDENTIALS=new R("google-credentials-uid"),R.FIRST_PARTY=new R("first-party-uid"),R.MOCK_USER=new R("mock-user");var V="9.17.1",O=new i.Logger("@firebase/firestore");function q(){return O.logLevel}function U(e){O.setLogLevel(e)}function B(e){if(O.logLevel<=i.LogLevel.DEBUG){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a=n.map(Q);O.debug.apply(O,["Firestore (".concat(V,"): ").concat(e)].concat(I(a)))}}function G(e){if(O.logLevel<=i.LogLevel.ERROR){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a=n.map(Q);O.error.apply(O,["Firestore (".concat(V,"): ").concat(e)].concat(I(a)))}}function K(e){if(O.logLevel<=i.LogLevel.WARN){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a=n.map(Q);O.warn.apply(O,["Firestore (".concat(V,"): ").concat(e)].concat(I(a)))}}function Q(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}var t}function j(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected state",t="FIRESTORE (".concat(V,") INTERNAL ASSERTION FAILED: ")+e;throw G(t),new Error(t)}function z(e,t){e||j()}function W(e,t){e||j()}function H(e,t){return e}var Y={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"},X=function(e){p(n,a.FirebaseError);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e,r)).code=e,i.message=r,i.toString=function(){return"".concat(i.name,": [code=").concat(i.code,"]: ").concat(i.message)},i}return P(n)}();exports.FirestoreError=X;var Z=P(function e(){var t=this;C(this,e),this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}),J=P(function e(t,n){C(this,e),this.user=n,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer ".concat(t))}),$=function(){function e(){C(this,e)}return P(e,[{key:"getToken",value:function(){return Promise.resolve(null)}},{key:"invalidateToken",value:function(){}},{key:"start",value:function(e,t){e.enqueueRetryable(function(){return t(R.UNAUTHENTICATED)})}},{key:"shutdown",value:function(){}}]),e}();exports._EmptyAuthCredentialsProvider=$;var ee=function(){function e(t){C(this,e),this.token=t,this.changeListener=null}return P(e,[{key:"getToken",value:function(){return Promise.resolve(this.token)}},{key:"invalidateToken",value:function(){}},{key:"start",value:function(e,t){var n=this;this.changeListener=t,e.enqueueRetryable(function(){return t(n.token.user)})}},{key:"shutdown",value:function(){this.changeListener=null}}]),e}(),te=function(){function e(t){C(this,e),this.t=t,this.currentUser=R.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}return P(e,[{key:"start",value:function(e,t){var n=this,r=this.i,i=function(e){return n.i!==r?(r=n.i,t(e)):Promise.resolve()},a=new Z;this.o=function(){n.i++,n.currentUser=n.u(),a.resolve(),a=new Z,e.enqueueRetryable(function(){return i(n.currentUser)})};var u=function(){var t=a;e.enqueueRetryable(function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,y().awrap(t.promise);case 2:return e.next=4,y().awrap(i(n.currentUser));case 4:case"end":return e.stop()}},null,null,null,Promise)})},o=function(e){B("FirebaseAuthCredentialsProvider","Auth detected"),n.auth=e,n.auth.addAuthTokenListener(n.o),u()};this.t.onInit(function(e){return o(e)}),setTimeout(function(){if(!n.auth){var e=n.t.getImmediate({optional:!0});e?o(e):(B("FirebaseAuthCredentialsProvider","Auth not yet detected"),a.resolve(),a=new Z)}},0),u()}},{key:"getToken",value:function(){var e=this,t=this.i,n=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(n).then(function(n){return e.i!==t?(B("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),e.getToken()):n?(z("string"==typeof n.accessToken),new J(n.accessToken,e.currentUser)):null}):Promise.resolve(null)}},{key:"invalidateToken",value:function(){this.forceRefresh=!0}},{key:"shutdown",value:function(){this.auth&&this.auth.removeAuthTokenListener(this.o)}},{key:"u",value:function(){var e=this.auth&&this.auth.getUid();return z(null===e||"string"==typeof e),new R(e)}}]),e}(),ne=function(){function e(t,n,r,i){C(this,e),this.h=t,this.l=n,this.m=r,this.g=i,this.type="FirstParty",this.user=R.FIRST_PARTY,this.p=new Map}return P(e,[{key:"I",value:function(){return this.g?this.g():(z(!("object"!=A(this.h)||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}},{key:"headers",get:function(){this.p.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}]),e}(),re=function(){function e(t,n,r,i){C(this,e),this.h=t,this.l=n,this.m=r,this.g=i}return P(e,[{key:"getToken",value:function(){return Promise.resolve(new ne(this.h,this.l,this.m,this.g))}},{key:"start",value:function(e,t){e.enqueueRetryable(function(){return t(R.FIRST_PARTY)})}},{key:"shutdown",value:function(){}},{key:"invalidateToken",value:function(){}}]),e}(),ie=P(function e(t){C(this,e),this.value=t,this.type="AppCheck",this.headers=new Map,t&&t.length>0&&this.headers.set("x-firebase-appcheck",this.value)}),ae=function(){function e(t){C(this,e),this.T=t,this.forceRefresh=!1,this.appCheck=null,this.A=null}return P(e,[{key:"start",value:function(e,t){var n=this,r=function(e){null!=e.error&&B("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: ".concat(e.error.message));var r=e.token!==n.A;return n.A=e.token,B("FirebaseAppCheckTokenProvider","Received ".concat(r?"new":"existing"," token.")),r?t(e.token):Promise.resolve()};this.o=function(t){e.enqueueRetryable(function(){return r(t)})};var i=function(e){B("FirebaseAppCheckTokenProvider","AppCheck detected"),n.appCheck=e,n.appCheck.addTokenListener(n.o)};this.T.onInit(function(e){return i(e)}),setTimeout(function(){if(!n.appCheck){var e=n.T.getImmediate({optional:!0});e?i(e):B("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}},{key:"getToken",value:function(){var e=this,t=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(t).then(function(t){return t?(z("string"==typeof t.token),e.A=t.token,new ie(t.token)):null}):Promise.resolve(null)}},{key:"invalidateToken",value:function(){this.forceRefresh=!0}},{key:"shutdown",value:function(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}]),e}(),ue=function(){function e(){C(this,e)}return P(e,[{key:"getToken",value:function(){return Promise.resolve(new ie(""))}},{key:"invalidateToken",value:function(){}},{key:"start",value:function(e,t){}},{key:"shutdown",value:function(){}}]),e}();function oe(e){var t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(var r=0;r<e;r++)n[r]=Math.floor(256*Math.random());return n}exports._EmptyAppCheckTokenProvider=ue;var se=function(){function e(){C(this,e)}return P(e,null,[{key:"R",value:function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Math.floor(256/e.length)*e.length,n="";n.length<20;)for(var r=oe(40),i=0;i<r.length;++i)n.length<20&&r[i]<t&&(n+=e.charAt(r[i]%e.length));return n}}]),e}();function ce(e,t){return e<t?-1:e>t?1:0}function le(e,t,n){return e.length===t.length&&e.every(function(e,r){return n(e,t[r])})}function fe(e){return e+"\0"}var he=function(){function e(t,n){if(C(this,e),this.seconds=t,this.nanoseconds=n,n<0)throw new X(Y.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+n);if(n>=1e9)throw new X(Y.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+n);if(t<-62135596800)throw new X(Y.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new X(Y.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}return P(e,[{key:"toDate",value:function(){return new Date(this.toMillis())}},{key:"toMillis",value:function(){return 1e3*this.seconds+this.nanoseconds/1e6}},{key:"_compareTo",value:function(e){return this.seconds===e.seconds?ce(this.nanoseconds,e.nanoseconds):ce(this.seconds,e.seconds)}},{key:"isEqual",value:function(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}},{key:"toString",value:function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}},{key:"toJSON",value:function(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}},{key:"valueOf",value:function(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}],[{key:"now",value:function(){return e.fromMillis(Date.now())}},{key:"fromDate",value:function(t){return e.fromMillis(t.getTime())}},{key:"fromMillis",value:function(t){var n=Math.floor(t/1e3);return new e(n,Math.floor(1e6*(t-1e3*n)))}}]),e}();exports.Timestamp=he;var de=function(){function e(t){C(this,e),this.timestamp=t}return P(e,[{key:"compareTo",value:function(e){return this.timestamp._compareTo(e.timestamp)}},{key:"isEqual",value:function(e){return this.timestamp.isEqual(e.timestamp)}},{key:"toMicroseconds",value:function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}},{key:"toString",value:function(){return"SnapshotVersion("+this.timestamp.toString()+")"}},{key:"toTimestamp",value:function(){return this.timestamp}}],[{key:"fromTimestamp",value:function(t){return new e(t)}},{key:"min",value:function(){return new e(new he(0,0))}},{key:"max",value:function(){return new e(new he(253402300799,999999999))}}]),e}(),ve=function(){function e(t,n,r){C(this,e),void 0===n?n=0:n>t.length&&j(),void 0===r?r=t.length-n:r>t.length-n&&j(),this.segments=t,this.offset=n,this.len=r}return P(e,[{key:"length",get:function(){return this.len}},{key:"isEqual",value:function(t){return 0===e.comparator(this,t)}},{key:"child",value:function(t){var n=this.segments.slice(this.offset,this.limit());return t instanceof e?t.forEach(function(e){n.push(e)}):n.push(t),this.construct(n)}},{key:"limit",value:function(){return this.offset+this.length}},{key:"popFirst",value:function(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}},{key:"popLast",value:function(){return this.construct(this.segments,this.offset,this.length-1)}},{key:"firstSegment",value:function(){return this.segments[this.offset]}},{key:"lastSegment",value:function(){return this.get(this.length-1)}},{key:"get",value:function(e){return this.segments[this.offset+e]}},{key:"isEmpty",value:function(){return 0===this.length}},{key:"isPrefixOf",value:function(e){if(e.length<this.length)return!1;for(var t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}},{key:"isImmediateParentOf",value:function(e){if(this.length+1!==e.length)return!1;for(var t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}},{key:"forEach",value:function(e){for(var t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}},{key:"toArray",value:function(){return this.segments.slice(this.offset,this.limit())}}],[{key:"comparator",value:function(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var i=e.get(r),a=t.get(r);if(i<a)return-1;if(i>a)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}]),e}(),ye=function(e){p(n,ve);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n,[{key:"construct",value:function(e,t,r){return new n(e,t,r)}},{key:"canonicalString",value:function(){return this.toArray().join("/")}},{key:"toString",value:function(){return this.canonicalString()}}],[{key:"fromString",value:function(){for(var e=[],t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];for(var a=0,u=r;a<u.length;a++){var o=u[a];if(o.indexOf("//")>=0)throw new X(Y.INVALID_ARGUMENT,"Invalid segment (".concat(o,"). Paths must not contain // in them."));e.push.apply(e,I(o.split("/").filter(function(e){return e.length>0})))}return new n(e)}},{key:"emptyPath",value:function(){return new n([])}}]),n}(),pe=/^[_a-zA-Z][_a-zA-Z0-9]*$/,me=function(e){p(n,ve);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n,[{key:"construct",value:function(e,t,r){return new n(e,t,r)}},{key:"canonicalString",value:function(){return this.toArray().map(function(e){return e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),n.isValidIdentifier(e)||(e="`"+e+"`"),e}).join(".")}},{key:"toString",value:function(){return this.canonicalString()}},{key:"isKeyField",value:function(){return 1===this.length&&"__name__"===this.get(0)}}],[{key:"isValidIdentifier",value:function(e){return pe.test(e)}},{key:"keyField",value:function(){return new n(["__name__"])}},{key:"fromServerFormat",value:function(e){for(var t=[],r="",i=0,a=function(){if(0===r.length)throw new X(Y.INVALID_ARGUMENT,"Invalid field path (".concat(e,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"));t.push(r),r=""},u=!1;i<e.length;){var o=e[i];if("\\"===o){if(i+1===e.length)throw new X(Y.INVALID_ARGUMENT,"Path has trailing escape character: "+e);var s=e[i+1];if("\\"!==s&&"."!==s&&"`"!==s)throw new X(Y.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=s,i+=2}else"`"===o?(u=!u,i++):"."!==o||u?(r+=o,i++):(a(),i++)}if(a(),u)throw new X(Y.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new n(t)}},{key:"emptyPath",value:function(){return new n([])}}]),n}();exports._FieldPath=me;var ge=function(){function e(t){C(this,e),this.path=t}return P(e,[{key:"collectionGroup",get:function(){return this.path.popLast().lastSegment()}},{key:"hasCollectionId",value:function(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}},{key:"getCollectionGroup",value:function(){return this.path.get(this.path.length-2)}},{key:"getCollectionPath",value:function(){return this.path.popLast()}},{key:"isEqual",value:function(e){return null!==e&&0===ye.comparator(this.path,e.path)}},{key:"toString",value:function(){return this.path.toString()}}],[{key:"fromPath",value:function(t){return new e(ye.fromString(t))}},{key:"fromName",value:function(t){return new e(ye.fromString(t).popFirst(5))}},{key:"empty",value:function(){return new e(ye.emptyPath())}},{key:"comparator",value:function(e,t){return ye.comparator(e.path,t.path)}},{key:"isDocumentKey",value:function(e){return e.length%2==0}},{key:"fromSegments",value:function(t){return new e(new ye(t.slice()))}}]),e}();exports._DocumentKey=ge;var ke=P(function e(t,n,r,i){C(this,e),this.indexId=t,this.collectionGroup=n,this.fields=r,this.indexState=i});function we(e){return e.fields.find(function(e){return 2===e.kind})}function xe(e){return e.fields.filter(function(e){return 2!==e.kind})}function be(e,t){var n=ce(e.collectionGroup,t.collectionGroup);if(0!==n)return n;for(var r=0;r<Math.min(e.fields.length,t.fields.length);++r)if(0!==(n=Ee(e.fields[r],t.fields[r])))return n;return ce(e.fields.length,t.fields.length)}ke.UNKNOWN_ID=-1;var Ie=P(function e(t,n){C(this,e),this.fieldPath=t,this.kind=n});function Ee(e,t){var n=me.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:ce(e.kind,t.kind)}var Te=function(){function e(t,n){C(this,e),this.sequenceNumber=t,this.offset=n}return P(e,null,[{key:"empty",value:function(){return new e(0,De.min())}}]),e}();function Se(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=de.fromTimestamp(1e9===r?new he(n+1,0):new he(n,r));return new De(i,ge.empty(),t)}function _e(e){return new De(e.readTime,e.key,-1)}var De=function(){function e(t,n,r){C(this,e),this.readTime=t,this.documentKey=n,this.largestBatchId=r}return P(e,null,[{key:"min",value:function(){return new e(de.min(),ge.empty(),-1)}},{key:"max",value:function(){return new e(de.max(),ge.empty(),-1)}}]),e}();function Ae(e,t){var n=e.readTime.compareTo(t.readTime);return 0!==n?n:0!==(n=ge.comparator(e.documentKey,t.documentKey))?n:ce(e.largestBatchId,t.largestBatchId)}var Ce="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",Ne=function(){function e(){C(this,e),this.onCommittedListeners=[]}return P(e,[{key:"addOnCommittedListener",value:function(e){this.onCommittedListeners.push(e)}},{key:"raiseOnCommittedEvent",value:function(){this.onCommittedListeners.forEach(function(e){return e()})}}]),e}();function Pe(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(e.code===Y.FAILED_PRECONDITION&&e.message===Ce){t.next=2;break}throw e;case 2:B("LocalStore","Unexpectedly lost primary lease");case 3:case"end":return t.stop()}},null,null,null,Promise)}var Le=function(){function e(t){var n=this;C(this,e),this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t(function(e){n.isDone=!0,n.result=e,n.nextCallback&&n.nextCallback(e)},function(e){n.isDone=!0,n.error=e,n.catchCallback&&n.catchCallback(e)})}return P(e,[{key:"catch",value:function(e){return this.next(void 0,e)}},{key:"next",value:function(t,n){var r=this;return this.callbackAttached&&j(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(t,this.result):new e(function(e,i){r.nextCallback=function(n){r.wrapSuccess(t,n).next(e,i)},r.catchCallback=function(t){r.wrapFailure(n,t).next(e,i)}})}},{key:"toPromise",value:function(){var e=this;return new Promise(function(t,n){e.next(t,n)})}},{key:"wrapUserFunction",value:function(t){try{var n=t();return n instanceof e?n:e.resolve(n)}catch(t){return e.reject(t)}}},{key:"wrapSuccess",value:function(t,n){return t?this.wrapUserFunction(function(){return t(n)}):e.resolve(n)}},{key:"wrapFailure",value:function(t,n){return t?this.wrapUserFunction(function(){return t(n)}):e.reject(n)}}],[{key:"resolve",value:function(t){return new e(function(e,n){e(t)})}},{key:"reject",value:function(t){return new e(function(e,n){n(t)})}},{key:"waitFor",value:function(t){return new e(function(e,n){var r=0,i=0,a=!1;t.forEach(function(t){++r,t.next(function(){++i,a&&i===r&&e()},function(e){return n(e)})}),a=!0,i===r&&e()})}},{key:"or",value:function(t){var n,r=e.resolve(!1),i=v(t);try{var a=function(){var t=n.value;r=r.next(function(n){return n?e.resolve(n):t()})};for(i.s();!(n=i.n()).done;)a()}catch(u){i.e(u)}finally{i.f()}return r}},{key:"forEach",value:function(e,t){var n=this,r=[];return e.forEach(function(e,i){r.push(t.call(n,e,i))}),this.waitFor(r)}},{key:"mapArray",value:function(t,n){return new e(function(e,r){for(var i=t.length,a=new Array(i),u=0,o=function(){var o=s;n(t[o]).next(function(t){a[o]=t,++u===i&&e(a)},function(e){return r(e)})},s=0;s<i;s++)o()})}},{key:"doWhile",value:function(t,n){return new e(function(e,r){!function i(){!0===t()?n().next(function(){i()},r):e()}()})}}]),e}(),Fe=function(){function e(t,n){var r=this;C(this,e),this.action=t,this.transaction=n,this.aborted=!1,this.P=new Z,this.transaction.oncomplete=function(){r.P.resolve()},this.transaction.onabort=function(){n.error?r.P.reject(new Ve(t,n.error)):r.P.resolve()},this.transaction.onerror=function(e){var n=Ge(e.target.error);r.P.reject(new Ve(t,n))}}return P(e,[{key:"v",get:function(){return this.P.promise}},{key:"abort",value:function(e){e&&this.P.reject(e),this.aborted||(B("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}},{key:"V",value:function(){var e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}},{key:"store",value:function(e){var t=this.transaction.objectStore(e);return new qe(t)}}],[{key:"open",value:function(t,n,r,i){try{return new e(n,t.transaction(i,r))}catch(t){throw new Ve(n,t)}}}]),e}(),Me=function(){function e(t,n,r){C(this,e),this.name=t,this.version=n,this.S=r,12.2===e.D((0,a.getUA)())&&G("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}return P(e,[{key:"F",value:function(e){var t=this;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=this.db,n.t0){n.next=6;break}return B("SimpleDb","Opening database:",this.name),n.next=5,y().awrap(new Promise(function(n,r){var i=indexedDB.open(t.name,t.version);i.onsuccess=function(e){var t=e.target.result;n(t)},i.onblocked=function(){r(new Ve(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=function(t){var n=t.target.error;"VersionError"===n.name?r(new X(Y.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===n.name?r(new X(Y.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+n)):r(new Ve(e,n))},i.onupgradeneeded=function(e){B("SimpleDb",'Database "'+t.name+'" requires upgrade from version:',e.oldVersion);var n=e.target.result;t.S.$(n,i.transaction,e.oldVersion,t.version).next(function(){B("SimpleDb","Database upgrade to version "+t.version+" complete")})}}));case 5:this.db=n.sent;case 6:return this.B&&(this.db.onversionchange=function(e){return t.B(e)}),n.abrupt("return",this.db);case 8:case"end":return n.stop()}},null,this,null,Promise)}},{key:"L",value:function(e){this.B=e,this.db&&(this.db.onversionchange=function(t){return e(t)})}},{key:"runTransaction",value:function(e,t,n,r){var i,a,u,o,s=this;return y().async(function(c){for(;;)switch(c.prev=c.next){case 0:i="readonly"===t,a=0,u=function(){var t,u,o,c;return y().async(function(l){for(;;)switch(l.prev=l.next){case 0:return++a,l.prev=1,l.next=4,y().awrap(s.F(e));case 4:return s.db=l.sent,t=Fe.open(s.db,e,i?"readonly":"readwrite",n),(u=r(t).next(function(e){return t.V(),e}).catch(function(e){return t.abort(e),Le.reject(e)}).toPromise()).catch(function(){}),l.next=9,y().awrap(t.v);case 9:return l.t0=u,l.abrupt("return",{v:l.t0});case 13:if(l.prev=13,l.t1=l.catch(1),o=l.t1,c="FirebaseError"!==o.name&&a<3,B("SimpleDb","Transaction failed with error:",o.message,"Retrying:",c),s.close(),c){l.next=18;break}return l.abrupt("return",{v:Promise.reject(o)});case 18:case"end":return l.stop()}},null,null,[[1,13]],Promise)};case 3:return c.next=5,y().awrap(u());case 5:if("object"!==A(o=c.sent)){c.next=8;break}return c.abrupt("return",o.v);case 8:c.next=3;break;case 10:case"end":return c.stop()}},null,null,null,Promise)}},{key:"close",value:function(){this.db&&this.db.close(),this.db=void 0}}],[{key:"delete",value:function(e){return B("SimpleDb","Removing database:",e),Ue(window.indexedDB.deleteDatabase(e)).toPromise()}},{key:"C",value:function(){if(!(0,a.isIndexedDBAvailable)())return!1;if(e.N())return!0;var t=(0,a.getUA)(),n=e.D(t),r=0<n&&n<10,i=e.k(t),u=0<i&&i<4.5;return!(t.indexOf("MSIE ")>0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0||r||u)}},{key:"N",value:function(){var e;return void 0!==t&&"YES"===(null===(e=t.env)||void 0===e?void 0:e.O)}},{key:"M",value:function(e,t){return e.store(t)}},{key:"D",value:function(e){var t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}},{key:"k",value:function(e){var t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}}]),e}(),Re=function(){function e(t){C(this,e),this.q=t,this.U=!1,this.K=null}return P(e,[{key:"isDone",get:function(){return this.U}},{key:"G",get:function(){return this.K}},{key:"cursor",set:function(e){this.q=e}},{key:"done",value:function(){this.U=!0}},{key:"j",value:function(e){this.K=e}},{key:"delete",value:function(){return Ue(this.q.delete())}}]),e}(),Ve=function(e){p(n,X);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,Y.UNAVAILABLE,"IndexedDB transaction '".concat(e,"' failed: ").concat(r))).name="IndexedDbTransactionError",i}return P(n)}();function Oe(e){return"IndexedDbTransactionError"===e.name}var qe=function(){function e(t){C(this,e),this.store=t}return P(e,[{key:"put",value:function(e,t){var n;return void 0!==t?(B("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(B("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),Ue(n)}},{key:"add",value:function(e){return B("SimpleDb","ADD",this.store.name,e,e),Ue(this.store.add(e))}},{key:"get",value:function(e){var t=this;return Ue(this.store.get(e)).next(function(n){return void 0===n&&(n=null),B("SimpleDb","GET",t.store.name,e,n),n})}},{key:"delete",value:function(e){return B("SimpleDb","DELETE",this.store.name,e),Ue(this.store.delete(e))}},{key:"count",value:function(){return B("SimpleDb","COUNT",this.store.name),Ue(this.store.count())}},{key:"W",value:function(e,t){var n=this.options(e,t);if(n.index||"function"!=typeof this.store.getAll){var r=this.cursor(n),i=[];return this.H(r,function(e,t){i.push(t)}).next(function(){return i})}var a=this.store.getAll(n.range);return new Le(function(e,t){a.onerror=function(e){t(e.target.error)},a.onsuccess=function(t){e(t.target.result)}})}},{key:"J",value:function(e,t){var n=this.store.getAll(e,null===t?void 0:t);return new Le(function(e,t){n.onerror=function(e){t(e.target.error)},n.onsuccess=function(t){e(t.target.result)}})}},{key:"Y",value:function(e,t){B("SimpleDb","DELETE ALL",this.store.name);var n=this.options(e,t);n.X=!1;var r=this.cursor(n);return this.H(r,function(e,t,n){return n.delete()})}},{key:"Z",value:function(e,t){var n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.H(r,t)}},{key:"tt",value:function(e){var t=this.cursor({});return new Le(function(n,r){t.onerror=function(e){var t=Ge(e.target.error);r(t)},t.onsuccess=function(t){var r=t.target.result;r?e(r.primaryKey,r.value).next(function(e){e?r.continue():n()}):n()}})}},{key:"H",value:function(e,t){var n=[];return new Le(function(r,i){e.onerror=function(e){i(e.target.error)},e.onsuccess=function(e){var i=e.target.result;if(i){var a=new Re(i),u=t(i.primaryKey,i.value,a);if(u instanceof Le){var o=u.catch(function(e){return a.done(),Le.reject(e)});n.push(o)}a.isDone?r():null===a.G?i.continue():i.continue(a.G)}else r()}}).next(function(){return Le.waitFor(n)})}},{key:"options",value:function(e,t){var n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}},{key:"cursor",value:function(e){var t="next";if(e.reverse&&(t="prev"),e.index){var n=this.store.index(e.index);return e.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}]),e}();function Ue(e){return new Le(function(t,n){e.onsuccess=function(e){var n=e.target.result;t(n)},e.onerror=function(e){var t=Ge(e.target.error);n(t)}})}var Be=!1;function Ge(e){var t=Me.D((0,a.getUA)());if(t>=12.2&&t<13){var n="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(n)>=0){var r=new X("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '".concat(n,"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."));return Be||(Be=!0,setTimeout(function(){throw r},0)),r}}return e}var Ke=function(){function e(t,n){C(this,e),this.asyncQueue=t,this.et=n,this.task=null}return P(e,[{key:"start",value:function(){this.nt(15e3)}},{key:"stop",value:function(){this.task&&(this.task.cancel(),this.task=null)}},{key:"started",get:function(){return null!==this.task}},{key:"nt",value:function(e){var t=this;B("IndexBackiller","Scheduled in ".concat(e,"ms")),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return t.task=null,e.prev=1,e.t0=B,e.t1="Documents written: ",e.next=6,y().awrap(t.et.st());case 6:e.t2=e.sent,e.t3=e.t1.concat.call(e.t1,e.t2),(0,e.t0)("IndexBackiller",e.t3),e.next=19;break;case 11:if(e.prev=11,e.t4=e.catch(1),!Oe(e.t4)){e.next=17;break}B("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e.t4),e.next=19;break;case 17:return e.next=19,y().awrap(Pe(e.t4));case 19:return e.next=21,y().awrap(t.nt(6e4));case 21:case"end":return e.stop()}},null,null,[[1,11]],Promise)})}}]),e}(),Qe=function(){function e(t,n){C(this,e),this.localStore=t,this.persistence=n}return P(e,[{key:"st",value:function(){var e,t=this,n=arguments;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return e=n.length>0&&void 0!==n[0]?n[0]:50,r.abrupt("return",this.persistence.runTransaction("Backfill Indexes","readwrite-primary",function(n){return t.it(n,e)}));case 2:case"end":return r.stop()}},null,this,null,Promise)}},{key:"it",value:function(e,t){var n=this,r=new Set,i=t,a=!0;return Le.doWhile(function(){return!0===a&&i>0},function(){return n.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(function(t){if(null!==t&&!r.has(t))return B("IndexBackiller","Processing collection: ".concat(t)),n.rt(e,t,i).next(function(e){i-=e,r.add(t)});a=!1})}).next(function(){return t-i})}},{key:"rt",value:function(e,t,n){var r=this;return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(function(i){return r.localStore.localDocuments.getNextDocuments(e,t,i,n).next(function(n){var a=n.changes;return r.localStore.indexManager.updateIndexEntries(e,a).next(function(){return r.ot(i,n)}).next(function(n){return B("IndexBackiller","Updating offset: ".concat(n)),r.localStore.indexManager.updateCollectionGroup(e,t,n)}).next(function(){return a.size})})})}},{key:"ot",value:function(e,t){var n=e;return t.changes.forEach(function(e,t){var r=_e(t);Ae(r,n)>0&&(n=r)}),new De(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}]),e}(),je=function(){function e(t,n){var r=this;C(this,e),this.previousValue=t,n&&(n.sequenceNumberHandler=function(e){return r.ut(e)},this.ct=function(e){return n.writeSequenceNumber(e)})}return P(e,[{key:"ut",value:function(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}},{key:"next",value:function(){var e=++this.previousValue;return this.ct&&this.ct(e),e}}]),e}();je.at=-1;var ze=P(function e(t,n,r,i,a,u,o,s){C(this,e),this.databaseId=t,this.appId=n,this.persistenceKey=r,this.host=i,this.ssl=a,this.forceLongPolling=u,this.autoDetectLongPolling=o,this.useFetchStreams=s}),We=function(){function e(t,n){C(this,e),this.projectId=t,this.database=n||"(default)"}return P(e,[{key:"isDefaultDatabase",get:function(){return"(default)"===this.database}},{key:"isEqual",value:function(t){return t instanceof e&&t.projectId===this.projectId&&t.database===this.database}}],[{key:"empty",value:function(){return new e("","")}}]),e}();function He(e){var t=0;for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Ye(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Xe(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Ze(e){return null==e}function Je(e){return 0===e&&1/e==-1/0}function $e(e){return"number"==typeof e&&Number.isInteger(e)&&!Je(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function et(){return"undefined"!=typeof atob}exports._DatabaseId=We;var tt=function(e){function t(e){C(this,t),this.binaryString=e}return P(t,[{key:Symbol.iterator,value:function(){var e=this,t=0;return{next:function(){return t<e.binaryString.length?{value:e.binaryString.charCodeAt(t++),done:!1}:{value:void 0,done:!0}}}}},{key:"toBase64",value:function(){return e=this.binaryString,btoa(e);var e}},{key:"toUint8Array",value:function(){return function(e){for(var t=new Uint8Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}},{key:"approximateByteSize",value:function(){return 2*this.binaryString.length}},{key:"compareTo",value:function(e){return ce(this.binaryString,e.binaryString)}},{key:"isEqual",value:function(e){return this.binaryString===e.binaryString}}],[{key:"fromBase64String",value:function(e){return new t(atob(e))}},{key:"fromUint8Array",value:function(e){return new t(function(e){for(var t="",n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e))}}]),t}();tt.EMPTY_BYTE_STRING=new tt("");var nt=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function rt(e){if(z(!!e),"string"==typeof e){var t=0,n=nt.exec(e);if(z(!!n),n[1]){var r=n[1];r=(r+"000000000").substr(0,9),t=Number(r)}var i=new Date(e);return{seconds:Math.floor(i.getTime()/1e3),nanos:t}}return{seconds:it(e.seconds),nanos:it(e.nanos)}}function it(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function at(e){return"string"==typeof e?tt.fromBase64String(e):tt.fromUint8Array(e)}function ut(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function ot(e){var t=e.mapValue.fields.__previous_value__;return ut(t)?ot(t):t}function st(e){var t=rt(e.mapValue.fields.__local_write_time__.timestampValue);return new he(t.seconds,t.nanos)}var ct={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},lt={nullValue:"NULL_VALUE"};function ft(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?ut(e)?4:Tt(e)?9007199254740991:10:j()}function ht(e,t){if(e===t)return!0;var n=ft(e);if(n!==ft(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return st(e).isEqual(st(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;var n=rt(e.timestampValue),r=rt(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 at(e.bytesValue).isEqual(at(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return it(e.geoPointValue.latitude)===it(t.geoPointValue.latitude)&&it(e.geoPointValue.longitude)===it(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return it(e.integerValue)===it(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=it(e.doubleValue),r=it(t.doubleValue);return n===r?Je(n)===Je(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return le(e.arrayValue.values||[],t.arrayValue.values||[],ht);case 10:return function(e,t){var n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(He(n)!==He(r))return!1;for(var i in n)if(n.hasOwnProperty(i)&&(void 0===r[i]||!ht(n[i],r[i])))return!1;return!0}(e,t);default:return j()}}function dt(e,t){return void 0!==(e.values||[]).find(function(e){return ht(e,t)})}function vt(e,t){if(e===t)return 0;var n=ft(e),r=ft(t);if(n!==r)return ce(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return ce(e.booleanValue,t.booleanValue);case 2:return function(e,t){var n=it(e.integerValue||e.doubleValue),r=it(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return yt(e.timestampValue,t.timestampValue);case 4:return yt(st(e),st(t));case 5:return ce(e.stringValue,t.stringValue);case 6:return function(e,t){var n=at(e),r=at(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){for(var n=e.split("/"),r=t.split("/"),i=0;i<n.length&&i<r.length;i++){var a=ce(n[i],r[i]);if(0!==a)return a}return ce(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){var n=ce(it(e.latitude),it(t.latitude));return 0!==n?n:ce(it(e.longitude),it(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){for(var n=e.values||[],r=t.values||[],i=0;i<n.length&&i<r.length;++i){var a=vt(n[i],r[i]);if(a)return a}return ce(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===ct.mapValue&&t===ct.mapValue)return 0;if(e===ct.mapValue)return 1;if(t===ct.mapValue)return-1;var n=e.fields||{},r=Object.keys(n),i=t.fields||{},a=Object.keys(i);r.sort(),a.sort();for(var u=0;u<r.length&&u<a.length;++u){var o=ce(r[u],a[u]);if(0!==o)return o;var s=vt(n[r[u]],i[a[u]]);if(0!==s)return s}return ce(r.length,a.length)}(e.mapValue,t.mapValue);default:throw j()}}function yt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return ce(e,t);var n=rt(e),r=rt(t),i=ce(n.seconds,r.seconds);return 0!==i?i:ce(n.nanos,r.nanos)}function pt(e){return mt(e)}function mt(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){var t=rt(e);return"time(".concat(t.seconds,",").concat(t.nanos,")")}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?at(e.bytesValue).toBase64():"referenceValue"in e?(n=e.referenceValue,ge.fromName(n).toString()):"geoPointValue"in e?"geo(".concat((t=e.geoPointValue).latitude,",").concat(t.longitude,")"):"arrayValue"in e?function(e){var t,n="[",r=!0,i=v(e.values||[]);try{for(i.s();!(t=i.n()).done;){var a=t.value;r?r=!1:n+=",",n+=mt(a)}}catch(u){i.e(u)}finally{i.f()}return n+"]"}(e.arrayValue):"mapValue"in e?function(e){var t,n="{",r=!0,i=v(Object.keys(e.fields||{}).sort());try{for(i.s();!(t=i.n()).done;){var a=t.value;r?r=!1:n+=",",n+="".concat(a,":").concat(mt(e.fields[a]))}}catch(u){i.e(u)}finally{i.f()}return n+"}"}(e.mapValue):j();var t,n}function gt(e,t){return{referenceValue:"projects/".concat(e.projectId,"/databases/").concat(e.database,"/documents/").concat(t.path.canonicalString())}}function kt(e){return!!e&&"integerValue"in e}function wt(e){return!!e&&"arrayValue"in e}function xt(e){return!!e&&"nullValue"in e}function bt(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function It(e){return!!e&&"mapValue"in e}function Et(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==A(e.timestampValue))return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){var t={mapValue:{fields:{}}};return Ye(e.mapValue.fields,function(e,n){return t.mapValue.fields[e]=Et(n)}),t}if(e.arrayValue){for(var n={arrayValue:{values:[]}},r=0;r<(e.arrayValue.values||[]).length;++r)n.arrayValue.values[r]=Et(e.arrayValue.values[r]);return n}return Object.assign({},e)}function Tt(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function St(e){return"nullValue"in e?lt:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?gt(We.empty(),ge.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?{mapValue:{}}:j()}function _t(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?gt(We.empty(),ge.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?{mapValue:{}}:"mapValue"in e?ct:j()}function Dt(e,t){var n=vt(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function At(e,t){var n=vt(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}var Ct=P(function e(t,n){C(this,e),this.position=t,this.inclusive=n});function Nt(e,t,n){for(var r=0,i=0;i<e.position.length;i++){var a=t[i],u=e.position[i];if(r=a.field.isKeyField()?ge.comparator(ge.fromName(u.referenceValue),n.key):vt(u,n.data.field(a.field)),"desc"===a.dir&&(r*=-1),0!==r)break}return r}function Pt(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(var n=0;n<e.position.length;n++)if(!ht(e.position[n],t.position[n]))return!1;return!0}var Lt=P(function e(){C(this,e)}),Ft=function(e){p(n,Lt);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this)).field=e,a.op=r,a.value=i,a}return P(n,[{key:"matches",value:function(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(vt(t,this.value)):null!==t&&ft(this.value)===ft(t)&&this.matchesComparison(vt(t,this.value))}},{key:"matchesComparison",value:function(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return j()}}},{key:"isInequality",value:function(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}},{key:"getFlattenedFilters",value:function(){return[this]}},{key:"getFilters",value:function(){return[this]}},{key:"getFirstInequalityField",value:function(){return this.isInequality()?this.field:null}}],[{key:"create",value:function(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new Qt(e,t,r):"array-contains"===t?new Ht(e,r):"in"===t?new Yt(e,r):"not-in"===t?new Xt(e,r):"array-contains-any"===t?new Zt(e,r):new n(e,t,r)}},{key:"createKeyFieldInFilter",value:function(e,t,n){return"in"===t?new jt(e,n):new zt(e,n)}}]),n}(),Mt=function(e){p(n,Lt);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).filters=e,i.op=r,i.ht=null,i}return P(n,[{key:"matches",value:function(e){return Rt(this)?void 0===this.filters.find(function(t){return!t.matches(e)}):void 0!==this.filters.find(function(t){return t.matches(e)})}},{key:"getFlattenedFilters",value:function(){return null!==this.ht||(this.ht=this.filters.reduce(function(e,t){return e.concat(t.getFlattenedFilters())},[])),this.ht}},{key:"getFilters",value:function(){return Object.assign([],this.filters)}},{key:"getFirstInequalityField",value:function(){var e=this.lt(function(e){return e.isInequality()});return null!==e?e.field:null}},{key:"lt",value:function(e){var t,n=v(this.getFlattenedFilters());try{for(n.s();!(t=n.n()).done;){var r=t.value;if(e(r))return r}}catch(i){n.e(i)}finally{n.f()}return null}}],[{key:"create",value:function(e,t){return new n(e,t)}}]),n}();function Rt(e){return"and"===e.op}function Vt(e){return"or"===e.op}function Ot(e){return qt(e)&&Rt(e)}function qt(e){var t,n=v(e.filters);try{for(n.s();!(t=n.n()).done;){if(t.value instanceof Mt)return!1}}catch(r){n.e(r)}finally{n.f()}return!0}function Ut(e){if(e instanceof Ft)return e.field.canonicalString()+e.op.toString()+pt(e.value);if(Ot(e))return e.filters.map(function(e){return Ut(e)}).join(",");var t=e.filters.map(function(e){return Ut(e)}).join(",");return"".concat(e.op,"(").concat(t,")")}function Bt(e,t){return e instanceof Ft?function(e,t){return t instanceof Ft&&e.op===t.op&&e.field.isEqual(t.field)&&ht(e.value,t.value)}(e,t):e instanceof Mt?function(e,t){return t instanceof Mt&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(function(e,n,r){return e&&Bt(n,t.filters[r])},!0)}(e,t):void j()}function Gt(e,t){var n=e.filters.concat(t);return Mt.create(n,e.op)}function Kt(e){return e instanceof Ft?function(e){return"".concat(e.field.canonicalString()," ").concat(e.op," ").concat(pt(e.value))}(e):e instanceof Mt?function(e){return e.op.toString()+" {"+e.getFilters().map(Kt).join(" ,")+"}"}(e):"Filter"}var Qt=function(e){p(n,Ft);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this,e,r,i)).key=ge.fromName(i.referenceValue),a}return P(n,[{key:"matches",value:function(e){var t=ge.comparator(e.key,this.key);return this.matchesComparison(t)}}]),n}(),jt=function(e){p(n,Ft);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e,"in",r)).keys=Wt("in",r),i}return P(n,[{key:"matches",value:function(e){return this.keys.some(function(t){return t.isEqual(e.key)})}}]),n}(),zt=function(e){p(n,Ft);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e,"not-in",r)).keys=Wt("not-in",r),i}return P(n,[{key:"matches",value:function(e){return!this.keys.some(function(t){return t.isEqual(e.key)})}}]),n}();function Wt(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(function(e){return ge.fromName(e.referenceValue)})}var Ht=function(e){p(n,Ft);var t=g(n);function n(e,r){return C(this,n),t.call(this,e,"array-contains",r)}return P(n,[{key:"matches",value:function(e){var t=e.data.field(this.field);return wt(t)&&dt(t.arrayValue,this.value)}}]),n}(),Yt=function(e){p(n,Ft);var t=g(n);function n(e,r){return C(this,n),t.call(this,e,"in",r)}return P(n,[{key:"matches",value:function(e){var t=e.data.field(this.field);return null!==t&&dt(this.value.arrayValue,t)}}]),n}(),Xt=function(e){p(n,Ft);var t=g(n);function n(e,r){return C(this,n),t.call(this,e,"not-in",r)}return P(n,[{key:"matches",value:function(e){if(dt(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!dt(this.value.arrayValue,t)}}]),n}(),Zt=function(e){p(n,Ft);var t=g(n);function n(e,r){return C(this,n),t.call(this,e,"array-contains-any",r)}return P(n,[{key:"matches",value:function(e){var t=this,n=e.data.field(this.field);return!(!wt(n)||!n.arrayValue.values)&&n.arrayValue.values.some(function(e){return dt(t.value.arrayValue,e)})}}]),n}(),Jt=P(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"asc";C(this,e),this.field=t,this.dir=n});function $t(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}var en=function(){function e(t,n){C(this,e),this.comparator=t,this.root=n||nn.EMPTY}return P(e,[{key:"insert",value:function(t,n){return new e(this.comparator,this.root.insert(t,n,this.comparator).copy(null,null,nn.BLACK,null,null))}},{key:"remove",value:function(t){return new e(this.comparator,this.root.remove(t,this.comparator).copy(null,null,nn.BLACK,null,null))}},{key:"get",value:function(e){for(var t=this.root;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}},{key:"indexOf",value:function(e){for(var t=0,n=this.root;!n.isEmpty();){var 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}},{key:"isEmpty",value:function(){return this.root.isEmpty()}},{key:"size",get:function(){return this.root.size}},{key:"minKey",value:function(){return this.root.minKey()}},{key:"maxKey",value:function(){return this.root.maxKey()}},{key:"inorderTraversal",value:function(e){return this.root.inorderTraversal(e)}},{key:"forEach",value:function(e){this.inorderTraversal(function(t,n){return e(t,n),!1})}},{key:"toString",value:function(){var e=[];return this.inorderTraversal(function(t,n){return e.push("".concat(t,":").concat(n)),!1}),"{".concat(e.join(", "),"}")}},{key:"reverseTraversal",value:function(e){return this.root.reverseTraversal(e)}},{key:"getIterator",value:function(){return new tn(this.root,null,this.comparator,!1)}},{key:"getIteratorFrom",value:function(e){return new tn(this.root,e,this.comparator,!1)}},{key:"getReverseIterator",value:function(){return new tn(this.root,null,this.comparator,!0)}},{key:"getReverseIteratorFrom",value:function(e){return new tn(this.root,e,this.comparator,!0)}}]),e}(),tn=function(){function e(t,n,r,i){C(this,e),this.isReverse=i,this.nodeStack=[];for(var a=1;!t.isEmpty();)if(a=n?r(t.key,n):1,n&&i&&(a*=-1),a<0)t=this.isReverse?t.left:t.right;else{if(0===a){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return P(e,[{key:"getNext",value:function(){var e=this.nodeStack.pop(),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}},{key:"hasNext",value:function(){return this.nodeStack.length>0}},{key:"peek",value:function(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}]),e}(),nn=function(){function e(t,n,r,i,a){C(this,e),this.key=t,this.value=n,this.color=null!=r?r:e.RED,this.left=null!=i?i:e.EMPTY,this.right=null!=a?a:e.EMPTY,this.size=this.left.size+1+this.right.size}return P(e,[{key:"copy",value:function(t,n,r,i,a){return new e(null!=t?t:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=a?a:this.right)}},{key:"isEmpty",value:function(){return!1}},{key:"inorderTraversal",value:function(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}},{key:"reverseTraversal",value:function(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}},{key:"min",value:function(){return this.left.isEmpty()?this:this.left.min()}},{key:"minKey",value:function(){return this.min().key}},{key:"maxKey",value:function(){return this.right.isEmpty()?this.key:this.right.maxKey()}},{key:"insert",value:function(e,t,n){var r=this,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))).fixUp()}},{key:"removeMin",value:function(){if(this.left.isEmpty())return e.EMPTY;var t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),(t=t.copy(null,null,null,t.left.removeMin(),null)).fixUp()}},{key:"remove",value:function(t,n){var r,i=this;if(n(t,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(t,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(t,i.key)){if(i.right.isEmpty())return e.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(t,n))}return i.fixUp()}},{key:"isRed",value:function(){return this.color}},{key:"fixUp",value:function(){var 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}},{key:"moveRedLeft",value:function(){var e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}},{key:"moveRedRight",value:function(){var e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}},{key:"rotateLeft",value:function(){var t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}},{key:"rotateRight",value:function(){var t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}},{key:"colorFlip",value:function(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}},{key:"checkMaxDepth",value:function(){var e=this.check();return Math.pow(2,e)<=this.size+1}},{key:"check",value:function(){if(this.isRed()&&this.left.isRed())throw j();if(this.right.isRed())throw j();var e=this.left.check();if(e!==this.right.check())throw j();return e+(this.isRed()?0:1)}}]),e}();nn.EMPTY=null,nn.RED=!0,nn.BLACK=!1,nn.EMPTY=new(function(){function e(){C(this,e),this.size=0}return P(e,[{key:"key",get:function(){throw j()}},{key:"value",get:function(){throw j()}},{key:"color",get:function(){throw j()}},{key:"left",get:function(){throw j()}},{key:"right",get:function(){throw j()}},{key:"copy",value:function(e,t,n,r,i){return this}},{key:"insert",value:function(e,t,n){return new nn(e,t)}},{key:"remove",value:function(e,t){return this}},{key:"isEmpty",value:function(){return!0}},{key:"inorderTraversal",value:function(e){return!1}},{key:"reverseTraversal",value:function(e){return!1}},{key:"minKey",value:function(){return null}},{key:"maxKey",value:function(){return null}},{key:"isRed",value:function(){return!1}},{key:"checkMaxDepth",value:function(){return!0}},{key:"check",value:function(){return 0}}]),e}());var rn=function(){function e(t){C(this,e),this.comparator=t,this.data=new en(this.comparator)}return P(e,[{key:"has",value:function(e){return null!==this.data.get(e)}},{key:"first",value:function(){return this.data.minKey()}},{key:"last",value:function(){return this.data.maxKey()}},{key:"size",get:function(){return this.data.size}},{key:"indexOf",value:function(e){return this.data.indexOf(e)}},{key:"forEach",value:function(e){this.data.inorderTraversal(function(t,n){return e(t),!1})}},{key:"forEachInRange",value:function(e,t){for(var n=this.data.getIteratorFrom(e[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}},{key:"forEachWhile",value:function(e,t){var n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}},{key:"firstAfterOrEqual",value:function(e){var t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}},{key:"getIterator",value:function(){return new an(this.data.getIterator())}},{key:"getIteratorFrom",value:function(e){return new an(this.data.getIteratorFrom(e))}},{key:"add",value:function(e){return this.copy(this.data.remove(e).insert(e,!0))}},{key:"delete",value:function(e){return this.has(e)?this.copy(this.data.remove(e)):this}},{key:"isEmpty",value:function(){return this.data.isEmpty()}},{key:"unionWith",value:function(e){var t=this;return t.size<e.size&&(t=e,e=this),e.forEach(function(e){t=t.add(e)}),t}},{key:"isEqual",value:function(t){if(!(t instanceof e))return!1;if(this.size!==t.size)return!1;for(var n=this.data.getIterator(),r=t.data.getIterator();n.hasNext();){var i=n.getNext().key,a=r.getNext().key;if(0!==this.comparator(i,a))return!1}return!0}},{key:"toArray",value:function(){var e=[];return this.forEach(function(t){e.push(t)}),e}},{key:"toString",value:function(){var e=[];return this.forEach(function(t){return e.push(t)}),"SortedSet("+e.toString()+")"}},{key:"copy",value:function(t){var n=new e(this.comparator);return n.data=t,n}}]),e}(),an=function(){function e(t){C(this,e),this.iter=t}return P(e,[{key:"getNext",value:function(){return this.iter.getNext().key}},{key:"hasNext",value:function(){return this.iter.hasNext()}}]),e}();function un(e){return e.hasNext()?e.getNext():void 0}var on=function(){function e(t){C(this,e),this.fields=t,t.sort(me.comparator)}return P(e,[{key:"unionWith",value:function(t){var n,r=new rn(me.comparator),i=v(this.fields);try{for(i.s();!(n=i.n()).done;){var a=n.value;r=r.add(a)}}catch(c){i.e(c)}finally{i.f()}var u,o=v(t);try{for(o.s();!(u=o.n()).done;){var s=u.value;r=r.add(s)}}catch(c){o.e(c)}finally{o.f()}return new e(r.toArray())}},{key:"covers",value:function(e){var t,n=v(this.fields);try{for(n.s();!(t=n.n()).done;){if(t.value.isPrefixOf(e))return!0}}catch(r){n.e(r)}finally{n.f()}return!1}},{key:"isEqual",value:function(e){return le(this.fields,e.fields,function(e,t){return e.isEqual(t)})}}],[{key:"empty",value:function(){return new e([])}}]),e}(),sn=function(){function e(t){C(this,e),this.value=t}return P(e,[{key:"field",value:function(e){if(e.isEmpty())return this.value;for(var t=this.value,n=0;n<e.length-1;++n)if(!It(t=(t.mapValue.fields||{})[e.get(n)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}},{key:"set",value:function(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Et(t)}},{key:"setAll",value:function(e){var t=this,n=me.emptyPath(),r={},i=[];e.forEach(function(e,a){if(!n.isImmediateParentOf(a)){var u=t.getFieldsMap(n);t.applyChanges(u,r,i),r={},i=[],n=a.popLast()}e?r[a.lastSegment()]=Et(e):i.push(a.lastSegment())});var a=this.getFieldsMap(n);this.applyChanges(a,r,i)}},{key:"delete",value:function(e){var t=this.field(e.popLast());It(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}},{key:"isEqual",value:function(e){return ht(this.value,e.value)}},{key:"getFieldsMap",value:function(e){var t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(var n=0;n<e.length;++n){var r=t.mapValue.fields[e.get(n)];It(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}},{key:"applyChanges",value:function(e,t,n){Ye(t,function(t,n){return e[t]=n});var r,i=v(n);try{for(i.s();!(r=i.n()).done;){var a=r.value;delete e[a]}}catch(u){i.e(u)}finally{i.f()}}},{key:"clone",value:function(){return new e(Et(this.value))}}],[{key:"empty",value:function(){return new e({mapValue:{}})}}]),e}();function cn(e){var t=[];return Ye(e.fields,function(e,n){var r=new me([e]);if(It(n)){var i=cn(n.mapValue).fields;if(0===i.length)t.push(r);else{var a,u=v(i);try{for(u.s();!(a=u.n()).done;){var o=a.value;t.push(r.child(o))}}catch(s){u.e(s)}finally{u.f()}}}else t.push(r)}),new on(t)}var ln=function(){function e(t,n,r,i,a,u,o){C(this,e),this.key=t,this.documentType=n,this.version=r,this.readTime=i,this.createTime=a,this.data=u,this.documentState=o}return P(e,[{key:"convertToFoundDocument",value:function(e,t){return!this.createTime.isEqual(de.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}},{key:"convertToNoDocument",value:function(e){return this.version=e,this.documentType=2,this.data=sn.empty(),this.documentState=0,this}},{key:"convertToUnknownDocument",value:function(e){return this.version=e,this.documentType=3,this.data=sn.empty(),this.documentState=2,this}},{key:"setHasCommittedMutations",value:function(){return this.documentState=2,this}},{key:"setHasLocalMutations",value:function(){return this.documentState=1,this.version=de.min(),this}},{key:"setReadTime",value:function(e){return this.readTime=e,this}},{key:"hasLocalMutations",get:function(){return 1===this.documentState}},{key:"hasCommittedMutations",get:function(){return 2===this.documentState}},{key:"hasPendingWrites",get:function(){return this.hasLocalMutations||this.hasCommittedMutations}},{key:"isValidDocument",value:function(){return 0!==this.documentType}},{key:"isFoundDocument",value:function(){return 1===this.documentType}},{key:"isNoDocument",value:function(){return 2===this.documentType}},{key:"isUnknownDocument",value:function(){return 3===this.documentType}},{key:"isEqual",value:function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}},{key:"mutableCopy",value:function(){return new e(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}},{key:"toString",value:function(){return"Document(".concat(this.key,", ").concat(this.version,", ").concat(JSON.stringify(this.data.value),", {createTime: ").concat(this.createTime,"}), {documentType: ").concat(this.documentType,"}), {documentState: ").concat(this.documentState,"})")}}],[{key:"newInvalidDocument",value:function(t){return new e(t,0,de.min(),de.min(),de.min(),sn.empty(),0)}},{key:"newFoundDocument",value:function(t,n,r,i){return new e(t,1,n,de.min(),r,i,0)}},{key:"newNoDocument",value:function(t,n){return new e(t,2,n,de.min(),de.min(),sn.empty(),0)}},{key:"newUnknownDocument",value:function(t,n){return new e(t,3,n,de.min(),de.min(),sn.empty(),2)}}]),e}(),fn=P(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;C(this,e),this.path=t,this.collectionGroup=n,this.orderBy=r,this.filters=i,this.limit=a,this.startAt=u,this.endAt=o,this.ft=null});function hn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,u=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;return new fn(e,t,n,r,i,a,u)}function dn(e){var t=H(e);if(null===t.ft){var n=t.path.canonicalString();null!==t.collectionGroup&&(n+="|cg:"+t.collectionGroup),n+="|f:",n+=t.filters.map(function(e){return Ut(e)}).join(","),n+="|ob:",n+=t.orderBy.map(function(e){return function(e){return e.field.canonicalString()+e.dir}(e)}).join(","),Ze(t.limit)||(n+="|l:",n+=t.limit),t.startAt&&(n+="|lb:",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(function(e){return pt(e)}).join(",")),t.endAt&&(n+="|ub:",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(function(e){return pt(e)}).join(",")),t.ft=n}return t.ft}function vn(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(var n=0;n<e.orderBy.length;n++)if(!$t(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(var r=0;r<e.filters.length;r++)if(!Bt(e.filters[r],t.filters[r]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Pt(e.startAt,t.startAt)&&Pt(e.endAt,t.endAt)}function yn(e){return ge.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function pn(e,t){return e.filters.filter(function(e){return e instanceof Ft&&e.field.isEqual(t)})}function mn(e,t,n){var r,i=lt,a=!0,u=v(pn(e,t));try{for(u.s();!(r=u.n()).done;){var o=r.value,s=lt,c=!0;switch(o.op){case"<":case"<=":s=St(o.value);break;case"==":case"in":case">=":s=o.value;break;case">":s=o.value,c=!1;break;case"!=":case"not-in":s=lt}Dt({value:i,inclusive:a},{value:s,inclusive:c})<0&&(i=s,a=c)}}catch(h){u.e(h)}finally{u.f()}if(null!==n)for(var l=0;l<e.orderBy.length;++l)if(e.orderBy[l].field.isEqual(t)){var f=n.position[l];Dt({value:i,inclusive:a},{value:f,inclusive:n.inclusive})<0&&(i=f,a=n.inclusive);break}return{value:i,inclusive:a}}function gn(e,t,n){var r,i=ct,a=!0,u=v(pn(e,t));try{for(u.s();!(r=u.n()).done;){var o=r.value,s=ct,c=!0;switch(o.op){case">=":case">":s=_t(o.value),c=!1;break;case"==":case"in":case"<=":s=o.value;break;case"<":s=o.value,c=!1;break;case"!=":case"not-in":s=ct}At({value:i,inclusive:a},{value:s,inclusive:c})>0&&(i=s,a=c)}}catch(h){u.e(h)}finally{u.f()}if(null!==n)for(var l=0;l<e.orderBy.length;++l)if(e.orderBy[l].field.isEqual(t)){var f=n.position[l];At({value:i,inclusive:a},{value:f,inclusive:n.inclusive})>0&&(i=f,a=n.inclusive);break}return{value:i,inclusive:a}}var kn=P(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"F",o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,s=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;C(this,e),this.path=t,this.collectionGroup=n,this.explicitOrderBy=r,this.filters=i,this.limit=a,this.limitType=u,this.startAt=o,this.endAt=s,this.dt=null,this._t=null,this.startAt,this.endAt});function wn(e,t,n,r,i,a,u,o){return new kn(e,t,n,r,i,a,u,o)}function xn(e){return new kn(e)}function bn(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function In(e){return e.explicitOrderBy.length>0?e.explicitOrderBy[0].field:null}function En(e){var t,n=v(e.filters);try{for(n.s();!(t=n.n()).done;){var r=t.value.getFirstInequalityField();if(null!==r)return r}}catch(i){n.e(i)}finally{n.f()}return null}function Tn(e){return null!==e.collectionGroup}function Sn(e){var t=H(e);if(null===t.dt){t.dt=[];var n=En(t),r=In(t);if(null!==n&&null===r)n.isKeyField()||t.dt.push(new Jt(n)),t.dt.push(new Jt(me.keyField(),"asc"));else{var i,a=!1,u=v(t.explicitOrderBy);try{for(u.s();!(i=u.n()).done;){var o=i.value;t.dt.push(o),o.field.isKeyField()&&(a=!0)}}catch(c){u.e(c)}finally{u.f()}if(!a){var s=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.dt.push(new Jt(me.keyField(),s))}}}return t.dt}function _n(e){var t=H(e);if(!t._t)if("F"===t.limitType)t._t=hn(t.path,t.collectionGroup,Sn(t),t.filters,t.limit,t.startAt,t.endAt);else{var n,r=[],i=v(Sn(t));try{for(i.s();!(n=i.n()).done;){var a=n.value,u="desc"===a.dir?"asc":"desc";r.push(new Jt(a.field,u))}}catch(c){i.e(c)}finally{i.f()}var o=t.endAt?new Ct(t.endAt.position,t.endAt.inclusive):null,s=t.startAt?new Ct(t.startAt.position,t.startAt.inclusive):null;t._t=hn(t.path,t.collectionGroup,r,t.filters,t.limit,o,s)}return t._t}function Dn(e,t){t.getFirstInequalityField(),En(e);var n=e.filters.concat([t]);return new kn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function An(e,t,n){return new kn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Cn(e,t){return vn(_n(e),_n(t))&&e.limitType===t.limitType}function Nn(e){return"".concat(dn(_n(e)),"|lt:").concat(e.limitType)}function Pn(e){return"Query(target=".concat(function(e){var t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=", filters: [".concat(e.filters.map(function(e){return Kt(e)}).join(", "),"]")),Ze(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=", orderBy: [".concat(e.orderBy.map(function(e){return function(e){return"".concat(e.field.canonicalString()," (").concat(e.dir,")")}(e)}).join(", "),"]")),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(function(e){return pt(e)}).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(function(e){return pt(e)}).join(",")),"Target(".concat(t,")")}(_n(e)),"; limitType=").concat(e.limitType,")")}function Ln(e,t){return t.isFoundDocument()&&function(e,t){var n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):ge.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){var n,r=v(Sn(e));try{for(r.s();!(n=r.n()).done;){var i=n.value;if(!i.field.isKeyField()&&null===t.data.field(i.field))return!1}}catch(a){r.e(a)}finally{r.f()}return!0}(e,t)&&function(e,t){var n,r=v(e.filters);try{for(r.s();!(n=r.n()).done;){if(!n.value.matches(t))return!1}}catch(i){r.e(i)}finally{r.f()}return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){var r=Nt(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Sn(e),t))&&!(e.endAt&&!function(e,t,n){var r=Nt(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Sn(e),t))}(e,t)}function Fn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Mn(e){return function(t,n){var r,i=!1,a=v(Sn(e));try{for(a.s();!(r=a.n()).done;){var u=r.value,o=Rn(u,t,n);if(0!==o)return o;i=i||u.field.isKeyField()}}catch(s){a.e(s)}finally{a.f()}return 0}}function Rn(e,t,n){var r=e.field.isKeyField()?ge.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?vt(r,i):j()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return j()}}function Vn(e,t){if(e.wt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Je(t)?"-0":t}}function On(e){return{integerValue:""+e}}function qn(e,t){return $e(t)?On(t):Vn(e,t)}var Un=P(function e(){C(this,e),this._=void 0});function Bn(e,t,n){return e instanceof Qn?function(e,t){var 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 jn?zn(e,t):e instanceof Wn?Hn(e,t):function(e,t){var n=Kn(e,t),r=Xn(n)+Xn(e.gt);return kt(n)&&kt(e.gt)?On(r):Vn(e.yt,r)}(e,t)}function Gn(e,t,n){return e instanceof jn?zn(e,t):e instanceof Wn?Hn(e,t):n}function Kn(e,t){return e instanceof Yn?kt(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}var Qn=function(e){p(n,Un);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n)}(),jn=function(e){p(n,Un);var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this)).elements=e,r}return P(n)}();function zn(e,t){var n,r=Zn(t),i=v(e.elements);try{var a=function(){var e=n.value;r.some(function(t){return ht(t,e)})||r.push(e)};for(i.s();!(n=i.n()).done;)a()}catch(u){i.e(u)}finally{i.f()}return{arrayValue:{values:r}}}var Wn=function(e){p(n,Un);var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this)).elements=e,r}return P(n)}();function Hn(e,t){var n,r=Zn(t),i=v(e.elements);try{var a=function(){var e=n.value;r=r.filter(function(t){return!ht(t,e)})};for(i.s();!(n=i.n()).done;)a()}catch(u){i.e(u)}finally{i.f()}return{arrayValue:{values:r}}}var Yn=function(e){p(n,Un);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).yt=e,i.gt=r,i}return P(n)}();function Xn(e){return it(e.integerValue||e.doubleValue)}function Zn(e){return wt(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}var Jn=P(function e(t,n){C(this,e),this.field=t,this.transform=n});function $n(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof jn&&t instanceof jn||e instanceof Wn&&t instanceof Wn?le(e.elements,t.elements,ht):e instanceof Yn&&t instanceof Yn?ht(e.gt,t.gt):e instanceof Qn&&t instanceof Qn}(e.transform,t.transform)}var er=P(function e(t,n){C(this,e),this.version=t,this.transformResults=n}),tr=function(){function e(t,n){C(this,e),this.updateTime=t,this.exists=n}return P(e,[{key:"isNone",get:function(){return void 0===this.updateTime&&void 0===this.exists}},{key:"isEqual",value:function(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}],[{key:"none",value:function(){return new e}},{key:"exists",value:function(t){return new e(void 0,t)}},{key:"updateTime",value:function(t){return new e(t)}}]),e}();function nr(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}var rr=P(function e(){C(this,e)});function ir(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new pr(e.key,tr.none()):new cr(e.key,e.data,tr.none());var n,r=e.data,i=sn.empty(),a=new rn(me.comparator),u=v(t.fields);try{for(u.s();!(n=u.n()).done;){var o=n.value;if(!a.has(o)){var s=r.field(o);null===s&&o.length>1&&(o=o.popLast(),s=r.field(o)),null===s?i.delete(o):i.set(o,s),a=a.add(o)}}}catch(c){u.e(c)}finally{u.f()}return new lr(e.key,i,new on(a.toArray()),tr.none())}function ar(e,t,n){e instanceof cr?function(e,t,n){var r=e.value.clone(),i=hr(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof lr?function(e,t,n){if(nr(e.precondition,t)){var r=hr(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(fr(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}else t.convertToUnknownDocument(n.version)}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function ur(e,t,n,r){return e instanceof cr?function(e,t,n,r){if(!nr(e.precondition,t))return n;var i=e.value.clone(),a=dr(e.fieldTransforms,r,t);return i.setAll(a),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof lr?function(e,t,n,r){if(!nr(e.precondition,t))return n;var i=dr(e.fieldTransforms,r,t),a=t.data;return a.setAll(fr(e)),a.setAll(i),t.convertToFoundDocument(t.version,a).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(function(e){return e.field}))}(e,t,n,r):function(e,t,n){return nr(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function or(e,t){var n,r=null,i=v(e.fieldTransforms);try{for(i.s();!(n=i.n()).done;){var a=n.value,u=t.data.field(a.field),o=Kn(a.transform,u||null);null!=o&&(null===r&&(r=sn.empty()),r.set(a.field,o))}}catch(s){i.e(s)}finally{i.f()}return r||null}function sr(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)&&le(e,t,function(e,t){return $n(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))}var cr=function(e){p(n,rr);var t=g(n);function n(e,r,i){var a,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];return C(this,n),(a=t.call(this)).key=e,a.value=r,a.precondition=i,a.fieldTransforms=u,a.type=0,a}return P(n,[{key:"getFieldMask",value:function(){return null}}]),n}(),lr=function(e){p(n,rr);var t=g(n);function n(e,r,i,a){var u,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[];return C(this,n),(u=t.call(this)).key=e,u.data=r,u.fieldMask=i,u.precondition=a,u.fieldTransforms=o,u.type=1,u}return P(n,[{key:"getFieldMask",value:function(){return this.fieldMask}}]),n}();function fr(e){var t=new Map;return e.fieldMask.fields.forEach(function(n){if(!n.isEmpty()){var r=e.data.field(n);t.set(n,r)}}),t}function hr(e,t,n){var r=new Map;z(e.length===n.length);for(var i=0;i<n.length;i++){var a=e[i],u=a.transform,o=t.data.field(a.field);r.set(a.field,Gn(u,o,n[i]))}return r}function dr(e,t,n){var r,i=new Map,a=v(e);try{for(a.s();!(r=a.n()).done;){var u=r.value,o=u.transform,s=n.data.field(u.field);i.set(u.field,Bn(o,s,t))}}catch(c){a.e(c)}finally{a.f()}return i}var vr,yr,pr=function(e){p(n,rr);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).key=e,i.precondition=r,i.type=2,i.fieldTransforms=[],i}return P(n,[{key:"getFieldMask",value:function(){return null}}]),n}(),mr=function(e){p(n,rr);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).key=e,i.precondition=r,i.type=3,i.fieldTransforms=[],i}return P(n,[{key:"getFieldMask",value:function(){return null}}]),n}(),gr=P(function e(t){C(this,e),this.count=t});function kr(e){switch(e){default:return j();case Y.CANCELLED:case Y.UNKNOWN:case Y.DEADLINE_EXCEEDED:case Y.RESOURCE_EXHAUSTED:case Y.INTERNAL:case Y.UNAVAILABLE:case Y.UNAUTHENTICATED:return!1;case Y.INVALID_ARGUMENT:case Y.NOT_FOUND:case Y.ALREADY_EXISTS:case Y.PERMISSION_DENIED:case Y.FAILED_PRECONDITION:case Y.ABORTED:case Y.OUT_OF_RANGE:case Y.UNIMPLEMENTED:case Y.DATA_LOSS:return!0}}function wr(e){if(void 0===e)return G("GRPC error has no .code"),Y.UNKNOWN;switch(e){case vr.OK:return Y.OK;case vr.CANCELLED:return Y.CANCELLED;case vr.UNKNOWN:return Y.UNKNOWN;case vr.DEADLINE_EXCEEDED:return Y.DEADLINE_EXCEEDED;case vr.RESOURCE_EXHAUSTED:return Y.RESOURCE_EXHAUSTED;case vr.INTERNAL:return Y.INTERNAL;case vr.UNAVAILABLE:return Y.UNAVAILABLE;case vr.UNAUTHENTICATED:return Y.UNAUTHENTICATED;case vr.INVALID_ARGUMENT:return Y.INVALID_ARGUMENT;case vr.NOT_FOUND:return Y.NOT_FOUND;case vr.ALREADY_EXISTS:return Y.ALREADY_EXISTS;case vr.PERMISSION_DENIED:return Y.PERMISSION_DENIED;case vr.FAILED_PRECONDITION:return Y.FAILED_PRECONDITION;case vr.ABORTED:return Y.ABORTED;case vr.OUT_OF_RANGE:return Y.OUT_OF_RANGE;case vr.UNIMPLEMENTED:return Y.UNIMPLEMENTED;case vr.DATA_LOSS:return Y.DATA_LOSS;default:return j()}}(yr=vr||(vr={}))[yr.OK=0]="OK",yr[yr.CANCELLED=1]="CANCELLED",yr[yr.UNKNOWN=2]="UNKNOWN",yr[yr.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",yr[yr.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",yr[yr.NOT_FOUND=5]="NOT_FOUND",yr[yr.ALREADY_EXISTS=6]="ALREADY_EXISTS",yr[yr.PERMISSION_DENIED=7]="PERMISSION_DENIED",yr[yr.UNAUTHENTICATED=16]="UNAUTHENTICATED",yr[yr.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",yr[yr.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",yr[yr.ABORTED=10]="ABORTED",yr[yr.OUT_OF_RANGE=11]="OUT_OF_RANGE",yr[yr.UNIMPLEMENTED=12]="UNIMPLEMENTED",yr[yr.INTERNAL=13]="INTERNAL",yr[yr.UNAVAILABLE=14]="UNAVAILABLE",yr[yr.DATA_LOSS=15]="DATA_LOSS";var xr=function(){function e(t,n){C(this,e),this.mapKeyFn=t,this.equalsFn=n,this.inner={},this.innerSize=0}return P(e,[{key:"get",value:function(e){var t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n){var r,i=v(n);try{for(i.s();!(r=i.n()).done;){var a=l(r.value,2),u=a[0],o=a[1];if(this.equalsFn(u,e))return o}}catch(s){i.e(s)}finally{i.f()}}}},{key:"has",value:function(e){return void 0!==this.get(e)}},{key:"set",value:function(e,t){var n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(var i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}},{key:"delete",value:function(e){var t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(var r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}},{key:"forEach",value:function(e){Ye(this.inner,function(t,n){var r,i=v(n);try{for(i.s();!(r=i.n()).done;){var a=l(r.value,2),u=a[0],o=a[1];e(u,o)}}catch(s){i.e(s)}finally{i.f()}})}},{key:"isEmpty",value:function(){return Xe(this.inner)}},{key:"size",value:function(){return this.innerSize}}]),e}(),br=new en(ge.comparator);function Ir(){return br}var Er=new en(ge.comparator);function Tr(){for(var e=Er,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0,a=n;i<a.length;i++){var u=a[i];e=e.insert(u.key,u)}return e}function Sr(e){var t=Er;return e.forEach(function(e,n){return t=t.insert(e,n.overlayedDocument)}),t}function _r(){return Ar()}function Dr(){return Ar()}function Ar(){return new xr(function(e){return e.toString()},function(e,t){return e.isEqual(t)})}var Cr=new en(ge.comparator),Nr=new rn(ge.comparator);function Pr(){for(var e=Nr,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0,a=n;i<a.length;i++){var u=a[i];e=e.add(u)}return e}var Lr=new rn(ce);function Fr(){return Lr}var Mr=function(){function e(t,n,r,i,a){C(this,e),this.snapshotVersion=t,this.targetChanges=n,this.targetMismatches=r,this.documentUpdates=i,this.resolvedLimboDocuments=a}return P(e,null,[{key:"createSynthesizedRemoteEventForCurrentChange",value:function(t,n,r){var i=new Map;return i.set(t,Rr.createSynthesizedTargetChangeForCurrentChange(t,n,r)),new e(de.min(),i,Fr(),Ir(),Pr())}}]),e}(),Rr=function(){function e(t,n,r,i,a){C(this,e),this.resumeToken=t,this.current=n,this.addedDocuments=r,this.modifiedDocuments=i,this.removedDocuments=a}return P(e,null,[{key:"createSynthesizedTargetChangeForCurrentChange",value:function(t,n,r){return new e(r,n,Pr(),Pr(),Pr())}}]),e}(),Vr=P(function e(t,n,r,i){C(this,e),this.It=t,this.removedTargetIds=n,this.key=r,this.Tt=i}),Or=P(function e(t,n){C(this,e),this.targetId=t,this.Et=n}),qr=P(function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:tt.EMPTY_BYTE_STRING,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;C(this,e),this.state=t,this.targetIds=n,this.resumeToken=r,this.cause=i}),Ur=function(){function e(){C(this,e),this.At=0,this.Rt=Kr(),this.bt=tt.EMPTY_BYTE_STRING,this.Pt=!1,this.vt=!0}return P(e,[{key:"current",get:function(){return this.Pt}},{key:"resumeToken",get:function(){return this.bt}},{key:"Vt",get:function(){return 0!==this.At}},{key:"St",get:function(){return this.vt}},{key:"Dt",value:function(e){e.approximateByteSize()>0&&(this.vt=!0,this.bt=e)}},{key:"Ct",value:function(){var e=Pr(),t=Pr(),n=Pr();return this.Rt.forEach(function(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:j()}}),new Rr(this.bt,this.Pt,e,t,n)}},{key:"xt",value:function(){this.vt=!1,this.Rt=Kr()}},{key:"Nt",value:function(e,t){this.vt=!0,this.Rt=this.Rt.insert(e,t)}},{key:"kt",value:function(e){this.vt=!0,this.Rt=this.Rt.remove(e)}},{key:"Ot",value:function(){this.At+=1}},{key:"Mt",value:function(){this.At-=1}},{key:"Ft",value:function(){this.vt=!0,this.Pt=!0}}]),e}(),Br=function(){function e(t){C(this,e),this.$t=t,this.Bt=new Map,this.Lt=Ir(),this.qt=Gr(),this.Ut=new rn(ce)}return P(e,[{key:"Kt",value:function(e){var t,n=v(e.It);try{for(n.s();!(t=n.n()).done;){var r=t.value;e.Tt&&e.Tt.isFoundDocument()?this.Gt(r,e.Tt):this.Qt(r,e.key,e.Tt)}}catch(o){n.e(o)}finally{n.f()}var i,a=v(e.removedTargetIds);try{for(a.s();!(i=a.n()).done;){var u=i.value;this.Qt(u,e.key,e.Tt)}}catch(o){a.e(o)}finally{a.f()}}},{key:"jt",value:function(e){var t=this;this.forEachTarget(e,function(n){var r=t.Wt(n);switch(e.state){case 0:t.zt(n)&&r.Dt(e.resumeToken);break;case 1:r.Mt(),r.Vt||r.xt(),r.Dt(e.resumeToken);break;case 2:r.Mt(),r.Vt||t.removeTarget(n);break;case 3:t.zt(n)&&(r.Ft(),r.Dt(e.resumeToken));break;case 4:t.zt(n)&&(t.Ht(n),r.Dt(e.resumeToken));break;default:j()}})}},{key:"forEachTarget",value:function(e,t){var n=this;e.targetIds.length>0?e.targetIds.forEach(t):this.Bt.forEach(function(e,r){n.zt(r)&&t(r)})}},{key:"Jt",value:function(e){var t=e.targetId,n=e.Et.count,r=this.Yt(t);if(r){var i=r.target;if(yn(i))if(0===n){var a=new ge(i.path);this.Qt(t,a,ln.newNoDocument(a,de.min()))}else z(1===n);else this.Xt(t)!==n&&(this.Ht(t),this.Ut=this.Ut.add(t))}}},{key:"Zt",value:function(e){var t=this,n=new Map;this.Bt.forEach(function(r,i){var a=t.Yt(i);if(a){if(r.current&&yn(a.target)){var u=new ge(a.target.path);null!==t.Lt.get(u)||t.te(i,u)||t.Qt(i,u,ln.newNoDocument(u,e))}r.St&&(n.set(i,r.Ct()),r.xt())}});var r=Pr();this.qt.forEach(function(e,n){var i=!0;n.forEachWhile(function(e){var n=t.Yt(e);return!n||2===n.purpose||(i=!1,!1)}),i&&(r=r.add(e))}),this.Lt.forEach(function(t,n){return n.setReadTime(e)});var i=new Mr(e,n,this.Ut,this.Lt,r);return this.Lt=Ir(),this.qt=Gr(),this.Ut=new rn(ce),i}},{key:"Gt",value:function(e,t){if(this.zt(e)){var n=this.te(e,t.key)?2:0;this.Wt(e).Nt(t.key,n),this.Lt=this.Lt.insert(t.key,t),this.qt=this.qt.insert(t.key,this.ee(t.key).add(e))}}},{key:"Qt",value:function(e,t,n){if(this.zt(e)){var r=this.Wt(e);this.te(e,t)?r.Nt(t,1):r.kt(t),this.qt=this.qt.insert(t,this.ee(t).delete(e)),n&&(this.Lt=this.Lt.insert(t,n))}}},{key:"removeTarget",value:function(e){this.Bt.delete(e)}},{key:"Xt",value:function(e){var t=this.Wt(e).Ct();return this.$t.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}},{key:"Ot",value:function(e){this.Wt(e).Ot()}},{key:"Wt",value:function(e){var t=this.Bt.get(e);return t||(t=new Ur,this.Bt.set(e,t)),t}},{key:"ee",value:function(e){var t=this.qt.get(e);return t||(t=new rn(ce),this.qt=this.qt.insert(e,t)),t}},{key:"zt",value:function(e){var t=null!==this.Yt(e);return t||B("WatchChangeAggregator","Detected inactive target",e),t}},{key:"Yt",value:function(e){var t=this.Bt.get(e);return t&&t.Vt?null:this.$t.ne(e)}},{key:"Ht",value:function(e){var t=this;this.Bt.set(e,new Ur),this.$t.getRemoteKeysForTarget(e).forEach(function(n){t.Qt(e,n,null)})}},{key:"te",value:function(e,t){return this.$t.getRemoteKeysForTarget(e).has(t)}}]),e}();function Gr(){return new en(ge.comparator)}function Kr(){return new en(ge.comparator)}var Qr={asc:"ASCENDING",desc:"DESCENDING"},jr={"<":"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"},zr={and:"AND",or:"OR"},Wr=P(function e(t,n){C(this,e),this.databaseId=t,this.wt=n});function Hr(e,t){return e.wt?"".concat(new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z",""),".").concat(("000000000"+t.nanoseconds).slice(-9),"Z"):{seconds:""+t.seconds,nanos:t.nanoseconds}}function Yr(e,t){return e.wt?t.toBase64():t.toUint8Array()}function Xr(e,t){return Hr(e,t.toTimestamp())}function Zr(e){return z(!!e),de.fromTimestamp(function(e){var t=rt(e);return new he(t.seconds,t.nanos)}(e))}function Jr(e,t){return function(e){return new ye(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function $r(e){var t=ye.fromString(e);return z(Ti(t)),t}function ei(e,t){return Jr(e.databaseId,t.path)}function ti(e,t){var n=$r(t);if(n.get(1)!==e.databaseId.projectId)throw new X(Y.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 X(Y.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ge(ai(n))}function ni(e,t){return Jr(e.databaseId,t)}function ri(e){var t=$r(e);return 4===t.length?ye.emptyPath():ai(t)}function ii(e){return new ye(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function ai(e){return z(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function ui(e,t,n){return{name:ei(e,t),fields:n.value.mapValue.fields}}function oi(e,t,n){var r=ti(e,t.name),i=Zr(t.updateTime),a=t.createTime?Zr(t.createTime):de.min(),u=new sn({mapValue:{fields:t.fields}}),o=ln.newFoundDocument(r,i,a,u);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function si(e,t){return"found"in t?function(e,t){z(!!t.found),t.found.name,t.found.updateTime;var n=ti(e,t.found.name),r=Zr(t.found.updateTime),i=t.found.createTime?Zr(t.found.createTime):de.min(),a=new sn({mapValue:{fields:t.found.fields}});return ln.newFoundDocument(n,r,i,a)}(e,t):"missing"in t?function(e,t){z(!!t.missing),z(!!t.readTime);var n=ti(e,t.missing),r=Zr(t.readTime);return ln.newNoDocument(n,r)}(e,t):j()}function ci(e,t){var n;if("targetChange"in t){t.targetChange;var r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:j()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],a=function(e,t){return e.wt?(z(void 0===t||"string"==typeof t),tt.fromBase64String(t||"")):(z(void 0===t||t instanceof Uint8Array),tt.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),u=t.targetChange.cause,o=u&&function(e){var t=void 0===e.code?Y.UNKNOWN:wr(e.code);return new X(t,e.message||"")}(u);n=new qr(r,i,a,o||null)}else if("documentChange"in t){t.documentChange;var s=t.documentChange;s.document,s.document.name,s.document.updateTime;var c=ti(e,s.document.name),l=Zr(s.document.updateTime),f=s.document.createTime?Zr(s.document.createTime):de.min(),h=new sn({mapValue:{fields:s.document.fields}}),d=ln.newFoundDocument(c,l,f,h),v=s.targetIds||[],y=s.removedTargetIds||[];n=new Vr(v,y,d.key,d)}else if("documentDelete"in t){t.documentDelete;var p=t.documentDelete;p.document;var m=ti(e,p.document),g=p.readTime?Zr(p.readTime):de.min(),k=ln.newNoDocument(m,g),w=p.removedTargetIds||[];n=new Vr([],w,k.key,k)}else if("documentRemove"in t){t.documentRemove;var x=t.documentRemove;x.document;var b=ti(e,x.document),I=x.removedTargetIds||[];n=new Vr([],I,b,null)}else{if(!("filter"in t))return j();t.filter;var E=t.filter;E.targetId;var T=E.count||0,S=new gr(T),_=E.targetId;n=new Or(_,S)}return n}function li(e,t){var n;if(t instanceof cr)n={update:ui(e,t.key,t.value)};else if(t instanceof pr)n={delete:ei(e,t.key)};else if(t instanceof lr)n={update:ui(e,t.key,t.data),updateMask:Ei(t.fieldMask)};else{if(!(t instanceof mr))return j();n={verify:ei(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map(function(e){return function(e,t){var n=t.transform;if(n instanceof Qn)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof jn)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof Wn)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof Yn)return{fieldPath:t.field.canonicalString(),increment:n.gt};throw j()}(0,e)})),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:Xr(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:j()}(e,t.precondition)),n}function fi(e,t){var n=t.currentDocument?function(e){return void 0!==e.updateTime?tr.updateTime(Zr(e.updateTime)):void 0!==e.exists?tr.exists(e.exists):tr.none()}(t.currentDocument):tr.none(),r=t.updateTransforms?t.updateTransforms.map(function(t){return function(e,t){var n=null;if("setToServerValue"in t)z("REQUEST_TIME"===t.setToServerValue),n=new Qn;else if("appendMissingElements"in t){var r=t.appendMissingElements.values||[];n=new jn(r)}else if("removeAllFromArray"in t){var i=t.removeAllFromArray.values||[];n=new Wn(i)}else"increment"in t?n=new Yn(e,t.increment):j();var a=me.fromServerFormat(t.fieldPath);return new Jn(a,n)}(e,t)}):[];if(t.update){t.update.name;var i=ti(e,t.update.name),a=new sn({mapValue:{fields:t.update.fields}});if(t.updateMask){var u=function(e){var t=e.fieldPaths||[];return new on(t.map(function(e){return me.fromServerFormat(e)}))}(t.updateMask);return new lr(i,a,u,n,r)}return new cr(i,a,n,r)}if(t.delete){var o=ti(e,t.delete);return new pr(o,n)}if(t.verify){var s=ti(e,t.verify);return new mr(s,n)}return j()}function hi(e,t){return e&&e.length>0?(z(void 0!==t),e.map(function(e){return function(e,t){var n=e.updateTime?Zr(e.updateTime):Zr(t);return n.isEqual(de.min())&&(n=Zr(t)),new er(n,e.transformResults||[])}(e,t)})):[]}function di(e,t){return{documents:[ni(e,t.path)]}}function vi(e,t){var n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=ni(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=ni(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return Ii(Mt.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);var a=function(e){if(0!==e.length)return e.map(function(e){return function(e){return{field:xi(e.field),direction:gi(e.dir)}}(e)})}(t.orderBy);a&&(n.structuredQuery.orderBy=a);var u,o=function(e,t){return e.wt||Ze(t)?t:{value:t}}(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt={before:(u=t.startAt).inclusive,values:u.position}),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function yi(e){var t=ri(e.parent),n=e.structuredQuery,r=n.from?n.from.length:0,i=null;if(r>0){z(1===r);var a=n.from[0];a.allDescendants?i=a.collectionId:t=t.child(a.collectionId)}var u=[];n.where&&(u=function(e){var t=mi(n.where);return t instanceof Mt&&Ot(t)?t.getFilters():[t]}());var o=[];n.orderBy&&(o=n.orderBy.map(function(e){return function(e){return new Jt(bi(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)}));var s=null;n.limit&&(s=function(e){var t;return Ze(t="object"==A(e)?e.value:e)?null:t}(n.limit));var c=null;n.startAt&&(c=function(e){var t=!!e.before,n=e.values||[];return new Ct(n,t)}(n.startAt));var l=null;return n.endAt&&(l=function(e){var t=!e.before,n=e.values||[];return new Ct(n,t)}(n.endAt)),wn(t,i,o,u,s,"F",c,l)}function pi(e,t){var n=function(e,t){switch(t){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return j()}}(0,t.purpose);return null==n?null:{"goog-listen-tags":n}}function mi(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":var t=bi(e.unaryFilter.field);return Ft.create(t,"==",{doubleValue:NaN});case"IS_NULL":var n=bi(e.unaryFilter.field);return Ft.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var r=bi(e.unaryFilter.field);return Ft.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":var i=bi(e.unaryFilter.field);return Ft.create(i,"!=",{nullValue:"NULL_VALUE"});default:return j()}}(e):void 0!==e.fieldFilter?function(e){return Ft.create(bi(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 j()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return Mt.create(e.compositeFilter.filters.map(function(e){return mi(e)}),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return j()}}(e.compositeFilter.op))}(e):j()}function gi(e){return Qr[e]}function ki(e){return jr[e]}function wi(e){return zr[e]}function xi(e){return{fieldPath:e.canonicalString()}}function bi(e){return me.fromServerFormat(e.fieldPath)}function Ii(e){return e instanceof Ft?function(e){if("=="===e.op){if(bt(e.value))return{unaryFilter:{field:xi(e.field),op:"IS_NAN"}};if(xt(e.value))return{unaryFilter:{field:xi(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(bt(e.value))return{unaryFilter:{field:xi(e.field),op:"IS_NOT_NAN"}};if(xt(e.value))return{unaryFilter:{field:xi(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:xi(e.field),op:ki(e.op),value:e.value}}}(e):e instanceof Mt?function(e){var t=e.getFilters().map(function(e){return Ii(e)});return 1===t.length?t[0]:{compositeFilter:{op:wi(e.op),filters:t}}}(e):j()}function Ei(e){var t=[];return e.fields.forEach(function(e){return t.push(e.canonicalString())}),{fieldPaths:t}}function Ti(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function Si(e){for(var t="",n=0;n<e.length;n++)t.length>0&&(t=Di(t)),t=_i(e.get(n),t);return Di(t)}function _i(e,t){for(var n=t,r=e.length,i=0;i<r;i++){var a=e.charAt(i);switch(a){case"\0":n+="";break;case"":n+="";break;default:n+=a}}return n}function Di(e){return e+""}function Ai(e){var t=e.length;if(z(t>=2),2===t)return z(""===e.charAt(0)&&""===e.charAt(1)),ye.emptyPath();for(var n=t-2,r=[],i="",a=0;a<t;){var u=e.indexOf("",a);switch((u<0||u>n)&&j(),e.charAt(u+1)){case"":var o=e.substring(a,u),s=void 0;0===i.length?s=o:(s=i+=o,i=""),r.push(s);break;case"":i+=e.substring(a,u),i+="\0";break;case"":i+=e.substring(a,u+1);break;default:j()}a=u+2}return new ye(r)}var Ci=["userId","batchId"];function Ni(e,t){return[e,Si(t)]}function Pi(e,t,n){return[e,Si(t),n]}var Li={},Fi=["prefixPath","collectionGroup","readTime","documentId"],Mi=["prefixPath","collectionGroup","documentId"],Ri=["collectionGroup","readTime","prefixPath","documentId"],Vi=["canonicalId","targetId"],Oi=["targetId","path"],qi=["path","targetId"],Ui=["collectionId","parent"],Bi=["indexId","uid"],Gi=["uid","sequenceNumber"],Ki=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Qi=["indexId","uid","orderedDocumentKey"],ji=["userId","collectionPath","documentId"],zi=["userId","collectionPath","largestBatchId"],Wi=["userId","collectionGroup","largestBatchId"],Hi=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments"].concat(["clientMetadata"]).concat(["remoteDocumentGlobal"]).concat(["collectionParents"]).concat(["bundles","namedQueries"]),Yi=[].concat(I(Hi),["documentOverlays"]),Xi=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Zi=Xi,Ji=[].concat(Zi,["indexConfiguration","indexState","indexEntries"]),$i=function(e){p(n,Ne);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).se=e,i.currentSequenceNumber=r,i}return P(n)}();function ea(e,t){var n=H(e);return Me.M(n.se,t)}var ta=function(){function e(t,n,r,i){C(this,e),this.batchId=t,this.localWriteTime=n,this.baseMutations=r,this.mutations=i}return P(e,[{key:"applyToRemoteDocument",value:function(e,t){for(var n=t.mutationResults,r=0;r<this.mutations.length;r++){var i=this.mutations[r];i.key.isEqual(e.key)&&ar(i,e,n[r])}}},{key:"applyToLocalView",value:function(e,t){var n,r=v(this.baseMutations);try{for(r.s();!(n=r.n()).done;){var i=n.value;i.key.isEqual(e.key)&&(t=ur(i,e,t,this.localWriteTime))}}catch(s){r.e(s)}finally{r.f()}var a,u=v(this.mutations);try{for(u.s();!(a=u.n()).done;){var o=a.value;o.key.isEqual(e.key)&&(t=ur(o,e,t,this.localWriteTime))}}catch(s){u.e(s)}finally{u.f()}return t}},{key:"applyToLocalDocumentSet",value:function(e,t){var n=this,r=Dr();return this.mutations.forEach(function(i){var a=e.get(i.key),u=a.overlayedDocument,o=n.applyToLocalView(u,a.mutatedFields),s=ir(u,o=t.has(i.key)?null:o);null!==s&&r.set(i.key,s),u.isValidDocument()||u.convertToNoDocument(de.min())}),r}},{key:"keys",value:function(){return this.mutations.reduce(function(e,t){return e.add(t.key)},Pr())}},{key:"isEqual",value:function(e){return this.batchId===e.batchId&&le(this.mutations,e.mutations,function(e,t){return sr(e,t)})&&le(this.baseMutations,e.baseMutations,function(e,t){return sr(e,t)})}}]),e}(),na=function(){function e(t,n,r,i){C(this,e),this.batch=t,this.commitVersion=n,this.mutationResults=r,this.docVersions=i}return P(e,null,[{key:"from",value:function(t,n,r){z(t.mutations.length===r.length);for(var i=Cr,a=t.mutations,u=0;u<a.length;u++)i=i.insert(a[u].key,r[u].version);return new e(t,n,r,i)}}]),e}(),ra=function(){function e(t,n){C(this,e),this.largestBatchId=t,this.mutation=n}return P(e,[{key:"getKey",value:function(){return this.mutation.key}},{key:"isEqual",value:function(e){return null!==e&&this.mutation===e.mutation}},{key:"toString",value:function(){return"Overlay{\n largestBatchId: ".concat(this.largestBatchId,",\n mutation: ").concat(this.mutation.toString(),"\n }")}}]),e}(),ia=function(){function e(t,n,r,i){var a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:de.min(),u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:de.min(),o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:tt.EMPTY_BYTE_STRING;C(this,e),this.target=t,this.targetId=n,this.purpose=r,this.sequenceNumber=i,this.snapshotVersion=a,this.lastLimboFreeSnapshotVersion=u,this.resumeToken=o}return P(e,[{key:"withSequenceNumber",value:function(t){return new e(this.target,this.targetId,this.purpose,t,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}},{key:"withResumeToken",value:function(t,n){return new e(this.target,this.targetId,this.purpose,this.sequenceNumber,n,this.lastLimboFreeSnapshotVersion,t)}},{key:"withLastLimboFreeSnapshotVersion",value:function(t){return new e(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,t,this.resumeToken)}}]),e}(),aa=P(function e(t){C(this,e),this.ie=t});function ua(e,t){var n;if(t.document)n=oi(e.ie,t.document,!!t.hasCommittedMutations);else if(t.noDocument){var r=ge.fromSegments(t.noDocument.path),i=la(t.noDocument.readTime);n=ln.newNoDocument(r,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return j();var a=ge.fromSegments(t.unknownDocument.path),u=la(t.unknownDocument.version);n=ln.newUnknownDocument(a,u)}return t.readTime&&n.setReadTime(function(e){var t=new he(e[0],e[1]);return de.fromTimestamp(t)}(t.readTime)),n}function oa(e,t){var n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:sa(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:ei(e,t.key),fields:t.data.value.mapValue.fields,updateTime:Hr(e,t.version.toTimestamp()),createTime:Hr(e,t.createTime.toTimestamp())}}(e.ie,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:ca(t.version)};else{if(!t.isUnknownDocument())return j();r.unknownDocument={path:n.path.toArray(),version:ca(t.version)}}return r}function sa(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function ca(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function la(e){var t=new he(e.seconds,e.nanoseconds);return de.fromTimestamp(t)}function fa(e,t){for(var n=(t.baseMutations||[]).map(function(t){return fi(e.ie,t)}),r=0;r<t.mutations.length-1;++r){var i=t.mutations[r];if(r+1<t.mutations.length&&void 0!==t.mutations[r+1].transform){var a=t.mutations[r+1];i.updateTransforms=a.transform.fieldTransforms,t.mutations.splice(r+1,1),++r}}var u=t.mutations.map(function(t){return fi(e.ie,t)}),o=he.fromMillis(t.localWriteTimeMs);return new ta(t.batchId,o,n,u)}function ha(e){var t,n,r=la(e.readTime),i=void 0!==e.lastLimboFreeSnapshotVersion?la(e.lastLimboFreeSnapshotVersion):de.min();return void 0!==e.query.documents?(z(1===(n=e.query).documents.length),t=_n(xn(ri(n.documents[0])))):t=function(e){return _n(yi(e))}(e.query),new ia(t,e.targetId,0,e.lastListenSequenceNumber,r,i,tt.fromBase64String(e.resumeToken))}function da(e,t){var n,r=ca(t.snapshotVersion),i=ca(t.lastLimboFreeSnapshotVersion);n=yn(t.target)?di(e.ie,t.target):vi(e.ie,t.target);var a=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:dn(t.target),readTime:r,resumeToken:a,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function va(e){var t=yi({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?An(t,t.limit,"L"):t}function ya(e,t){return new ra(t.largestBatchId,fi(e.ie,t.overlayMutation))}function pa(e,t){var n=t.path.lastSegment();return[e,Si(t.path.popLast()),n]}function ma(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:ca(r.readTime),documentKey:Si(r.documentKey.path),largestBatchId:r.largestBatchId}}var ga=function(){function e(){C(this,e)}return P(e,[{key:"getBundleMetadata",value:function(e,t){return ka(e).get(t).next(function(e){if(e)return{id:(t=e).bundleId,createTime:la(t.createTime),version:t.version};var t})}},{key:"saveBundleMetadata",value:function(e,t){return ka(e).put({bundleId:(n=t).id,createTime:ca(Zr(n.createTime)),version:n.version});var n}},{key:"getNamedQuery",value:function(e,t){return wa(e).get(t).next(function(e){if(e)return{name:(t=e).name,query:va(t.bundledQuery),readTime:la(t.readTime)};var t})}},{key:"saveNamedQuery",value:function(e,t){return wa(e).put(function(e){return{name:e.name,readTime:ca(Zr(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}]),e}();function ka(e){return ea(e,"bundles")}function wa(e){return ea(e,"namedQueries")}var xa=function(){function e(t,n){C(this,e),this.yt=t,this.userId=n}return P(e,[{key:"getOverlay",value:function(e,t){var n=this;return ba(e).get(pa(this.userId,t)).next(function(e){return e?ya(n.yt,e):null})}},{key:"getOverlays",value:function(e,t){var n=this,r=_r();return Le.forEach(t,function(t){return n.getOverlay(e,t).next(function(e){null!==e&&r.set(t,e)})}).next(function(){return r})}},{key:"saveOverlays",value:function(e,t,n){var r=this,i=[];return n.forEach(function(n,a){var u=new ra(t,a);i.push(r.oe(e,u))}),Le.waitFor(i)}},{key:"removeOverlaysForBatchId",value:function(e,t,n){var r=this,i=new Set;t.forEach(function(e){return i.add(Si(e.getCollectionPath()))});var a=[];return i.forEach(function(t){var i=IDBKeyRange.bound([r.userId,t,n],[r.userId,t,n+1],!1,!0);a.push(ba(e).Y("collectionPathOverlayIndex",i))}),Le.waitFor(a)}},{key:"getOverlaysForCollection",value:function(e,t,n){var r=this,i=_r(),a=Si(t),u=IDBKeyRange.bound([this.userId,a,n],[this.userId,a,Number.POSITIVE_INFINITY],!0);return ba(e).W("collectionPathOverlayIndex",u).next(function(e){var t,n=v(e);try{for(n.s();!(t=n.n()).done;){var a=t.value,u=ya(r.yt,a);i.set(u.getKey(),u)}}catch(o){n.e(o)}finally{n.f()}return i})}},{key:"getOverlaysForCollectionGroup",value:function(e,t,n,r){var i,a=this,u=_r(),o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return ba(e).Z({index:"collectionGroupOverlayIndex",range:o},function(e,t,n){var o=ya(a.yt,t);u.size()<r||o.largestBatchId===i?(u.set(o.getKey(),o),i=o.largestBatchId):n.done()}).next(function(){return u})}},{key:"oe",value:function(e,t){return ba(e).put(function(e,t,n){var r=l(pa(t,n.mutation.key),3);r[0];return{userId:t,collectionPath:r[1],documentId:r[2],collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:li(e.ie,n.mutation)}}(this.yt,this.userId,t))}}],[{key:"re",value:function(t,n){return new e(t,n.uid||"")}}]),e}();function ba(e){return ea(e,"documentOverlays")}var Ia=function(){function e(){C(this,e)}return P(e,[{key:"ue",value:function(e,t){this.ce(e,t),t.ae()}},{key:"ce",value:function(e,t){if("nullValue"in e)this.he(t,5);else if("booleanValue"in e)this.he(t,10),t.le(e.booleanValue?1:0);else if("integerValue"in e)this.he(t,15),t.le(it(e.integerValue));else if("doubleValue"in e){var n=it(e.doubleValue);isNaN(n)?this.he(t,13):(this.he(t,15),Je(n)?t.le(0):t.le(n))}else if("timestampValue"in e){var r=e.timestampValue;this.he(t,20),"string"==typeof r?t.fe(r):(t.fe("".concat(r.seconds||"")),t.le(r.nanos||0))}else if("stringValue"in e)this.de(e.stringValue,t),this._e(t);else if("bytesValue"in e)this.he(t,30),t.we(at(e.bytesValue)),this._e(t);else if("referenceValue"in e)this.me(e.referenceValue,t);else if("geoPointValue"in e){var i=e.geoPointValue;this.he(t,45),t.le(i.latitude||0),t.le(i.longitude||0)}else"mapValue"in e?Tt(e)?this.he(t,Number.MAX_SAFE_INTEGER):(this.ge(e.mapValue,t),this._e(t)):"arrayValue"in e?(this.ye(e.arrayValue,t),this._e(t)):j()}},{key:"de",value:function(e,t){this.he(t,25),this.pe(e,t)}},{key:"pe",value:function(e,t){t.fe(e)}},{key:"ge",value:function(e,t){var n=e.fields||{};this.he(t,55);for(var r=0,i=Object.keys(n);r<i.length;r++){var a=i[r];this.de(a,t),this.ce(n[a],t)}}},{key:"ye",value:function(e,t){var n=e.values||[];this.he(t,50);var r,i=v(n);try{for(i.s();!(r=i.n()).done;){var a=r.value;this.ce(a,t)}}catch(u){i.e(u)}finally{i.f()}}},{key:"me",value:function(e,t){var n=this;this.he(t,37),ge.fromName(e).path.forEach(function(e){n.he(t,60),n.pe(e,t)})}},{key:"he",value:function(e,t){e.le(t)}},{key:"_e",value:function(e){e.le(2)}}]),e}();function Ea(e){if(0===e)return 8;var t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}function Ta(e){var t=64-function(e){for(var t=0,n=0;n<8;++n){var r=Ea(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}Ia.Ie=new Ia;var Sa=function(){function e(){C(this,e),this.buffer=new Uint8Array(1024),this.position=0}return P(e,[{key:"Te",value:function(e){for(var t=e[Symbol.iterator](),n=t.next();!n.done;)this.Ee(n.value),n=t.next();this.Ae()}},{key:"Re",value:function(e){for(var t=e[Symbol.iterator](),n=t.next();!n.done;)this.be(n.value),n=t.next();this.Pe()}},{key:"ve",value:function(e){var t,n=v(e);try{for(n.s();!(t=n.n()).done;){var r=t.value,i=r.charCodeAt(0);if(i<128)this.Ee(i);else if(i<2048)this.Ee(960|i>>>6),this.Ee(128|63&i);else if(r<"\ud800"||"\udbff"<r)this.Ee(480|i>>>12),this.Ee(128|63&i>>>6),this.Ee(128|63&i);else{var a=r.codePointAt(0);this.Ee(240|a>>>18),this.Ee(128|63&a>>>12),this.Ee(128|63&a>>>6),this.Ee(128|63&a)}}}catch(u){n.e(u)}finally{n.f()}this.Ae()}},{key:"Ve",value:function(e){var t,n=v(e);try{for(n.s();!(t=n.n()).done;){var r=t.value,i=r.charCodeAt(0);if(i<128)this.be(i);else if(i<2048)this.be(960|i>>>6),this.be(128|63&i);else if(r<"\ud800"||"\udbff"<r)this.be(480|i>>>12),this.be(128|63&i>>>6),this.be(128|63&i);else{var a=r.codePointAt(0);this.be(240|a>>>18),this.be(128|63&a>>>12),this.be(128|63&a>>>6),this.be(128|63&a)}}}catch(u){n.e(u)}finally{n.f()}this.Pe()}},{key:"Se",value:function(e){var t=this.De(e),n=Ta(t);this.Ce(1+n),this.buffer[this.position++]=255&n;for(var r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}},{key:"xe",value:function(e){var t=this.De(e),n=Ta(t);this.Ce(1+n),this.buffer[this.position++]=~(255&n);for(var r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}},{key:"Ne",value:function(){this.ke(255),this.ke(255)}},{key:"Oe",value:function(){this.Me(255),this.Me(255)}},{key:"reset",value:function(){this.position=0}},{key:"seed",value:function(e){this.Ce(e.length),this.buffer.set(e,this.position),this.position+=e.length}},{key:"Fe",value:function(){return this.buffer.slice(0,this.position)}},{key:"De",value:function(e){var t=function(e){var t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(var r=1;r<t.length;++r)t[r]^=n?255:0;return t}},{key:"Ee",value:function(e){var t=255&e;0===t?(this.ke(0),this.ke(255)):255===t?(this.ke(255),this.ke(0)):this.ke(t)}},{key:"be",value:function(e){var t=255&e;0===t?(this.Me(0),this.Me(255)):255===t?(this.Me(255),this.Me(0)):this.Me(e)}},{key:"Ae",value:function(){this.ke(0),this.ke(1)}},{key:"Pe",value:function(){this.Me(0),this.Me(1)}},{key:"ke",value:function(e){this.Ce(1),this.buffer[this.position++]=e}},{key:"Me",value:function(e){this.Ce(1),this.buffer[this.position++]=~e}},{key:"Ce",value:function(e){var t=e+this.position;if(!(t<=this.buffer.length)){var n=2*this.buffer.length;n<t&&(n=t);var r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}}]),e}(),_a=function(){function e(t){C(this,e),this.$e=t}return P(e,[{key:"we",value:function(e){this.$e.Te(e)}},{key:"fe",value:function(e){this.$e.ve(e)}},{key:"le",value:function(e){this.$e.Se(e)}},{key:"ae",value:function(){this.$e.Ne()}}]),e}(),Da=function(){function e(t){C(this,e),this.$e=t}return P(e,[{key:"we",value:function(e){this.$e.Re(e)}},{key:"fe",value:function(e){this.$e.Ve(e)}},{key:"le",value:function(e){this.$e.xe(e)}},{key:"ae",value:function(){this.$e.Oe()}}]),e}(),Aa=function(){function e(){C(this,e),this.$e=new Sa,this.Be=new _a(this.$e),this.Le=new Da(this.$e)}return P(e,[{key:"seed",value:function(e){this.$e.seed(e)}},{key:"qe",value:function(e){return 0===e?this.Be:this.Le}},{key:"Fe",value:function(){return this.$e.Fe()}},{key:"reset",value:function(){this.$e.reset()}}]),e}(),Ca=function(){function e(t,n,r,i){C(this,e),this.indexId=t,this.documentKey=n,this.arrayValue=r,this.directionalValue=i}return P(e,[{key:"Ue",value:function(){var t=this.directionalValue.length,n=0===t||255===this.directionalValue[t-1]?t+1:t,r=new Uint8Array(n);return r.set(this.directionalValue,0),n!==t?r.set([0],this.directionalValue.length):++r[r.length-1],new e(this.indexId,this.documentKey,this.arrayValue,r)}}]),e}();function Na(e,t){var n=e.indexId-t.indexId;return 0!==n?n:0!==(n=Pa(e.arrayValue,t.arrayValue))?n:0!==(n=Pa(e.directionalValue,t.directionalValue))?n:ge.comparator(e.documentKey,t.documentKey)}function Pa(e,t){for(var n=0;n<e.length&&n<t.length;++n){var r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}var La=function(){function e(t){C(this,e),this.collectionId=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment(),this.Ke=t.orderBy,this.Ge=[];var n,r=v(t.filters);try{for(r.s();!(n=r.n()).done;){var i=n.value;i.isInequality()?this.Qe=i:this.Ge.push(i)}}catch(a){r.e(a)}finally{r.f()}}return P(e,[{key:"je",value:function(e){z(e.collectionGroup===this.collectionId);var t=we(e);if(void 0!==t&&!this.We(t))return!1;for(var n=xe(e),r=0,i=0;r<n.length&&this.We(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Qe){var a=n[r];if(!this.ze(this.Qe,a)||!this.He(this.Ke[i++],a))return!1;++r}for(;r<n.length;++r){var u=n[r];if(i>=this.Ke.length||!this.He(this.Ke[i++],u))return!1}return!0}},{key:"We",value:function(e){var t,n=v(this.Ge);try{for(n.s();!(t=n.n()).done;){var r=t.value;if(this.ze(r,e))return!0}}catch(i){n.e(i)}finally{n.f()}return!1}},{key:"ze",value:function(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}},{key:"He",value:function(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}]),e}();function Fa(e){var t,n;if(z(e instanceof Ft||e instanceof Mt),e instanceof Ft){if(e instanceof Yt){var r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map(function(t){return Ft.create(e.field,"==",t)}))||[];return Mt.create(r,"or")}return e}var i=e.filters.map(function(e){return Fa(e)});return Mt.create(i,e.op)}function Ma(e){if(0===e.getFilters().length)return[];var t=qa(Fa(e));return z(Oa(t)),Ra(t)||Va(t)?[t]:t.getFilters()}function Ra(e){return e instanceof Ft}function Va(e){return e instanceof Mt&&Ot(e)}function Oa(e){return Ra(e)||Va(e)||function(e){if(e instanceof Mt&&Vt(e)){var t,n=v(e.getFilters());try{for(n.s();!(t=n.n()).done;){var r=t.value;if(!Ra(r)&&!Va(r))return!1}}catch(i){n.e(i)}finally{n.f()}return!0}return!1}(e)}function qa(e){if(z(e instanceof Ft||e instanceof Mt),e instanceof Ft)return e;if(1===e.filters.length)return qa(e.filters[0]);var t=e.filters.map(function(e){return qa(e)}),n=Mt.create(t,e.op);return Oa(n=Ga(n))?n:(z(n instanceof Mt),z(Rt(n)),z(n.filters.length>1),n.filters.reduce(function(e,t){return Ua(e,t)}))}function Ua(e,t){return z(e instanceof Ft||e instanceof Mt),z(t instanceof Ft||t instanceof Mt),Ga(e instanceof Ft?t instanceof Ft?function(e,t){return Mt.create([e,t],"and")}(e,t):Ba(e,t):t instanceof Ft?Ba(t,e):function(e,t){if(z(e.filters.length>0&&t.filters.length>0),Rt(e)&&Rt(t))return Gt(e,t.getFilters());var n=Vt(e)?e:t,r=Vt(e)?t:e,i=n.filters.map(function(e){return Ua(e,r)});return Mt.create(i,"or")}(e,t))}function Ba(e,t){if(Rt(t))return Gt(t,e.getFilters());var n=t.filters.map(function(t){return Ua(e,t)});return Mt.create(n,"or")}function Ga(e){if(z(e instanceof Ft||e instanceof Mt),e instanceof Ft)return e;var t=e.getFilters();if(1===t.length)return Ga(t[0]);if(qt(e))return e;var n=t.map(function(e){return Ga(e)}),r=[];return n.forEach(function(t){t instanceof Ft?r.push(t):t instanceof Mt&&(t.op===e.op?r.push.apply(r,I(t.filters)):r.push(t))}),1===r.length?r[0]:Mt.create(r,e.op)}var Ka=function(){function e(){C(this,e),this.Je=new Qa}return P(e,[{key:"addToCollectionParentIndex",value:function(e,t){return this.Je.add(t),Le.resolve()}},{key:"getCollectionParents",value:function(e,t){return Le.resolve(this.Je.getEntries(t))}},{key:"addFieldIndex",value:function(e,t){return Le.resolve()}},{key:"deleteFieldIndex",value:function(e,t){return Le.resolve()}},{key:"getDocumentsMatchingTarget",value:function(e,t){return Le.resolve(null)}},{key:"getIndexType",value:function(e,t){return Le.resolve(0)}},{key:"getFieldIndexes",value:function(e,t){return Le.resolve([])}},{key:"getNextCollectionGroupToUpdate",value:function(e){return Le.resolve(null)}},{key:"getMinOffset",value:function(e,t){return Le.resolve(De.min())}},{key:"getMinOffsetFromCollectionGroup",value:function(e,t){return Le.resolve(De.min())}},{key:"updateCollectionGroup",value:function(e,t,n){return Le.resolve()}},{key:"updateIndexEntries",value:function(e,t){return Le.resolve()}}]),e}(),Qa=function(){function e(){C(this,e),this.index={}}return P(e,[{key:"add",value:function(e){var t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new rn(ye.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}},{key:"has",value:function(e){var t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}},{key:"getEntries",value:function(e){return(this.index[e]||new rn(ye.comparator)).toArray()}}]),e}(),ja=new Uint8Array(0),za=function(){function e(t,n){C(this,e),this.user=t,this.databaseId=n,this.Ye=new Qa,this.Xe=new xr(function(e){return dn(e)},function(e,t){return vn(e,t)}),this.uid=t.uid||""}return P(e,[{key:"addToCollectionParentIndex",value:function(e,t){var n=this;if(!this.Ye.has(t)){var r=t.lastSegment(),i=t.popLast();e.addOnCommittedListener(function(){n.Ye.add(t)});var a={collectionId:r,parent:Si(i)};return Wa(e).put(a)}return Le.resolve()}},{key:"getCollectionParents",value:function(e,t){var n=[],r=IDBKeyRange.bound([t,""],[fe(t),""],!1,!0);return Wa(e).W(r).next(function(e){var r,i=v(e);try{for(i.s();!(r=i.n()).done;){var a=r.value;if(a.collectionId!==t)break;n.push(Ai(a.parent))}}catch(u){i.e(u)}finally{i.f()}return n})}},{key:"addFieldIndex",value:function(e,t){var n=this,r=Ya(e),i=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map(function(e){return[e.fieldPath.canonicalString(),e.kind]})}}(t);delete i.indexId;var a=r.add(i);if(t.indexState){var u=Xa(e);return a.next(function(e){u.put(ma(e,n.user,t.indexState.sequenceNumber,t.indexState.offset))})}return a.next()}},{key:"deleteFieldIndex",value:function(e,t){var n=Ya(e),r=Xa(e),i=Ha(e);return n.delete(t.indexId).next(function(){return r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))}).next(function(){return i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))})}},{key:"getDocumentsMatchingTarget",value:function(e,t){var n=this,r=Ha(e),i=!0,a=new Map;return Le.forEach(this.Ze(t),function(t){return n.tn(e,t).next(function(e){i&&(i=!!e),a.set(t,e)})}).next(function(){if(i){var e=Pr(),u=[];return Le.forEach(a,function(i,a){var o;B("IndexedDbIndexManager","Using index ".concat((o=i,"id=".concat(o.indexId,"|cg=").concat(o.collectionGroup,"|f=").concat(o.fields.map(function(e){return"".concat(e.fieldPath,":").concat(e.kind)}).join(",")))," to execute ").concat(dn(t)));var s=function(e,t){var n=we(i);if(void 0===n)return null;var r,a=v(pn(e,n.fieldPath));try{for(a.s();!(r=a.n()).done;){var u=r.value;switch(u.op){case"array-contains-any":return u.value.arrayValue.values||[];case"array-contains":return[u.value]}}}catch(o){a.e(o)}finally{a.f()}return null}(a),c=function(e,t){var n,r=new Map,i=v(xe(t));try{for(i.s();!(n=i.n()).done;){var a,u=n.value,o=v(pn(e,u.fieldPath));try{for(o.s();!(a=o.n()).done;){var s=a.value;switch(s.op){case"==":case"in":r.set(u.fieldPath.canonicalString(),s.value);break;case"not-in":case"!=":return r.set(u.fieldPath.canonicalString(),s.value),Array.from(r.values())}}}catch(c){o.e(c)}finally{o.f()}}}catch(c){i.e(c)}finally{i.f()}return null}(a,i),l=function(e,t){var n,r=[],a=!0,u=v(xe(i));try{for(u.s();!(n=u.n()).done;){var o=n.value,s=0===o.kind?mn(e,o.fieldPath,e.startAt):gn(e,o.fieldPath,e.startAt);r.push(s.value),a&&(a=s.inclusive)}}catch(c){u.e(c)}finally{u.f()}return new Ct(r,a)}(a),f=function(e,t){var n,r=[],a=!0,u=v(xe(i));try{for(u.s();!(n=u.n()).done;){var o=n.value,s=0===o.kind?gn(e,o.fieldPath,e.endAt):mn(e,o.fieldPath,e.endAt);r.push(s.value),a&&(a=s.inclusive)}}catch(c){u.e(c)}finally{u.f()}return new Ct(r,a)}(a),h=n.en(i,a,l),d=n.en(i,a,f),y=n.nn(i,a,c),p=n.sn(i.indexId,s,h,l.inclusive,d,f.inclusive,y);return Le.forEach(p,function(n){return r.J(n,t.limit).next(function(t){t.forEach(function(t){var n=ge.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),u.push(n))})})})}).next(function(){return u})}return Le.resolve(null)})}},{key:"Ze",value:function(e){var t=this.Xe.get(e);return t||(t=0===e.filters.length?[e]:Ma(Mt.create(e.filters,"and")).map(function(t){return hn(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)}),this.Xe.set(e,t),t)}},{key:"sn",value:function(e,t,n,r,i,a,u){for(var o=this,s=(null!=t?t.length:1)*Math.max(n.length,i.length),c=s/(null!=t?t.length:1),l=[],f=function(){var s=t?o.rn(t[h/c]):ja,f=o.on(e,s,n[h%c],r),d=o.un(e,s,i[h%c],a),v=u.map(function(t){return o.on(e,s,t,!0)});l.push.apply(l,I(o.createRange(f,d,v)))},h=0;h<s;++h)f();return l}},{key:"on",value:function(e,t,n,r){var i=new Ca(e,ge.empty(),t,n);return r?i:i.Ue()}},{key:"un",value:function(e,t,n,r){var i=new Ca(e,ge.empty(),t,n);return r?i.Ue():i}},{key:"tn",value:function(e,t){var n=new La(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(function(e){var t,r=null,i=v(e);try{for(i.s();!(t=i.n()).done;){var a=t.value;n.je(a)&&(!r||a.fields.length>r.fields.length)&&(r=a)}}catch(u){i.e(u)}finally{i.f()}return r})}},{key:"getIndexType",value:function(e,t){var n=this,r=2,i=this.Ze(t);return Le.forEach(i,function(t){return n.tn(e,t).next(function(e){e?0!==r&&e.fields.length<function(e){var t,n=new rn(me.comparator),r=!1,i=v(e.filters);try{for(i.s();!(t=i.n()).done;){var a,u=v(t.value.getFlattenedFilters());try{for(u.s();!(a=u.n()).done;){var o=a.value;o.field.isKeyField()||("array-contains"===o.op||"array-contains-any"===o.op?r=!0:n=n.add(o.field))}}catch(f){u.e(f)}finally{u.f()}}}catch(f){i.e(f)}finally{i.f()}var s,c=v(e.orderBy);try{for(c.s();!(s=c.n()).done;){var l=s.value;l.field.isKeyField()||(n=n.add(l.field))}}catch(f){c.e(f)}finally{c.f()}return n.size+(r?1:0)}(t)&&(r=1):r=0})}).next(function(){return null!==t.limit&&i.length>1&&2===r?1:r})}},{key:"cn",value:function(e,t){var n,r=new Aa,i=v(xe(e));try{for(i.s();!(n=i.n()).done;){var a=n.value,u=t.data.field(a.fieldPath);if(null==u)return null;var o=r.qe(a.kind);Ia.Ie.ue(u,o)}}catch(s){i.e(s)}finally{i.f()}return r.Fe()}},{key:"rn",value:function(e){var t=new Aa;return Ia.Ie.ue(e,t.qe(0)),t.Fe()}},{key:"an",value:function(e,t){var n=new Aa;return Ia.Ie.ue(gt(this.databaseId,t),n.qe(function(e){var t=xe(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Fe()}},{key:"nn",value:function(e,t,n){if(null===n)return[];var r=[];r.push(new Aa);var i,a=0,u=v(xe(e));try{for(u.s();!(i=u.n()).done;){var o,s=i.value,c=n[a++],l=v(r);try{for(l.s();!(o=l.n()).done;){var f=o.value;if(this.hn(t,s.fieldPath)&&wt(c))r=this.ln(r,s,c);else{var h=f.qe(s.kind);Ia.Ie.ue(c,h)}}}catch(d){l.e(d)}finally{l.f()}}}catch(d){u.e(d)}finally{u.f()}return this.fn(r)}},{key:"en",value:function(e,t,n){return this.nn(e,t,n.position)}},{key:"fn",value:function(e){for(var t=[],n=0;n<e.length;++n)t[n]=e[n].Fe();return t}},{key:"ln",value:function(e,t,n){var r,i=I(e),a=[],u=v(n.arrayValue.values||[]);try{for(u.s();!(r=u.n()).done;){var o,s=r.value,c=v(i);try{for(c.s();!(o=c.n()).done;){var l=o.value,f=new Aa;f.seed(l.Fe()),Ia.Ie.ue(s,f.qe(t.kind)),a.push(f)}}catch(h){c.e(h)}finally{c.f()}}}catch(h){u.e(h)}finally{u.f()}return a}},{key:"hn",value:function(e,t){return!!e.filters.find(function(e){return e instanceof Ft&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op)})}},{key:"getFieldIndexes",value:function(e,t){var n=this,r=Ya(e),i=Xa(e);return(t?r.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):r.W()).next(function(e){var t=[];return Le.forEach(e,function(e){return i.get([e.indexId,n.uid]).next(function(n){t.push(function(e,t){var n=t?new Te(t.sequenceNumber,new De(la(t.readTime),new ge(Ai(t.documentKey)),t.largestBatchId)):Te.empty(),r=e.fields.map(function(e){var t=l(e,2),n=t[0],r=t[1];return new Ie(me.fromServerFormat(n),r)});return new ke(e.indexId,e.collectionGroup,r,n)}(e,n))})}).next(function(){return t})})}},{key:"getNextCollectionGroupToUpdate",value:function(e){return this.getFieldIndexes(e).next(function(e){return 0===e.length?null:(e.sort(function(e,t){var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:ce(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup)})}},{key:"updateCollectionGroup",value:function(e,t,n){var r=this,i=Ya(e),a=Xa(e);return this.dn(e).next(function(e){return i.W("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(function(t){return Le.forEach(t,function(t){return a.put(ma(t.indexId,r.user,e,n))})})})}},{key:"updateIndexEntries",value:function(e,t){var n=this,r=new Map;return Le.forEach(t,function(t,i){var a=r.get(t.collectionGroup);return(a?Le.resolve(a):n.getFieldIndexes(e,t.collectionGroup)).next(function(a){return r.set(t.collectionGroup,a),Le.forEach(a,function(r){return n._n(e,t,r).next(function(t){var a=n.wn(i,r);return t.isEqual(a)?Le.resolve():n.mn(e,i,r,t,a)})})})})}},{key:"gn",value:function(e,t,n,r){return Ha(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.an(n,t.key),documentKey:t.key.path.toArray()})}},{key:"yn",value:function(e,t,n,r){return Ha(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.an(n,t.key),t.key.path.toArray()])}},{key:"_n",value:function(e,t,n){var r=Ha(e),i=new rn(Na);return r.Z({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.an(n,t)])},function(e,r){i=i.add(new Ca(n.indexId,t,r.arrayValue,r.directionalValue))}).next(function(){return i})}},{key:"wn",value:function(e,t){var n=new rn(Na),r=this.cn(t,e);if(null==r)return n;var i=we(t);if(null!=i){var a=e.data.field(i.fieldPath);if(wt(a)){var u,o=v(a.arrayValue.values||[]);try{for(o.s();!(u=o.n()).done;){var s=u.value;n=n.add(new Ca(t.indexId,e.key,this.rn(s),r))}}catch(c){o.e(c)}finally{o.f()}}}else n=n.add(new Ca(t.indexId,e.key,ja,r));return n}},{key:"mn",value:function(e,t,n,r,i){var a=this;B("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);var u=[];return function(e,t,n,r,i){for(var a=e.getIterator(),u=t.getIterator(),o=un(a),s=un(u);o||s;){var c=!1,l=!1;if(o&&s){var f=n(o,s);f<0?l=!0:f>0&&(c=!0)}else null!=o?l=!0:c=!0;c?(r(s),s=un(u)):l?(i(o),o=un(a)):(o=un(a),s=un(u))}}(r,i,Na,function(r){u.push(a.gn(e,t,n,r))},function(r){u.push(a.yn(e,t,n,r))}),Le.waitFor(u)}},{key:"dn",value:function(e){var t=1;return Xa(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},function(e,n,r){r.done(),t=n.sequenceNumber+1}).next(function(){return t})}},{key:"createRange",value:function(e,t,n){n=n.sort(function(e,t){return Na(e,t)}).filter(function(e,t,n){return!t||0!==Na(e,n[t-1])});var r=[];r.push(e);var i,a=v(n);try{for(a.s();!(i=a.n()).done;){var u=i.value,o=Na(u,e),s=Na(u,t);if(0===o)r[0]=e.Ue();else if(o>0&&s<0)r.push(u),r.push(u.Ue());else if(s>0)break}}catch(d){a.e(d)}finally{a.f()}r.push(t);for(var c=[],l=0;l<r.length;l+=2){if(this.pn(r[l],r[l+1]))return[];var f=[r[l].indexId,this.uid,r[l].arrayValue,r[l].directionalValue,ja,[]],h=[r[l+1].indexId,this.uid,r[l+1].arrayValue,r[l+1].directionalValue,ja,[]];c.push(IDBKeyRange.bound(f,h))}return c}},{key:"pn",value:function(e,t){return Na(e,t)>0}},{key:"getMinOffsetFromCollectionGroup",value:function(e,t){return this.getFieldIndexes(e,t).next(Za)}},{key:"getMinOffset",value:function(e,t){var n=this;return Le.mapArray(this.Ze(t),function(t){return n.tn(e,t).next(function(e){return e||j()})}).next(Za)}}]),e}();function Wa(e){return ea(e,"collectionParents")}function Ha(e){return ea(e,"indexEntries")}function Ya(e){return ea(e,"indexConfiguration")}function Xa(e){return ea(e,"indexState")}function Za(e){z(0!==e.length);for(var t=e[0].indexState.offset,n=t.largestBatchId,r=1;r<e.length;r++){var i=e[r].indexState.offset;Ae(i,t)<0&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new De(t.readTime,t.documentKey,n)}var Ja={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},$a=function(){function e(t,n,r){C(this,e),this.cacheSizeCollectionThreshold=t,this.percentileToCollect=n,this.maximumSequenceNumbersToCollect=r}return P(e,null,[{key:"withCacheSize",value:function(t){return new e(t,e.DEFAULT_COLLECTION_PERCENTILE,e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}]),e}();function eu(e,t,n){var r=e.store("mutations"),i=e.store("documentMutations"),a=[],u=IDBKeyRange.only(n.batchId),o=0,s=r.Z({range:u},function(e,t,n){return o++,n.delete()});a.push(s.next(function(){z(1===o)}));var c,l=[],f=v(n.mutations);try{for(f.s();!(c=f.n()).done;){var h=c.value,d=Pi(t,h.key.path,n.batchId);a.push(i.delete(d)),l.push(h.key)}}catch(y){f.e(y)}finally{f.f()}return Le.waitFor(a).next(function(){return l})}function tu(e){if(!e)return 0;var t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw j();t=e.noDocument}return JSON.stringify(t).length}$a.DEFAULT_COLLECTION_PERCENTILE=10,$a.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,$a.DEFAULT=new $a(41943040,$a.DEFAULT_COLLECTION_PERCENTILE,$a.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),$a.DISABLED=new $a(-1,0,0);var nu=function(){function e(t,n,r,i){C(this,e),this.userId=t,this.yt=n,this.indexManager=r,this.referenceDelegate=i,this.In={}}return P(e,[{key:"checkEmpty",value:function(e){var t=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return iu(e).Z({index:"userMutationsIndex",range:n},function(e,n,r){t=!1,r.done()}).next(function(){return t})}},{key:"addMutationBatch",value:function(e,t,n,r){var i=this,a=au(e),u=iu(e);return u.add({}).next(function(o){z("number"==typeof o);var s,c=new ta(o,t,n,r),l=function(e,t,n){var r=n.baseMutations.map(function(t){return li(e.ie,t)}),i=n.mutations.map(function(t){return li(e.ie,t)});return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(i.yt,i.userId,c),f=[],h=new rn(function(e,t){return ce(e.canonicalString(),t.canonicalString())}),d=v(r);try{for(d.s();!(s=d.n()).done;){var y=s.value,p=Pi(i.userId,y.key.path,o);h=h.add(y.key.path.popLast()),f.push(u.put(l)),f.push(a.put(p,Li))}}catch(m){d.e(m)}finally{d.f()}return h.forEach(function(t){f.push(i.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(function(){i.In[o]=c.keys()}),Le.waitFor(f).next(function(){return c})})}},{key:"lookupMutationBatch",value:function(e,t){var n=this;return iu(e).get(t).next(function(e){return e?(z(e.userId===n.userId),fa(n.yt,e)):null})}},{key:"Tn",value:function(e,t){var n=this;return this.In[t]?Le.resolve(this.In[t]):this.lookupMutationBatch(e,t).next(function(e){if(e){var r=e.keys();return n.In[t]=r,r}return null})}},{key:"getNextMutationBatchAfterBatchId",value:function(e,t){var n=this,r=t+1,i=IDBKeyRange.lowerBound([this.userId,r]),a=null;return iu(e).Z({index:"userMutationsIndex",range:i},function(e,t,i){t.userId===n.userId&&(z(t.batchId>=r),a=fa(n.yt,t)),i.done()}).next(function(){return a})}},{key:"getHighestUnacknowledgedBatchId",value:function(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=-1;return iu(e).Z({index:"userMutationsIndex",range:t,reverse:!0},function(e,t,r){n=t.batchId,r.done()}).next(function(){return n})}},{key:"getAllMutationBatches",value:function(e){var t=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return iu(e).W("userMutationsIndex",n).next(function(e){return e.map(function(e){return fa(t.yt,e)})})}},{key:"getAllMutationBatchesAffectingDocumentKey",value:function(e,t){var n=this,r=Ni(this.userId,t.path),i=IDBKeyRange.lowerBound(r),a=[];return au(e).Z({range:i},function(r,i,u){var o=l(r,3),s=o[0],c=o[1],f=o[2],h=Ai(c);if(s===n.userId&&t.path.isEqual(h))return iu(e).get(f).next(function(e){if(!e)throw j();z(e.userId===n.userId),a.push(fa(n.yt,e))});u.done()}).next(function(){return a})}},{key:"getAllMutationBatchesAffectingDocumentKeys",value:function(e,t){var n=this,r=new rn(ce),i=[];return t.forEach(function(t){var a=Ni(n.userId,t.path),u=IDBKeyRange.lowerBound(a),o=au(e).Z({range:u},function(e,i,a){var u=l(e,3),o=u[0],s=u[1],c=u[2],f=Ai(s);o===n.userId&&t.path.isEqual(f)?r=r.add(c):a.done()});i.push(o)}),Le.waitFor(i).next(function(){return n.En(e,r)})}},{key:"getAllMutationBatchesAffectingQuery",value:function(e,t){var n=this,r=t.path,i=r.length+1,a=Ni(this.userId,r),u=IDBKeyRange.lowerBound(a),o=new rn(ce);return au(e).Z({range:u},function(e,t,a){var u=l(e,3),s=u[0],c=u[1],f=u[2],h=Ai(c);s===n.userId&&r.isPrefixOf(h)?h.length===i&&(o=o.add(f)):a.done()}).next(function(){return n.En(e,o)})}},{key:"En",value:function(e,t){var n=this,r=[],i=[];return t.forEach(function(t){i.push(iu(e).get(t).next(function(e){if(null===e)throw j();z(e.userId===n.userId),r.push(fa(n.yt,e))}))}),Le.waitFor(i).next(function(){return r})}},{key:"removeMutationBatch",value:function(e,t){var n=this;return eu(e.se,this.userId,t).next(function(r){return e.addOnCommittedListener(function(){n.An(t.batchId)}),Le.forEach(r,function(t){return n.referenceDelegate.markPotentiallyOrphaned(e,t)})})}},{key:"An",value:function(e){delete this.In[e]}},{key:"performConsistencyCheck",value:function(e){var t=this;return this.checkEmpty(e).next(function(n){if(!n)return Le.resolve();var r=IDBKeyRange.lowerBound([t.userId]),i=[];return au(e).Z({range:r},function(e,n,r){if(e[0]===t.userId){var a=Ai(e[1]);i.push(a)}else r.done()}).next(function(){z(0===i.length)})})}},{key:"containsKey",value:function(e,t){return ru(e,this.userId,t)}},{key:"Rn",value:function(e){var t=this;return uu(e).get(this.userId).next(function(e){return e||{userId:t.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}})}}],[{key:"re",value:function(t,n,r,i){return z(""!==t.uid),new e(t.isAuthenticated()?t.uid:"",n,r,i)}}]),e}();function ru(e,t,n){var r=Ni(t,n.path),i=r[1],a=IDBKeyRange.lowerBound(r),u=!1;return au(e).Z({range:a,X:!0},function(e,n,r){var a=l(e,3),o=a[0],s=a[1];a[2];o===t&&s===i&&(u=!0),r.done()}).next(function(){return u})}function iu(e){return ea(e,"mutations")}function au(e){return ea(e,"documentMutations")}function uu(e){return ea(e,"mutationQueues")}var ou=function(){function e(t){C(this,e),this.bn=t}return P(e,[{key:"next",value:function(){return this.bn+=2,this.bn}}],[{key:"Pn",value:function(){return new e(0)}},{key:"vn",value:function(){return new e(-1)}}]),e}(),su=function(){function e(t,n){C(this,e),this.referenceDelegate=t,this.yt=n}return P(e,[{key:"allocateTargetId",value:function(e){var t=this;return this.Vn(e).next(function(n){var r=new ou(n.highestTargetId);return n.highestTargetId=r.next(),t.Sn(e,n).next(function(){return n.highestTargetId})})}},{key:"getLastRemoteSnapshotVersion",value:function(e){return this.Vn(e).next(function(e){return de.fromTimestamp(new he(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))})}},{key:"getHighestSequenceNumber",value:function(e){return this.Vn(e).next(function(e){return e.highestListenSequenceNumber})}},{key:"setTargetsMetadata",value:function(e,t,n){var r=this;return this.Vn(e).next(function(i){return i.highestListenSequenceNumber=t,n&&(i.lastRemoteSnapshotVersion=n.toTimestamp()),t>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=t),r.Sn(e,i)})}},{key:"addTargetData",value:function(e,t){var n=this;return this.Dn(e,t).next(function(){return n.Vn(e).next(function(r){return r.targetCount+=1,n.Cn(t,r),n.Sn(e,r)})})}},{key:"updateTargetData",value:function(e,t){return this.Dn(e,t)}},{key:"removeTargetData",value:function(e,t){var n=this;return this.removeMatchingKeysForTargetId(e,t.targetId).next(function(){return cu(e).delete(t.targetId)}).next(function(){return n.Vn(e)}).next(function(t){return z(t.targetCount>0),t.targetCount-=1,n.Sn(e,t)})}},{key:"removeTargets",value:function(e,t,n){var r=this,i=0,a=[];return cu(e).Z(function(u,o){var s=ha(o);s.sequenceNumber<=t&&null===n.get(s.targetId)&&(i++,a.push(r.removeTargetData(e,s)))}).next(function(){return Le.waitFor(a)}).next(function(){return i})}},{key:"forEachTarget",value:function(e,t){return cu(e).Z(function(e,n){var r=ha(n);t(r)})}},{key:"Vn",value:function(e){return lu(e).get("targetGlobalKey").next(function(e){return z(null!==e),e})}},{key:"Sn",value:function(e,t){return lu(e).put("targetGlobalKey",t)}},{key:"Dn",value:function(e,t){return cu(e).put(da(this.yt,t))}},{key:"Cn",value:function(e,t){var n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}},{key:"getTargetCount",value:function(e){return this.Vn(e).next(function(e){return e.targetCount})}},{key:"getTargetData",value:function(e,t){var n=dn(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]),i=null;return cu(e).Z({range:r,index:"queryTargetsIndex"},function(e,n,r){var a=ha(n);vn(t,a.target)&&(i=a,r.done())}).next(function(){return i})}},{key:"addMatchingKeys",value:function(e,t,n){var r=this,i=[],a=fu(e);return t.forEach(function(t){var u=Si(t.path);i.push(a.put({targetId:n,path:u})),i.push(r.referenceDelegate.addReference(e,n,t))}),Le.waitFor(i)}},{key:"removeMatchingKeys",value:function(e,t,n){var r=this,i=fu(e);return Le.forEach(t,function(t){var a=Si(t.path);return Le.waitFor([i.delete([n,a]),r.referenceDelegate.removeReference(e,n,t)])})}},{key:"removeMatchingKeysForTargetId",value:function(e,t){var n=fu(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}},{key:"getMatchingKeysForTargetId",value:function(e,t){var n=IDBKeyRange.bound([t],[t+1],!1,!0),r=fu(e),i=Pr();return r.Z({range:n,X:!0},function(e,t,n){var r=Ai(e[1]),a=new ge(r);i=i.add(a)}).next(function(){return i})}},{key:"containsKey",value:function(e,t){var n=Si(t.path),r=IDBKeyRange.bound([n],[fe(n)],!1,!0),i=0;return fu(e).Z({index:"documentTargetsIndex",X:!0,range:r},function(e,t,n){var r=l(e,2),a=r[0];r[1];0!==a&&(i++,n.done())}).next(function(){return i>0})}},{key:"ne",value:function(e,t){return cu(e).get(t).next(function(e){return e?ha(e):null})}}]),e}();function cu(e){return ea(e,"targets")}function lu(e){return ea(e,"targetGlobal")}function fu(e){return ea(e,"targetDocuments")}function hu(e,t){var n=l(e,2),r=n[0],i=n[1],a=l(t,2),u=a[0],o=a[1],s=ce(r,u);return 0===s?ce(i,o):s}var du=function(){function e(t){C(this,e),this.xn=t,this.buffer=new rn(hu),this.Nn=0}return P(e,[{key:"kn",value:function(){return++this.Nn}},{key:"On",value:function(e){var t=[e,this.kn()];if(this.buffer.size<this.xn)this.buffer=this.buffer.add(t);else{var n=this.buffer.last();hu(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}},{key:"maxValue",get:function(){return this.buffer.last()[0]}}]),e}(),vu=function(){function e(t,n,r){C(this,e),this.garbageCollector=t,this.asyncQueue=n,this.localStore=r,this.Mn=null}return P(e,[{key:"start",value:function(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Fn(6e4)}},{key:"stop",value:function(){this.Mn&&(this.Mn.cancel(),this.Mn=null)}},{key:"started",get:function(){return null!==this.Mn}},{key:"Fn",value:function(e){var t=this;B("LruGarbageCollector","Garbage collection scheduled in ".concat(e,"ms")),this.Mn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return t.Mn=null,e.prev=1,e.next=4,y().awrap(t.localStore.collectGarbage(t.garbageCollector));case 4:e.next=14;break;case 6:if(e.prev=6,e.t0=e.catch(1),!Oe(e.t0)){e.next=12;break}B("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e.t0),e.next=14;break;case 12:return e.next=14,y().awrap(Pe(e.t0));case 14:return e.next=16,y().awrap(t.Fn(3e5));case 16:case"end":return e.stop()}},null,null,[[1,6]],Promise)})}}]),e}(),yu=function(){function e(t,n){C(this,e),this.$n=t,this.params=n}return P(e,[{key:"calculateTargetCount",value:function(e,t){return this.$n.Bn(e).next(function(e){return Math.floor(t/100*e)})}},{key:"nthSequenceNumber",value:function(e,t){var n=this;if(0===t)return Le.resolve(je.at);var r=new du(t);return this.$n.forEachTarget(e,function(e){return r.On(e.sequenceNumber)}).next(function(){return n.$n.Ln(e,function(e){return r.On(e)})}).next(function(){return r.maxValue})}},{key:"removeTargets",value:function(e,t,n){return this.$n.removeTargets(e,t,n)}},{key:"removeOrphanedDocuments",value:function(e,t){return this.$n.removeOrphanedDocuments(e,t)}},{key:"collect",value:function(e,t){var n=this;return-1===this.params.cacheSizeCollectionThreshold?(B("LruGarbageCollector","Garbage collection skipped; disabled"),Le.resolve(Ja)):this.getCacheSize(e).next(function(r){return r<n.params.cacheSizeCollectionThreshold?(B("LruGarbageCollector","Garbage collection skipped; Cache size ".concat(r," is lower than threshold ").concat(n.params.cacheSizeCollectionThreshold)),Ja):n.qn(e,t)})}},{key:"getCacheSize",value:function(e){return this.$n.getCacheSize(e)}},{key:"qn",value:function(e,t){var n,r,a,u,o,s,c,l=this,f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(function(t){return t>l.params.maximumSequenceNumbersToCollect?(B("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of ".concat(l.params.maximumSequenceNumbersToCollect," from ").concat(t)),r=l.params.maximumSequenceNumbersToCollect):r=t,u=Date.now(),l.nthSequenceNumber(e,r)}).next(function(r){return n=r,o=Date.now(),l.removeTargets(e,n,t)}).next(function(t){return a=t,s=Date.now(),l.removeOrphanedDocuments(e,n)}).next(function(e){return c=Date.now(),q()<=i.LogLevel.DEBUG&&B("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in ".concat(u-f,"ms\n\tDetermined least recently used ").concat(r," in ")+(o-u)+"ms\n"+"\tRemoved ".concat(a," targets in ")+(s-o)+"ms\n"+"\tRemoved ".concat(e," documents in ")+(c-s)+"ms\n"+"Total Duration: ".concat(c-f,"ms")),Le.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:a,documentsRemoved:e})})}}]),e}(),pu=function(){function e(t,n){C(this,e),this.db=t,this.garbageCollector=function(e,t){return new yu(e,t)}(this,n)}return P(e,[{key:"Bn",value:function(e){var t=this.Un(e);return this.db.getTargetCache().getTargetCount(e).next(function(e){return t.next(function(t){return e+t})})}},{key:"Un",value:function(e){var t=0;return this.Ln(e,function(e){t++}).next(function(){return t})}},{key:"forEachTarget",value:function(e,t){return this.db.getTargetCache().forEachTarget(e,t)}},{key:"Ln",value:function(e,t){return this.Kn(e,function(e,n){return t(n)})}},{key:"addReference",value:function(e,t,n){return mu(e,n)}},{key:"removeReference",value:function(e,t,n){return mu(e,n)}},{key:"removeTargets",value:function(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}},{key:"markPotentiallyOrphaned",value:function(e,t){return mu(e,t)}},{key:"Gn",value:function(e,t){return function(e,t){var n=!1;return uu(e).tt(function(r){return ru(e,r,t).next(function(e){return e&&(n=!0),Le.resolve(!e)})}).next(function(){return n})}(e,t)}},{key:"removeOrphanedDocuments",value:function(e,t){var n=this,r=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[],a=0;return this.Kn(e,function(u,o){if(o<=t){var s=n.Gn(e,u).next(function(t){if(!t)return a++,r.getEntry(e,u).next(function(){return r.removeEntry(u,de.min()),fu(e).delete([0,Si(u.path)])})});i.push(s)}}).next(function(){return Le.waitFor(i)}).next(function(){return r.apply(e)}).next(function(){return a})}},{key:"removeTarget",value:function(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}},{key:"updateLimboDocument",value:function(e,t){return mu(e,t)}},{key:"Kn",value:function(e,t){var n,r=fu(e),i=je.at;return r.Z({index:"documentTargetsIndex"},function(e,r){var a=l(e,2),u=a[0],o=(a[1],r.path),s=r.sequenceNumber;0===u?(i!==je.at&&t(new ge(Ai(n)),i),i=s,n=o):i=je.at}).next(function(){i!==je.at&&t(new ge(Ai(n)),i)})}},{key:"getCacheSize",value:function(e){return this.db.getRemoteDocumentCache().getSize(e)}}]),e}();function mu(e,t){return fu(e).put(function(e,t){return{targetId:0,path:Si(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}var gu=function(){function e(){C(this,e),this.changes=new xr(function(e){return e.toString()},function(e,t){return e.isEqual(t)}),this.changesApplied=!1}return P(e,[{key:"addEntry",value:function(e){this.assertNotApplied(),this.changes.set(e.key,e)}},{key:"removeEntry",value:function(e,t){this.assertNotApplied(),this.changes.set(e,ln.newInvalidDocument(e).setReadTime(t))}},{key:"getEntry",value:function(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?Le.resolve(n):this.getFromCache(e,t)}},{key:"getEntries",value:function(e,t){return this.getAllFromCache(e,t)}},{key:"apply",value:function(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}},{key:"assertNotApplied",value:function(){}}]),e}(),ku=function(){function e(t){C(this,e),this.yt=t}return P(e,[{key:"setIndexManager",value:function(e){this.indexManager=e}},{key:"addEntry",value:function(e,t,n){return Iu(e).put(n)}},{key:"removeEntry",value:function(e,t,n){return Iu(e).delete(function(e,t){var n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],sa(t),n[n.length-1]]}(t,n))}},{key:"updateMetadata",value:function(e,t){var n=this;return this.getMetadata(e).next(function(r){return r.byteSize+=t,n.Qn(e,r)})}},{key:"getEntry",value:function(e,t){var n=this,r=ln.newInvalidDocument(t);return Iu(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Eu(t))},function(e,i){r=n.jn(t,i)}).next(function(){return r})}},{key:"Wn",value:function(e,t){var n=this,r={size:0,document:ln.newInvalidDocument(t)};return Iu(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Eu(t))},function(e,i){r={document:n.jn(t,i),size:tu(i)}}).next(function(){return r})}},{key:"getEntries",value:function(e,t){var n=this,r=Ir();return this.zn(e,t,function(e,t){var i=n.jn(e,t);r=r.insert(e,i)}).next(function(){return r})}},{key:"Hn",value:function(e,t){var n=this,r=Ir(),i=new en(ge.comparator);return this.zn(e,t,function(e,t){var a=n.jn(e,t);r=r.insert(e,a),i=i.insert(e,tu(t))}).next(function(){return{documents:r,Jn:i}})}},{key:"zn",value:function(e,t,n){if(t.isEmpty())return Le.resolve();var r=new rn(Su);t.forEach(function(e){return r=r.add(e)});var i=IDBKeyRange.bound(Eu(r.first()),Eu(r.last())),a=r.getIterator(),u=a.getNext();return Iu(e).Z({index:"documentKeyIndex",range:i},function(e,t,r){for(var i=ge.fromSegments([].concat(I(t.prefixPath),[t.collectionGroup,t.documentId]));u&&Su(u,i)<0;)n(u,null),u=a.getNext();u&&u.isEqual(i)&&(n(u,t),u=a.hasNext()?a.getNext():null),u?r.j(Eu(u)):r.done()}).next(function(){for(;u;)n(u,null),u=a.hasNext()?a.getNext():null})}},{key:"getDocumentsMatchingQuery",value:function(e,t,n,r){var i=this,a=t.path,u=[a.popLast().toArray(),a.lastSegment(),sa(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[a.popLast().toArray(),a.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Iu(e).W(IDBKeyRange.bound(u,o,!0)).next(function(e){var n,a=Ir(),u=v(e);try{for(u.s();!(n=u.n()).done;){var o=n.value,s=i.jn(ge.fromSegments(o.prefixPath.concat(o.collectionGroup,o.documentId)),o);s.isFoundDocument()&&(Ln(t,s)||r.has(s.key))&&(a=a.insert(s.key,s))}}catch(c){u.e(c)}finally{u.f()}return a})}},{key:"getAllFromCollectionGroup",value:function(e,t,n,r){var i=this,a=Ir(),u=Tu(t,n),o=Tu(t,De.max());return Iu(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(u,o,!0)},function(e,t,n){var u=i.jn(ge.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(a=a.insert(u.key,u)).size===r&&n.done()}).next(function(){return a})}},{key:"newChangeBuffer",value:function(e){return new xu(this,!!e&&e.trackRemovals)}},{key:"getSize",value:function(e){return this.getMetadata(e).next(function(e){return e.byteSize})}},{key:"getMetadata",value:function(e){return bu(e).get("remoteDocumentGlobalKey").next(function(e){return z(!!e),e})}},{key:"Qn",value:function(e,t){return bu(e).put("remoteDocumentGlobalKey",t)}},{key:"jn",value:function(e,t){if(t){var n=ua(this.yt,t);if(!n.isNoDocument()||!n.version.isEqual(de.min()))return n}return ln.newInvalidDocument(e)}}]),e}();function wu(e){return new ku(e)}var xu=function(e){p(n,gu);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).Yn=e,i.trackRemovals=r,i.Xn=new xr(function(e){return e.toString()},function(e,t){return e.isEqual(t)}),i}return P(n,[{key:"applyChanges",value:function(e){var t=this,n=[],r=0,i=new rn(function(e,t){return ce(e.canonicalString(),t.canonicalString())});return this.changes.forEach(function(a,u){var o=t.Xn.get(a);if(n.push(t.Yn.removeEntry(e,a,o.readTime)),u.isValidDocument()){var s=oa(t.Yn.yt,u);i=i.add(a.path.popLast());var c=tu(s);r+=c-o.size,n.push(t.Yn.addEntry(e,a,s))}else if(r-=o.size,t.trackRemovals){var l=oa(t.Yn.yt,u.convertToNoDocument(de.min()));n.push(t.Yn.addEntry(e,a,l))}}),i.forEach(function(r){n.push(t.Yn.indexManager.addToCollectionParentIndex(e,r))}),n.push(this.Yn.updateMetadata(e,r)),Le.waitFor(n)}},{key:"getFromCache",value:function(e,t){var n=this;return this.Yn.Wn(e,t).next(function(e){return n.Xn.set(t,{size:e.size,readTime:e.document.readTime}),e.document})}},{key:"getAllFromCache",value:function(e,t){var n=this;return this.Yn.Hn(e,t).next(function(e){var t=e.documents;return e.Jn.forEach(function(e,r){n.Xn.set(e,{size:r,readTime:t.get(e).readTime})}),t})}}]),n}();function bu(e){return ea(e,"remoteDocumentGlobal")}function Iu(e){return ea(e,"remoteDocumentsV14")}function Eu(e){var t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Tu(e,t){var n=t.documentKey.path.toArray();return[e,sa(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function Su(e,t){for(var n=e.path.toArray(),r=t.path.toArray(),i=0,a=0;a<n.length-2&&a<r.length-2;++a)if(i=ce(n[a],r[a]))return i;return(i=ce(n.length,r.length))||((i=ce(n[n.length-2],r[r.length-2]))||ce(n[n.length-1],r[r.length-1]))}var _u=P(function e(t,n){C(this,e),this.overlayedDocument=t,this.mutatedFields=n}),Du=function(){function e(t,n,r,i){C(this,e),this.remoteDocumentCache=t,this.mutationQueue=n,this.documentOverlayCache=r,this.indexManager=i}return P(e,[{key:"getDocument",value:function(e,t){var n=this,r=null;return this.documentOverlayCache.getOverlay(e,t).next(function(i){return r=i,n.remoteDocumentCache.getEntry(e,t)}).next(function(e){return null!==r&&ur(r.mutation,e,on.empty(),he.now()),e})}},{key:"getDocuments",value:function(e,t){var n=this;return this.remoteDocumentCache.getEntries(e,t).next(function(t){return n.getLocalViewOfDocuments(e,t,Pr()).next(function(){return t})})}},{key:"getLocalViewOfDocuments",value:function(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Pr(),i=_r();return this.populateOverlays(e,i,t).next(function(){return n.computeViews(e,t,i,r).next(function(e){var t=Tr();return e.forEach(function(e,n){t=t.insert(e,n.overlayedDocument)}),t})})}},{key:"getOverlayedDocuments",value:function(e,t){var n=this,r=_r();return this.populateOverlays(e,r,t).next(function(){return n.computeViews(e,t,r,Pr())})}},{key:"populateOverlays",value:function(e,t,n){var r=[];return n.forEach(function(e){t.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(function(e){e.forEach(function(e,n){t.set(e,n)})})}},{key:"computeViews",value:function(e,t,n,r){var i=Ir(),a=Ar(),u=Ar();return t.forEach(function(e,t){var u=n.get(t.key);r.has(t.key)&&(void 0===u||u.mutation instanceof lr)?i=i.insert(t.key,t):void 0!==u?(a.set(t.key,u.mutation.getFieldMask()),ur(u.mutation,t,u.mutation.getFieldMask(),he.now())):a.set(t.key,on.empty())}),this.recalculateAndSaveOverlays(e,i).next(function(e){return e.forEach(function(e,t){return a.set(e,t)}),t.forEach(function(e,t){var n;return u.set(e,new _u(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),u})}},{key:"recalculateAndSaveOverlays",value:function(e,t){var n=this,r=Ar(),i=new en(function(e,t){return e-t}),a=Pr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(function(e){var n,a=v(e);try{var u=function(){var e=n.value;e.keys().forEach(function(n){var a=t.get(n);if(null!==a){var u=r.get(n)||on.empty();u=e.applyToLocalView(a,u),r.set(n,u);var o=(i.get(e.batchId)||Pr()).add(n);i=i.insert(e.batchId,o)}})};for(a.s();!(n=a.n()).done;)u()}catch(o){a.e(o)}finally{a.f()}}).next(function(){for(var u=[],o=i.getReverseIterator(),s=function(){var i=o.getNext(),s=i.key,c=i.value,l=Dr();c.forEach(function(e){if(!a.has(e)){var n=ir(t.get(e),r.get(e));null!==n&&l.set(e,n),a=a.add(e)}}),u.push(n.documentOverlayCache.saveOverlays(e,s,l))};o.hasNext();)s();return Le.waitFor(u)}).next(function(){return r})}},{key:"recalculateAndSaveOverlaysForDocumentKeys",value:function(e,t){var n=this;return this.remoteDocumentCache.getEntries(e,t).next(function(t){return n.recalculateAndSaveOverlays(e,t)})}},{key:"getDocumentsMatchingQuery",value:function(e,t,n){return function(e){return ge.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Tn(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n)}},{key:"getNextDocuments",value:function(e,t,n,r){var i=this;return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(function(a){var u=r-a.size>0?i.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-a.size):Le.resolve(_r()),o=-1,s=a;return u.next(function(t){return Le.forEach(t,function(t,n){return o<n.largestBatchId&&(o=n.largestBatchId),a.get(t)?Le.resolve():i.remoteDocumentCache.getEntry(e,t).next(function(e){s=s.insert(t,e)})}).next(function(){return i.populateOverlays(e,t,a)}).next(function(){return i.computeViews(e,s,t,Pr())}).next(function(e){return{batchId:o,changes:Sr(e)}})})})}},{key:"getDocumentsMatchingDocumentQuery",value:function(e,t){return this.getDocument(e,new ge(t)).next(function(e){var t=Tr();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}},{key:"getDocumentsMatchingCollectionGroupQuery",value:function(e,t,n){var r=this,i=t.collectionGroup,a=Tr();return this.indexManager.getCollectionParents(e,i).next(function(u){return Le.forEach(u,function(u){var o=function(e,t){return new kn(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,u.child(i));return r.getDocumentsMatchingCollectionQuery(e,o,n).next(function(e){e.forEach(function(e,t){a=a.insert(e,t)})})}).next(function(){return a})})}},{key:"getDocumentsMatchingCollectionQuery",value:function(e,t,n){var r,i=this;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(function(a){return r=a,i.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,r)}).next(function(e){r.forEach(function(t,n){var r=n.getKey();null===e.get(r)&&(e=e.insert(r,ln.newInvalidDocument(r)))});var n=Tr();return e.forEach(function(e,i){var a=r.get(e);void 0!==a&&ur(a.mutation,i,on.empty(),he.now()),Ln(t,i)&&(n=n.insert(e,i))}),n})}}]),e}(),Au=function(){function e(t){C(this,e),this.yt=t,this.Zn=new Map,this.ts=new Map}return P(e,[{key:"getBundleMetadata",value:function(e,t){return Le.resolve(this.Zn.get(t))}},{key:"saveBundleMetadata",value:function(e,t){var n;return this.Zn.set(t.id,{id:(n=t).id,version:n.version,createTime:Zr(n.createTime)}),Le.resolve()}},{key:"getNamedQuery",value:function(e,t){return Le.resolve(this.ts.get(t))}},{key:"saveNamedQuery",value:function(e,t){return this.ts.set(t.name,function(e){return{name:e.name,query:va(e.bundledQuery),readTime:Zr(e.readTime)}}(t)),Le.resolve()}}]),e}(),Cu=function(){function e(){C(this,e),this.overlays=new en(ge.comparator),this.es=new Map}return P(e,[{key:"getOverlay",value:function(e,t){return Le.resolve(this.overlays.get(t))}},{key:"getOverlays",value:function(e,t){var n=this,r=_r();return Le.forEach(t,function(t){return n.getOverlay(e,t).next(function(e){null!==e&&r.set(t,e)})}).next(function(){return r})}},{key:"saveOverlays",value:function(e,t,n){var r=this;return n.forEach(function(n,i){r.oe(e,t,i)}),Le.resolve()}},{key:"removeOverlaysForBatchId",value:function(e,t,n){var r=this,i=this.es.get(n);return void 0!==i&&(i.forEach(function(e){return r.overlays=r.overlays.remove(e)}),this.es.delete(n)),Le.resolve()}},{key:"getOverlaysForCollection",value:function(e,t,n){for(var r=_r(),i=t.length+1,a=new ge(t.child("")),u=this.overlays.getIteratorFrom(a);u.hasNext();){var o=u.getNext().value,s=o.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&o.largestBatchId>n&&r.set(o.getKey(),o)}return Le.resolve(r)}},{key:"getOverlaysForCollectionGroup",value:function(e,t,n,r){for(var i=new en(function(e,t){return e-t}),a=this.overlays.getIterator();a.hasNext();){var u=a.getNext().value;if(u.getKey().getCollectionGroup()===t&&u.largestBatchId>n){var o=i.get(u.largestBatchId);null===o&&(o=_r(),i=i.insert(u.largestBatchId,o)),o.set(u.getKey(),u)}}for(var s=_r(),c=i.getIterator();c.hasNext()&&(c.getNext().value.forEach(function(e,t){return s.set(e,t)}),!(s.size()>=r)););return Le.resolve(s)}},{key:"oe",value:function(e,t,n){var r=this.overlays.get(n.key);if(null!==r){var i=this.es.get(r.largestBatchId).delete(n.key);this.es.set(r.largestBatchId,i)}this.overlays=this.overlays.insert(n.key,new ra(t,n));var a=this.es.get(t);void 0===a&&(a=Pr(),this.es.set(t,a)),this.es.set(t,a.add(n.key))}}]),e}(),Nu=function(){function e(){C(this,e),this.ns=new rn(Pu.ss),this.rs=new rn(Pu.os)}return P(e,[{key:"isEmpty",value:function(){return this.ns.isEmpty()}},{key:"addReference",value:function(e,t){var n=new Pu(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}},{key:"us",value:function(e,t){var n=this;e.forEach(function(e){return n.addReference(e,t)})}},{key:"removeReference",value:function(e,t){this.cs(new Pu(e,t))}},{key:"hs",value:function(e,t){var n=this;e.forEach(function(e){return n.removeReference(e,t)})}},{key:"ls",value:function(e){var t=this,n=new ge(new ye([])),r=new Pu(n,e),i=new Pu(n,e+1),a=[];return this.rs.forEachInRange([r,i],function(e){t.cs(e),a.push(e.key)}),a}},{key:"fs",value:function(){var e=this;this.ns.forEach(function(t){return e.cs(t)})}},{key:"cs",value:function(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}},{key:"ds",value:function(e){var t=new ge(new ye([])),n=new Pu(t,e),r=new Pu(t,e+1),i=Pr();return this.rs.forEachInRange([n,r],function(e){i=i.add(e.key)}),i}},{key:"containsKey",value:function(e){var t=new Pu(e,0),n=this.ns.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}]),e}(),Pu=function(){function e(t,n){C(this,e),this.key=t,this._s=n}return P(e,null,[{key:"ss",value:function(e,t){return ge.comparator(e.key,t.key)||ce(e._s,t._s)}},{key:"os",value:function(e,t){return ce(e._s,t._s)||ge.comparator(e.key,t.key)}}]),e}(),Lu=function(){function e(t,n){C(this,e),this.indexManager=t,this.referenceDelegate=n,this.mutationQueue=[],this.ws=1,this.gs=new rn(Pu.ss)}return P(e,[{key:"checkEmpty",value:function(e){return Le.resolve(0===this.mutationQueue.length)}},{key:"addMutationBatch",value:function(e,t,n,r){var i=this.ws;this.ws++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];var a=new ta(i,t,n,r);this.mutationQueue.push(a);var u,o=v(r);try{for(o.s();!(u=o.n()).done;){var s=u.value;this.gs=this.gs.add(new Pu(s.key,i)),this.indexManager.addToCollectionParentIndex(e,s.key.path.popLast())}}catch(c){o.e(c)}finally{o.f()}return Le.resolve(a)}},{key:"lookupMutationBatch",value:function(e,t){return Le.resolve(this.ys(t))}},{key:"getNextMutationBatchAfterBatchId",value:function(e,t){var n=t+1,r=this.ps(n),i=r<0?0:r;return Le.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}},{key:"getHighestUnacknowledgedBatchId",value:function(){return Le.resolve(0===this.mutationQueue.length?-1:this.ws-1)}},{key:"getAllMutationBatches",value:function(e){return Le.resolve(this.mutationQueue.slice())}},{key:"getAllMutationBatchesAffectingDocumentKey",value:function(e,t){var n=this,r=new Pu(t,0),i=new Pu(t,Number.POSITIVE_INFINITY),a=[];return this.gs.forEachInRange([r,i],function(e){var t=n.ys(e._s);a.push(t)}),Le.resolve(a)}},{key:"getAllMutationBatchesAffectingDocumentKeys",value:function(e,t){var n=this,r=new rn(ce);return t.forEach(function(e){var t=new Pu(e,0),i=new Pu(e,Number.POSITIVE_INFINITY);n.gs.forEachInRange([t,i],function(e){r=r.add(e._s)})}),Le.resolve(this.Is(r))}},{key:"getAllMutationBatchesAffectingQuery",value:function(e,t){var n=t.path,r=n.length+1,i=n;ge.isDocumentKey(i)||(i=i.child(""));var a=new Pu(new ge(i),0),u=new rn(ce);return this.gs.forEachWhile(function(e){var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(u=u.add(e._s)),!0)},a),Le.resolve(this.Is(u))}},{key:"Is",value:function(e){var t=this,n=[];return e.forEach(function(e){var r=t.ys(e);null!==r&&n.push(r)}),n}},{key:"removeMutationBatch",value:function(e,t){var n=this;z(0===this.Ts(t.batchId,"removed")),this.mutationQueue.shift();var r=this.gs;return Le.forEach(t.mutations,function(i){var a=new Pu(i.key,t.batchId);return r=r.delete(a),n.referenceDelegate.markPotentiallyOrphaned(e,i.key)}).next(function(){n.gs=r})}},{key:"An",value:function(e){}},{key:"containsKey",value:function(e,t){var n=new Pu(t,0),r=this.gs.firstAfterOrEqual(n);return Le.resolve(t.isEqual(r&&r.key))}},{key:"performConsistencyCheck",value:function(e){return this.mutationQueue.length,Le.resolve()}},{key:"Ts",value:function(e,t){return this.ps(e)}},{key:"ps",value:function(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}},{key:"ys",value:function(e){var t=this.ps(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}]),e}(),Fu=function(){function e(t){C(this,e),this.Es=t,this.docs=new en(ge.comparator),this.size=0}return P(e,[{key:"setIndexManager",value:function(e){this.indexManager=e}},{key:"addEntry",value:function(e,t){var n=t.key,r=this.docs.get(n),i=r?r.size:0,a=this.Es(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}},{key:"removeEntry",value:function(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}},{key:"getEntry",value:function(e,t){var n=this.docs.get(t);return Le.resolve(n?n.document.mutableCopy():ln.newInvalidDocument(t))}},{key:"getEntries",value:function(e,t){var n=this,r=Ir();return t.forEach(function(e){var t=n.docs.get(e);r=r.insert(e,t?t.document.mutableCopy():ln.newInvalidDocument(e))}),Le.resolve(r)}},{key:"getDocumentsMatchingQuery",value:function(e,t,n,r){for(var i=Ir(),a=t.path,u=new ge(a.child("")),o=this.docs.getIteratorFrom(u);o.hasNext();){var s=o.getNext(),c=s.key,l=s.value.document;if(!a.isPrefixOf(c.path))break;c.path.length>a.length+1||Ae(_e(l),n)<=0||(r.has(l.key)||Ln(t,l))&&(i=i.insert(l.key,l.mutableCopy()))}return Le.resolve(i)}},{key:"getAllFromCollectionGroup",value:function(e,t,n,r){j()}},{key:"As",value:function(e,t){return Le.forEach(this.docs,function(e){return t(e)})}},{key:"newChangeBuffer",value:function(e){return new Mu(this)}},{key:"getSize",value:function(e){return Le.resolve(this.size)}}]),e}(),Mu=function(e){p(n,gu);var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this)).Yn=e,r}return P(n,[{key:"applyChanges",value:function(e){var t=this,n=[];return this.changes.forEach(function(r,i){i.isValidDocument()?n.push(t.Yn.addEntry(e,i)):t.Yn.removeEntry(r)}),Le.waitFor(n)}},{key:"getFromCache",value:function(e,t){return this.Yn.getEntry(e,t)}},{key:"getAllFromCache",value:function(e,t){return this.Yn.getEntries(e,t)}}]),n}(),Ru=function(){function e(t){C(this,e),this.persistence=t,this.Rs=new xr(function(e){return dn(e)},vn),this.lastRemoteSnapshotVersion=de.min(),this.highestTargetId=0,this.bs=0,this.Ps=new Nu,this.targetCount=0,this.vs=ou.Pn()}return P(e,[{key:"forEachTarget",value:function(e,t){return this.Rs.forEach(function(e,n){return t(n)}),Le.resolve()}},{key:"getLastRemoteSnapshotVersion",value:function(e){return Le.resolve(this.lastRemoteSnapshotVersion)}},{key:"getHighestSequenceNumber",value:function(e){return Le.resolve(this.bs)}},{key:"allocateTargetId",value:function(e){return this.highestTargetId=this.vs.next(),Le.resolve(this.highestTargetId)}},{key:"setTargetsMetadata",value:function(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),Le.resolve()}},{key:"Dn",value:function(e){this.Rs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.vs=new ou(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}},{key:"addTargetData",value:function(e,t){return this.Dn(t),this.targetCount+=1,Le.resolve()}},{key:"updateTargetData",value:function(e,t){return this.Dn(t),Le.resolve()}},{key:"removeTargetData",value:function(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),this.targetCount-=1,Le.resolve()}},{key:"removeTargets",value:function(e,t,n){var r=this,i=0,a=[];return this.Rs.forEach(function(u,o){o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r.Rs.delete(u),a.push(r.removeMatchingKeysForTargetId(e,o.targetId)),i++)}),Le.waitFor(a).next(function(){return i})}},{key:"getTargetCount",value:function(e){return Le.resolve(this.targetCount)}},{key:"getTargetData",value:function(e,t){var n=this.Rs.get(t)||null;return Le.resolve(n)}},{key:"addMatchingKeys",value:function(e,t,n){return this.Ps.us(t,n),Le.resolve()}},{key:"removeMatchingKeys",value:function(e,t,n){this.Ps.hs(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(function(t){i.push(r.markPotentiallyOrphaned(e,t))}),Le.waitFor(i)}},{key:"removeMatchingKeysForTargetId",value:function(e,t){return this.Ps.ls(t),Le.resolve()}},{key:"getMatchingKeysForTargetId",value:function(e,t){var n=this.Ps.ds(t);return Le.resolve(n)}},{key:"containsKey",value:function(e,t){return Le.resolve(this.Ps.containsKey(t))}}]),e}(),Vu=function(){function e(t,n){var r=this;C(this,e),this.Vs={},this.overlays={},this.Ss=new je(0),this.Ds=!1,this.Ds=!0,this.referenceDelegate=t(this),this.Cs=new Ru(this),this.indexManager=new Ka,this.remoteDocumentCache=new Fu(function(e){return r.referenceDelegate.xs(e)}),this.yt=new aa(n),this.Ns=new Au(this.yt)}return P(e,[{key:"start",value:function(){return Promise.resolve()}},{key:"shutdown",value:function(){return this.Ds=!1,Promise.resolve()}},{key:"started",get:function(){return this.Ds}},{key:"setDatabaseDeletedListener",value:function(){}},{key:"setNetworkEnabled",value:function(){}},{key:"getIndexManager",value:function(e){return this.indexManager}},{key:"getDocumentOverlayCache",value:function(e){var t=this.overlays[e.toKey()];return t||(t=new Cu,this.overlays[e.toKey()]=t),t}},{key:"getMutationQueue",value:function(e,t){var n=this.Vs[e.toKey()];return n||(n=new Lu(t,this.referenceDelegate),this.Vs[e.toKey()]=n),n}},{key:"getTargetCache",value:function(){return this.Cs}},{key:"getRemoteDocumentCache",value:function(){return this.remoteDocumentCache}},{key:"getBundleCache",value:function(){return this.Ns}},{key:"runTransaction",value:function(e,t,n){var r=this;B("MemoryPersistence","Starting transaction:",e);var i=new Ou(this.Ss.next());return this.referenceDelegate.ks(),n(i).next(function(e){return r.referenceDelegate.Os(i).next(function(){return e})}).toPromise().then(function(e){return i.raiseOnCommittedEvent(),e})}},{key:"Ms",value:function(e,t){return Le.or(Object.values(this.Vs).map(function(n){return function(){return n.containsKey(e,t)}}))}}]),e}(),Ou=function(e){p(n,Ne);var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this)).currentSequenceNumber=e,r}return P(n)}(),qu=function(){function e(t){C(this,e),this.persistence=t,this.Fs=new Nu,this.$s=null}return P(e,[{key:"Ls",get:function(){if(this.$s)return this.$s;throw j()}},{key:"addReference",value:function(e,t,n){return this.Fs.addReference(n,t),this.Ls.delete(n.toString()),Le.resolve()}},{key:"removeReference",value:function(e,t,n){return this.Fs.removeReference(n,t),this.Ls.add(n.toString()),Le.resolve()}},{key:"markPotentiallyOrphaned",value:function(e,t){return this.Ls.add(t.toString()),Le.resolve()}},{key:"removeTarget",value:function(e,t){var n=this;this.Fs.ls(t.targetId).forEach(function(e){return n.Ls.add(e.toString())});var r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(function(e){e.forEach(function(e){return n.Ls.add(e.toString())})}).next(function(){return r.removeTargetData(e,t)})}},{key:"ks",value:function(){this.$s=new Set}},{key:"Os",value:function(e){var t=this,n=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Le.forEach(this.Ls,function(r){var i=ge.fromPath(r);return t.qs(e,i).next(function(e){e||n.removeEntry(i,de.min())})}).next(function(){return t.$s=null,n.apply(e)})}},{key:"updateLimboDocument",value:function(e,t){var n=this;return this.qs(e,t).next(function(e){e?n.Ls.delete(t.toString()):n.Ls.add(t.toString())})}},{key:"xs",value:function(e){return 0}},{key:"qs",value:function(e,t){var n=this;return Le.or([function(){return Le.resolve(n.Fs.containsKey(t))},function(){return n.persistence.getTargetCache().containsKey(e,t)},function(){return n.persistence.Ms(e,t)}])}}],[{key:"Bs",value:function(t){return new e(t)}}]),e}(),Uu=function(){function e(t){C(this,e),this.yt=t}return P(e,[{key:"$",value:function(e,t,n,r){var i=this,a=new Fe("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Ci,{unique:!0}),e.createObjectStore("documentMutations")}(e),Bu(e),function(e){e.createObjectStore("remoteDocuments")}(e));var u=Le.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),Bu(e)),u=u.next(function(){return e=a.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:de.min().toTimestamp(),targetCount:0},e.put("targetGlobalKey",t);var e,t})),n<4&&r>=4&&(0!==n&&(u=u.next(function(){return function(e,t){return t.store("mutations").W().next(function(n){e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Ci,{unique:!0});var r=t.store("mutations"),i=n.map(function(e){return r.put(e)});return Le.waitFor(i)})}(e,a)})),u=u.next(function(){!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)})),n<5&&r>=5&&(u=u.next(function(){return i.Us(a)})),n<6&&r>=6&&(u=u.next(function(){return function(e){e.createObjectStore("remoteDocumentGlobal")}(e),i.Ks(a)})),n<7&&r>=7&&(u=u.next(function(){return i.Gs(a)})),n<8&&r>=8&&(u=u.next(function(){return i.Qs(e,a)})),n<9&&r>=9&&(u=u.next(function(){!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)})),n<10&&r>=10&&(u=u.next(function(){return i.js(a)})),n<11&&r>=11&&(u=u.next(function(){!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)})),n<12&&r>=12&&(u=u.next(function(){!function(e){var t=e.createObjectStore("documentOverlays",{keyPath:ji});t.createIndex("collectionPathOverlayIndex",zi,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",Wi,{unique:!1})}(e)})),n<13&&r>=13&&(u=u.next(function(){return function(e){var t=e.createObjectStore("remoteDocumentsV14",{keyPath:Fi});t.createIndex("documentKeyIndex",Mi),t.createIndex("collectionGroupIndex",Ri)}(e)}).next(function(){return i.Ws(e,a)}).next(function(){return e.deleteObjectStore("remoteDocuments")})),n<14&&r>=14&&(u=u.next(function(){return i.zs(e,a)})),n<15&&r>=15&&(u=u.next(function(){return function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Bi}).createIndex("sequenceNumberIndex",Gi,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Ki}).createIndex("documentKeyIndex",Qi,{unique:!1})}(e)})),u}},{key:"Ks",value:function(e){var t=0;return e.store("remoteDocuments").Z(function(e,n){t+=tu(n)}).next(function(){var n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)})}},{key:"Us",value:function(e){var t=this,n=e.store("mutationQueues"),r=e.store("mutations");return n.W().next(function(n){return Le.forEach(n,function(n){var i=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return r.W("userMutationsIndex",i).next(function(r){return Le.forEach(r,function(r){z(r.userId===n.userId);var i=fa(t.yt,r);return eu(e,n.userId,i).next(function(){})})})})})}},{key:"Gs",value:function(e){var t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(function(e){var r=[];return n.Z(function(n,i){var a=new ye(n),u=[0,Si(a)];r.push(t.get(u).next(function(n){return n?Le.resolve():function(n){return t.put({targetId:0,path:Si(n),sequenceNumber:e.highestListenSequenceNumber})}(a)}))}).next(function(){return Le.waitFor(r)})})}},{key:"Qs",value:function(e,t){e.createObjectStore("collectionParents",{keyPath:Ui});var n=t.store("collectionParents"),r=new Qa,i=function(e){if(r.add(e)){var t=e.lastSegment(),i=e.popLast();return n.put({collectionId:t,parent:Si(i)})}};return t.store("remoteDocuments").Z({X:!0},function(e,t){var n=new ye(e);return i(n.popLast())}).next(function(){return t.store("documentMutations").Z({X:!0},function(e,t){var n=l(e,3),r=(n[0],n[1]),a=(n[2],Ai(r));return i(a.popLast())})})}},{key:"js",value:function(e){var t=this,n=e.store("targets");return n.Z(function(e,r){var i=ha(r),a=da(t.yt,i);return n.put(a)})}},{key:"Ws",value:function(e,t){var n=t.store("remoteDocuments"),r=[];return n.Z(function(e,n){var i,a=t.store("remoteDocumentsV14"),u=(i=n,i.document?new ge(ye.fromString(i.document.name).popFirst(5)):i.noDocument?ge.fromSegments(i.noDocument.path):i.unknownDocument?ge.fromSegments(i.unknownDocument.path):j()).path.toArray(),o={prefixPath:u.slice(0,u.length-2),collectionGroup:u[u.length-2],documentId:u[u.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(a.put(o))}).next(function(){return Le.waitFor(r)})}},{key:"zs",value:function(e,t){var n=this,r=t.store("mutations"),i=wu(this.yt),a=new Vu(qu.Bs,this.yt.ie);return r.W().next(function(e){var r=new Map;return e.forEach(function(e){var t,i=null!==(t=r.get(e.userId))&&void 0!==t?t:Pr();fa(n.yt,e).keys().forEach(function(e){return i=i.add(e)}),r.set(e.userId,i)}),Le.forEach(r,function(e,r){var u=new R(r),o=xa.re(n.yt,u),s=a.getIndexManager(u),c=nu.re(u,n.yt,s,a.referenceDelegate);return new Du(i,c,o,s).recalculateAndSaveOverlaysForDocumentKeys(new $i(t,je.at),e).next()})})}}]),e}();function Bu(e){e.createObjectStore("targetDocuments",{keyPath:Oi}).createIndex("documentTargetsIndex",qi,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Vi,{unique:!0}),e.createObjectStore("targetGlobal")}var Gu="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.",Ku=function(){function e(t,n,r,i,a,u,o,s,c,l){var f=arguments.length>10&&void 0!==arguments[10]?arguments[10]:15;if(C(this,e),this.allowTabSynchronization=t,this.persistenceKey=n,this.clientId=r,this.Hs=a,this.window=u,this.document=o,this.Js=c,this.Ys=l,this.Xs=f,this.Ss=null,this.Ds=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Zs=null,this.inForeground=!1,this.ti=null,this.ei=null,this.ni=Number.NEGATIVE_INFINITY,this.si=function(e){return Promise.resolve()},!e.C())throw new X(Y.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new pu(this,i),this.ii=n+"main",this.yt=new aa(s),this.ri=new Me(this.ii,this.Xs,new Uu(this.yt)),this.Cs=new su(this.referenceDelegate,this.yt),this.remoteDocumentCache=wu(this.yt),this.Ns=new ga,this.window&&this.window.localStorage?this.oi=this.window.localStorage:(this.oi=null,!1===l&&G("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}return P(e,[{key:"start",value:function(){var e=this;return this.ui().then(function(){if(!e.isPrimary&&!e.allowTabSynchronization)throw new X(Y.FAILED_PRECONDITION,Gu);return e.ci(),e.ai(),e.hi(),e.runTransaction("getHighestListenSequenceNumber","readonly",function(t){return e.Cs.getHighestSequenceNumber(t)})}).then(function(t){e.Ss=new je(t,e.Js)}).then(function(){e.Ds=!0}).catch(function(t){return e.ri&&e.ri.close(),Promise.reject(t)})}},{key:"li",value:function(e){var t=this;return this.si=function(n){return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(!t.started){r.next=2;break}return r.abrupt("return",e(n));case 2:case"end":return r.stop()}},null,null,null,Promise)},e(this.isPrimary)}},{key:"setDatabaseDeletedListener",value:function(e){this.ri.L(function(t){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=null===t.newVersion,!n.t0){n.next=4;break}return n.next=4,y().awrap(e());case 4:case"end":return n.stop()}},null,null,null,Promise)})}},{key:"setNetworkEnabled",value:function(e){var t=this;this.networkEnabled!==e&&(this.networkEnabled=e,this.Hs.enqueueAndForget(function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=t.started,!e.t0){e.next=4;break}return e.next=4,y().awrap(t.ui());case 4:case"end":return e.stop()}},null,null,null,Promise)}))}},{key:"ui",value:function(){var e=this;return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",function(t){return ju(t).put({clientId:e.clientId,updateTimeMs:Date.now(),networkEnabled:e.networkEnabled,inForeground:e.inForeground}).next(function(){if(e.isPrimary)return e.fi(t).next(function(t){t||(e.isPrimary=!1,e.Hs.enqueueRetryable(function(){return e.si(!1)}))})}).next(function(){return e.di(t)}).next(function(n){return e.isPrimary&&!n?e._i(t).next(function(){return!1}):!!n&&e.wi(t).next(function(){return!0})})}).catch(function(t){if(Oe(t))return B("IndexedDbPersistence","Failed to extend owner lease: ",t),e.isPrimary;if(!e.allowTabSynchronization)throw t;return B("IndexedDbPersistence","Releasing owner lease after error during lease refresh",t),!1}).then(function(t){e.isPrimary!==t&&e.Hs.enqueueRetryable(function(){return e.si(t)}),e.isPrimary=t})}},{key:"fi",value:function(e){var t=this;return Qu(e).get("owner").next(function(e){return Le.resolve(t.mi(e))})}},{key:"gi",value:function(e){return ju(e).delete(this.clientId)}},{key:"yi",value:function(){var e,t,n,r,i=this;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:if(!this.isPrimary||this.pi(this.ni,18e5)){a.next=6;break}return this.ni=Date.now(),a.next=4,y().awrap(this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(e){var t=ea(e,"clientMetadata");return t.W().next(function(e){var n=i.Ii(e,18e5),r=e.filter(function(e){return-1===n.indexOf(e)});return Le.forEach(r,function(e){return t.delete(e.clientId)}).next(function(){return r})})}).catch(function(){return[]}));case 4:if(e=a.sent,this.oi){t=v(e);try{for(t.s();!(n=t.n()).done;)r=n.value,this.oi.removeItem(this.Ti(r.clientId))}catch(u){t.e(u)}finally{t.f()}}case 6:case"end":return a.stop()}},null,this,null,Promise)}},{key:"hi",value:function(){var e=this;this.ei=this.Hs.enqueueAfterDelay("client_metadata_refresh",4e3,function(){return e.ui().then(function(){return e.yi()}).then(function(){return e.hi()})})}},{key:"mi",value:function(e){return!!e&&e.ownerId===this.clientId}},{key:"di",value:function(e){var t=this;return this.Ys?Le.resolve(!0):Qu(e).get("owner").next(function(n){if(null!==n&&t.pi(n.leaseTimestampMs,5e3)&&!t.Ei(n.ownerId)){if(t.mi(n)&&t.networkEnabled)return!0;if(!t.mi(n)){if(!n.allowTabSynchronization)throw new X(Y.FAILED_PRECONDITION,Gu);return!1}}return!(!t.networkEnabled||!t.inForeground)||ju(e).W().next(function(e){return void 0===t.Ii(e,5e3).find(function(e){if(t.clientId!==e.clientId){var n=!t.networkEnabled&&e.networkEnabled,r=!t.inForeground&&e.inForeground,i=t.networkEnabled===e.networkEnabled;if(n||r&&i)return!0}return!1})})}).next(function(e){return t.isPrimary!==e&&B("IndexedDbPersistence","Client ".concat(e?"is":"is not"," eligible for a primary lease.")),e})}},{key:"shutdown",value:function(){var e=this;return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return this.Ds=!1,this.Ai(),this.ei&&(this.ei.cancel(),this.ei=null),this.Ri(),this.bi(),t.next=7,y().awrap(this.ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],function(t){var n=new $i(t,je.at);return e._i(n).next(function(){return e.gi(n)})}));case 7:this.ri.close(),this.Pi();case 9:case"end":return t.stop()}},null,this,null,Promise)}},{key:"Ii",value:function(e,t){var n=this;return e.filter(function(e){return n.pi(e.updateTimeMs,t)&&!n.Ei(e.clientId)})}},{key:"vi",value:function(){var e=this;return this.runTransaction("getActiveClients","readonly",function(t){return ju(t).W().next(function(t){return e.Ii(t,18e5).map(function(e){return e.clientId})})})}},{key:"started",get:function(){return this.Ds}},{key:"getMutationQueue",value:function(e,t){return nu.re(e,this.yt,t,this.referenceDelegate)}},{key:"getTargetCache",value:function(){return this.Cs}},{key:"getRemoteDocumentCache",value:function(){return this.remoteDocumentCache}},{key:"getIndexManager",value:function(e){return new za(e,this.yt.ie.databaseId)}},{key:"getDocumentOverlayCache",value:function(e){return xa.re(this.yt,e)}},{key:"getBundleCache",value:function(){return this.Ns}},{key:"runTransaction",value:function(e,t,n){var r=this;B("IndexedDbPersistence","Starting transaction:",e);var i,a,u="readonly"===t?"readonly":"readwrite",o=15===(i=this.Xs)?Ji:14===i?Zi:13===i?Xi:12===i?Yi:11===i?Hi:void j();return this.ri.runTransaction(e,u,o,function(i){return a=new $i(i,r.Ss?r.Ss.next():je.at),"readwrite-primary"===t?r.fi(a).next(function(e){return!!e||r.di(a)}).next(function(t){if(!t)throw G("Failed to obtain primary lease for action '".concat(e,"'.")),r.isPrimary=!1,r.Hs.enqueueRetryable(function(){return r.si(!1)}),new X(Y.FAILED_PRECONDITION,Ce);return n(a)}).next(function(e){return r.wi(a).next(function(){return e})}):r.Vi(a).next(function(){return n(a)})}).then(function(e){return a.raiseOnCommittedEvent(),e})}},{key:"Vi",value:function(e){var t=this;return Qu(e).get("owner").next(function(e){if(null!==e&&t.pi(e.leaseTimestampMs,5e3)&&!t.Ei(e.ownerId)&&!t.mi(e)&&!(t.Ys||t.allowTabSynchronization&&e.allowTabSynchronization))throw new X(Y.FAILED_PRECONDITION,Gu)})}},{key:"wi",value:function(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Qu(e).put("owner",t)}},{key:"_i",value:function(e){var t=this,n=Qu(e);return n.get("owner").next(function(e){return t.mi(e)?(B("IndexedDbPersistence","Releasing primary lease."),n.delete("owner")):Le.resolve()})}},{key:"pi",value:function(e,t){var n=Date.now();return!(e<n-t||e>n&&(G("Detected an update time that is in the future: ".concat(e," > ").concat(n)),1))}},{key:"ci",value:function(){var e=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ti=function(){e.Hs.enqueueAndForget(function(){return e.inForeground="visible"===e.document.visibilityState,e.ui()})},this.document.addEventListener("visibilitychange",this.ti),this.inForeground="visible"===this.document.visibilityState)}},{key:"Ri",value:function(){this.ti&&(this.document.removeEventListener("visibilitychange",this.ti),this.ti=null)}},{key:"ai",value:function(){var e,t=this;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Zs=function(){t.Ai(),(0,a.isSafari)()&&navigator.appVersion.match(/Version\/1[45]/)&&t.Hs.enterRestrictedMode(!0),t.Hs.enqueueAndForget(function(){return t.shutdown()})},this.window.addEventListener("pagehide",this.Zs))}},{key:"bi",value:function(){this.Zs&&(this.window.removeEventListener("pagehide",this.Zs),this.Zs=null)}},{key:"Ei",value:function(e){var t;try{var n=null!==(null===(t=this.oi)||void 0===t?void 0:t.getItem(this.Ti(e)));return B("IndexedDbPersistence","Client '".concat(e,"' ").concat(n?"is":"is not"," zombied in LocalStorage")),n}catch(e){return G("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}},{key:"Ai",value:function(){if(this.oi)try{this.oi.setItem(this.Ti(this.clientId),String(Date.now()))}catch(e){G("Failed to set zombie client id.",e)}}},{key:"Pi",value:function(){if(this.oi)try{this.oi.removeItem(this.Ti(this.clientId))}catch(e){}}},{key:"Ti",value:function(e){return"firestore_zombie_".concat(this.persistenceKey,"_").concat(e)}}],[{key:"C",value:function(){return Me.C()}}]),e}();function Qu(e){return ea(e,"owner")}function ju(e){return ea(e,"clientMetadata")}function zu(e,t){var n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}var Wu=function(){function e(t,n,r,i){C(this,e),this.targetId=t,this.fromCache=n,this.Si=r,this.Di=i}return P(e,null,[{key:"Ci",value:function(t,n){var r,i=Pr(),a=Pr(),u=v(n.docChanges);try{for(u.s();!(r=u.n()).done;){var o=r.value;switch(o.type){case 0:i=i.add(o.doc.key);break;case 1:a=a.add(o.doc.key)}}}catch(s){u.e(s)}finally{u.f()}return new e(t,n.fromCache,i,a)}}]),e}(),Hu=function(){function e(){C(this,e),this.xi=!1}return P(e,[{key:"initialize",value:function(e,t){this.Ni=e,this.indexManager=t,this.xi=!0}},{key:"getDocumentsMatchingQuery",value:function(e,t,n,r){var i=this;return this.ki(e,t).next(function(a){return a||i.Oi(e,t,r,n)}).next(function(n){return n||i.Mi(e,t)})}},{key:"ki",value:function(e,t){var n=this;if(bn(t))return Le.resolve(null);var r=_n(t);return this.indexManager.getIndexType(e,r).next(function(i){return 0===i?null:(null!==t.limit&&1===i&&(t=An(t,null,"F"),r=_n(t)),n.indexManager.getDocumentsMatchingTarget(e,r).next(function(i){var a=Pr.apply(void 0,I(i));return n.Ni.getDocuments(e,a).next(function(i){return n.indexManager.getMinOffset(e,r).next(function(r){var u=n.Fi(t,i);return n.$i(t,u,a,r.readTime)?n.ki(e,An(t,null,"F")):n.Bi(e,u,t,r)})})}))})}},{key:"Oi",value:function(e,t,n,r){var a=this;return bn(t)||r.isEqual(de.min())?this.Mi(e,t):this.Ni.getDocuments(e,n).next(function(u){var o=a.Fi(t,u);return a.$i(t,o,n,r)?a.Mi(e,t):(q()<=i.LogLevel.DEBUG&&B("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Pn(t)),a.Bi(e,o,t,Se(r,-1)))})}},{key:"Fi",value:function(e,t){var n=new rn(Mn(e));return t.forEach(function(t,r){Ln(e,r)&&(n=n.add(r))}),n}},{key:"$i",value:function(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;var i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}},{key:"Mi",value:function(e,t){return q()<=i.LogLevel.DEBUG&&B("QueryEngine","Using full collection scan to execute query:",Pn(t)),this.Ni.getDocumentsMatchingQuery(e,t,De.min())}},{key:"Bi",value:function(e,t,n,r){return this.Ni.getDocumentsMatchingQuery(e,n,r).next(function(e){return t.forEach(function(t){e=e.insert(t.key,t)}),e})}}]),e}(),Yu=function(){function e(t,n,r,i){C(this,e),this.persistence=t,this.Li=n,this.yt=i,this.qi=new en(ce),this.Ui=new xr(function(e){return dn(e)},vn),this.Ki=new Map,this.Gi=t.getRemoteDocumentCache(),this.Cs=t.getTargetCache(),this.Ns=t.getBundleCache(),this.Qi(r)}return P(e,[{key:"Qi",value:function(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Du(this.Gi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Gi.setIndexManager(this.indexManager),this.Li.initialize(this.localDocuments,this.indexManager)}},{key:"collectGarbage",value:function(e){var t=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",function(n){return e.collect(n,t.qi)})}}]),e}();function Xu(e,t,n,r){return new Yu(e,t,n,r)}function Zu(e,t){var n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return n=H(e),r.next=3,y().awrap(n.persistence.runTransaction("Handle user change","readonly",function(e){var r;return n.mutationQueue.getAllMutationBatches(e).next(function(i){return r=i,n.Qi(t),n.mutationQueue.getAllMutationBatches(e)}).next(function(t){var i,a=[],u=[],o=Pr(),s=v(r);try{for(s.s();!(i=s.n()).done;){var c=i.value;a.push(c.batchId);var l,f=v(c.mutations);try{for(f.s();!(l=f.n()).done;){var h=l.value;o=o.add(h.key)}}catch(w){f.e(w)}finally{f.f()}}}catch(w){s.e(w)}finally{s.f()}var d,y=v(t);try{for(y.s();!(d=y.n()).done;){var p=d.value;u.push(p.batchId);var m,g=v(p.mutations);try{for(g.s();!(m=g.n()).done;){var k=m.value;o=o.add(k.key)}}catch(w){g.e(w)}finally{g.f()}}}catch(w){y.e(w)}finally{y.f()}return n.localDocuments.getDocuments(e,o).next(function(e){return{ji:e,removedBatchIds:a,addedBatchIds:u}})})}));case 3:return r.abrupt("return",r.sent);case 4:case"end":return r.stop()}},null,null,null,Promise)}function Ju(e,t){var n=H(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",function(e){var r=t.batch.keys(),i=n.Gi.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){var i=n.batch,a=i.keys(),u=Le.resolve();return a.forEach(function(e){u=u.next(function(){return r.getEntry(t,e)}).next(function(t){var a=n.docVersions.get(e);z(null!==a),t.version.compareTo(a)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),u.next(function(){return e.mutationQueue.removeMutationBatch(t,i)})}(n,e,t,i).next(function(){return i.apply(e)}).next(function(){return n.mutationQueue.performConsistencyCheck(e)}).next(function(){return n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)}).next(function(){return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){for(var t=Pr(),n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))}).next(function(){return n.localDocuments.getDocuments(e,r)})})}function $u(e){var t=H(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",function(e){return t.Cs.getLastRemoteSnapshotVersion(e)})}function eo(e,t){var n=H(e),r=t.snapshotVersion,i=n.qi;return n.persistence.runTransaction("Apply remote event","readwrite-primary",function(e){var a=n.Gi.newChangeBuffer({trackRemovals:!0});i=n.qi;var u=[];t.targetChanges.forEach(function(a,o){var s=i.get(o);if(s){u.push(n.Cs.removeMatchingKeys(e,a.removedDocuments,o).next(function(){return n.Cs.addMatchingKeys(e,a.addedDocuments,o)}));var c=s.withSequenceNumber(e.currentSequenceNumber);t.targetMismatches.has(o)?c=c.withResumeToken(tt.EMPTY_BYTE_STRING,de.min()).withLastLimboFreeSnapshotVersion(de.min()):a.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(a.resumeToken,r)),i=i.insert(o,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||(t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0)}(s,c,a)&&u.push(n.Cs.updateTargetData(e,c))}});var o=Ir(),s=Pr();if(t.documentUpdates.forEach(function(r){t.resolvedLimboDocuments.has(r)&&u.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))}),u.push(to(e,a,t.documentUpdates).next(function(e){o=e.Wi,s=e.zi})),!r.isEqual(de.min())){var c=n.Cs.getLastRemoteSnapshotVersion(e).next(function(t){return n.Cs.setTargetsMetadata(e,e.currentSequenceNumber,r)});u.push(c)}return Le.waitFor(u).next(function(){return a.apply(e)}).next(function(){return n.localDocuments.getLocalViewOfDocuments(e,o,s)}).next(function(){return o})}).then(function(e){return n.qi=i,e})}function to(e,t,n){var r=Pr(),i=Pr();return n.forEach(function(e){return r=r.add(e)}),t.getEntries(e,r).next(function(e){var r=Ir();return n.forEach(function(n,a){var u=e.get(n);a.isFoundDocument()!==u.isFoundDocument()&&(i=i.add(n)),a.isNoDocument()&&a.version.isEqual(de.min())?(t.removeEntry(n,a.readTime),r=r.insert(n,a)):!u.isValidDocument()||a.version.compareTo(u.version)>0||0===a.version.compareTo(u.version)&&u.hasPendingWrites?(t.addEntry(a),r=r.insert(n,a)):B("LocalStore","Ignoring outdated watch update for ",n,". Current version:",u.version," Watch version:",a.version)}),{Wi:r,zi:i}})}function no(e,t){var n=H(e);return n.persistence.runTransaction("Get next mutation batch","readonly",function(e){return void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)})}function ro(e,t){var n=H(e);return n.persistence.runTransaction("Allocate target","readwrite",function(e){var r;return n.Cs.getTargetData(e,t).next(function(i){return i?(r=i,Le.resolve(r)):n.Cs.allocateTargetId(e).next(function(i){return r=new ia(t,i,0,e.currentSequenceNumber),n.Cs.addTargetData(e,r).next(function(){return r})})})}).then(function(e){var r=n.qi.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.qi=n.qi.insert(e.targetId,e),n.Ui.set(t,e.targetId)),e})}function io(e,t,n){var r,i,a;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:if(r=H(e),i=r.qi.get(t),a=n?"readwrite":"readwrite-primary",u.prev=1,u.t0=n,u.t0){u.next=6;break}return u.next=6,y().awrap(r.persistence.runTransaction("Release target",a,function(e){return r.persistence.referenceDelegate.removeTarget(e,i)}));case 6:u.next=13;break;case 8:if(u.prev=8,u.t1=u.catch(1),Oe(u.t1)){u.next=12;break}throw u.t1;case 12:B("LocalStore","Failed to update sequence numbers for target ".concat(t,": ").concat(u.t1));case 13:r.qi=r.qi.remove(t),r.Ui.delete(i.target);case 14:case"end":return u.stop()}},null,null,[[1,8]],Promise)}function ao(e,t,n){var r=H(e),i=de.min(),a=Pr();return r.persistence.runTransaction("Execute query","readonly",function(e){return function(e,t,n){var r=H(e),i=r.Ui.get(n);return void 0!==i?Le.resolve(r.qi.get(i)):r.Cs.getTargetData(t,n)}(r,e,_n(t)).next(function(t){if(t)return i=t.lastLimboFreeSnapshotVersion,r.Cs.getMatchingKeysForTargetId(e,t.targetId).next(function(e){a=e})}).next(function(){return r.Li.getDocumentsMatchingQuery(e,t,n?i:de.min(),n?a:Pr())}).next(function(e){return so(r,Fn(t),e),{documents:e,Hi:a}})})}function uo(e,t){var n=H(e),r=H(n.Cs),i=n.qi.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",function(e){return r.ne(e,t).next(function(e){return e?e.target:null})})}function oo(e,t){var n=H(e),r=n.Ki.get(t)||de.min();return n.persistence.runTransaction("Get new document changes","readonly",function(e){return n.Gi.getAllFromCollectionGroup(e,t,Se(r,-1),Number.MAX_SAFE_INTEGER)}).then(function(e){return so(n,t,e),e})}function so(e,t,n){var r=e.Ki.get(t)||de.min();n.forEach(function(e,t){t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.Ki.set(t,r)}function co(e,t,n,r){var i,a,u,o,s,c,l,f,h,d;return y().async(function(p){for(;;)switch(p.prev=p.next){case 0:i=H(e),a=Pr(),u=Ir(),o=v(n);try{for(o.s();!(s=o.n()).done;)c=s.value,l=t.Ji(c.metadata.name),c.document&&(a=a.add(l)),(f=t.Yi(c)).setReadTime(t.Xi(c.metadata.readTime)),u=u.insert(l,f)}catch(m){o.e(m)}finally{o.f()}return h=i.Gi.newChangeBuffer({trackRemovals:!0}),p.next=7,y().awrap(ro(i,function(e){return _n(xn(ye.fromString("__bundle__/docs/".concat(e))))}(r)));case 7:return d=p.sent,p.abrupt("return",i.persistence.runTransaction("Apply bundle documents","readwrite",function(e){return to(e,h,u).next(function(t){return h.apply(e),t}).next(function(t){return i.Cs.removeMatchingKeysForTargetId(e,d.targetId).next(function(){return i.Cs.addMatchingKeys(e,a,d.targetId)}).next(function(){return i.localDocuments.getLocalViewOfDocuments(e,t.Wi,t.zi)}).next(function(){return t.Wi})})}));case 9:case"end":return p.stop()}},null,null,null,Promise)}function lo(e,t){var n,r,i,a=arguments;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:return n=a.length>2&&void 0!==a[2]?a[2]:Pr(),u.next=3,y().awrap(ro(e,_n(va(t.bundledQuery))));case 3:return r=u.sent,i=H(e),u.abrupt("return",i.persistence.runTransaction("Save named query","readwrite",function(e){var a=Zr(t.readTime);if(r.snapshotVersion.compareTo(a)>=0)return i.Ns.saveNamedQuery(e,t);var u=r.withResumeToken(tt.EMPTY_BYTE_STRING,a);return i.qi=i.qi.insert(u.targetId,u),i.Cs.updateTargetData(e,u).next(function(){return i.Cs.removeMatchingKeysForTargetId(e,r.targetId)}).next(function(){return i.Cs.addMatchingKeys(e,n,r.targetId)}).next(function(){return i.Ns.saveNamedQuery(e,t)})}));case 6:case"end":return u.stop()}},null,null,null,Promise)}function fo(e,t){return"firestore_clients_".concat(e,"_").concat(t)}function ho(e,t,n){var r="firestore_mutations_".concat(e,"_").concat(n);return t.isAuthenticated()&&(r+="_".concat(t.uid)),r}function vo(e,t){return"firestore_targets_".concat(e,"_").concat(t)}var yo=function(){function e(t,n,r,i){C(this,e),this.user=t,this.batchId=n,this.state=r,this.error=i}return P(e,[{key:"tr",value:function(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}],[{key:"Zi",value:function(t,n,r){var i,a=JSON.parse(r),u="object"==A(a)&&-1!==["pending","acknowledged","rejected"].indexOf(a.state)&&(void 0===a.error||"object"==A(a.error));return u&&a.error&&((u="string"==typeof a.error.message&&"string"==typeof a.error.code)&&(i=new X(a.error.code,a.error.message))),u?new e(t,n,a.state,i):(G("SharedClientState","Failed to parse mutation state for ID '".concat(n,"': ").concat(r)),null)}}]),e}(),po=function(){function e(t,n,r){C(this,e),this.targetId=t,this.state=n,this.error=r}return P(e,[{key:"tr",value:function(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}],[{key:"Zi",value:function(t,n){var r,i=JSON.parse(n),a="object"==A(i)&&-1!==["not-current","current","rejected"].indexOf(i.state)&&(void 0===i.error||"object"==A(i.error));return a&&i.error&&((a="string"==typeof i.error.message&&"string"==typeof i.error.code)&&(r=new X(i.error.code,i.error.message))),a?new e(t,i.state,r):(G("SharedClientState","Failed to parse target state for ID '".concat(t,"': ").concat(n)),null)}}]),e}(),mo=function(){function e(t,n){C(this,e),this.clientId=t,this.activeTargetIds=n}return P(e,null,[{key:"Zi",value:function(t,n){for(var r=JSON.parse(n),i="object"==A(r)&&r.activeTargetIds instanceof Array,a=Fr(),u=0;i&&u<r.activeTargetIds.length;++u)i=$e(r.activeTargetIds[u]),a=a.add(r.activeTargetIds[u]);return i?new e(t,a):(G("SharedClientState","Failed to parse client data for instance '".concat(t,"': ").concat(n)),null)}}]),e}(),go=function(){function e(t,n){C(this,e),this.clientId=t,this.onlineState=n}return P(e,null,[{key:"Zi",value:function(t){var n=JSON.parse(t);return"object"==A(n)&&-1!==["Unknown","Online","Offline"].indexOf(n.onlineState)&&"string"==typeof n.clientId?new e(n.clientId,n.onlineState):(G("SharedClientState","Failed to parse online state: ".concat(t)),null)}}]),e}(),ko=function(){function e(){C(this,e),this.activeTargetIds=Fr()}return P(e,[{key:"er",value:function(e){this.activeTargetIds=this.activeTargetIds.add(e)}},{key:"nr",value:function(e){this.activeTargetIds=this.activeTargetIds.delete(e)}},{key:"tr",value:function(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}]),e}(),wo=function(){function e(t,n,r,i,a){C(this,e),this.window=t,this.Hs=n,this.persistenceKey=r,this.sr=i,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ir=this.rr.bind(this),this.ur=new en(ce),this.started=!1,this.cr=[];var u=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=a,this.ar=fo(this.persistenceKey,this.sr),this.hr=function(e){return"firestore_sequence_number_".concat(e)}(this.persistenceKey),this.ur=this.ur.insert(this.sr,new ko),this.lr=new RegExp("^firestore_clients_".concat(u,"_([^_]*)$")),this.dr=new RegExp("^firestore_mutations_".concat(u,"_(\\d+)(?:_(.*))?$")),this._r=new RegExp("^firestore_targets_".concat(u,"_(\\d+)$")),this.wr=function(e){return"firestore_online_state_".concat(e)}(this.persistenceKey),this.mr=function(e){return"firestore_bundle_loaded_v2_".concat(e)}(this.persistenceKey),this.window.addEventListener("storage",this.ir)}return P(e,[{key:"start",value:function(){var e,t,n,r,i,a,u,o,s,c,l,f=this;return y().async(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,y().awrap(this.syncEngine.vi());case 2:e=h.sent,t=v(e),h.prev=4,t.s();case 6:if((n=t.n()).done){h.next=14;break}if((r=n.value)!==this.sr){h.next=10;break}return h.abrupt("continue",12);case 10:(i=this.getItem(fo(this.persistenceKey,r)))&&(a=mo.Zi(r,i))&&(this.ur=this.ur.insert(a.clientId,a));case 12:h.next=6;break;case 14:h.next=19;break;case 16:h.prev=16,h.t0=h.catch(4),t.e(h.t0);case 19:return h.prev=19,t.f(),h.finish(19);case 22:this.gr(),(u=this.storage.getItem(this.wr))&&(o=this.yr(u))&&this.pr(o),s=v(this.cr);try{for(s.s();!(c=s.n()).done;)l=c.value,this.rr(l)}catch(d){s.e(d)}finally{s.f()}this.cr=[],this.window.addEventListener("pagehide",function(){return f.shutdown()}),this.started=!0;case 28:case"end":return h.stop()}},null,this,[[4,16,19,22]],Promise)}},{key:"writeSequenceNumber",value:function(e){this.setItem(this.hr,JSON.stringify(e))}},{key:"getAllActiveQueryTargets",value:function(){return this.Ir(this.ur)}},{key:"isActiveQueryTarget",value:function(e){var t=!1;return this.ur.forEach(function(n,r){r.activeTargetIds.has(e)&&(t=!0)}),t}},{key:"addPendingMutation",value:function(e){this.Tr(e,"pending")}},{key:"updateMutationState",value:function(e,t,n){this.Tr(e,t,n),this.Er(e)}},{key:"addLocalQueryTarget",value:function(e){var t="not-current";if(this.isActiveQueryTarget(e)){var n=this.storage.getItem(vo(this.persistenceKey,e));if(n){var r=po.Zi(e,n);r&&(t=r.state)}}return this.Ar.er(e),this.gr(),t}},{key:"removeLocalQueryTarget",value:function(e){this.Ar.nr(e),this.gr()}},{key:"isLocalQueryTarget",value:function(e){return this.Ar.activeTargetIds.has(e)}},{key:"clearQueryState",value:function(e){this.removeItem(vo(this.persistenceKey,e))}},{key:"updateQueryState",value:function(e,t,n){this.Rr(e,t,n)}},{key:"handleUserChange",value:function(e,t,n){var r=this;t.forEach(function(e){r.Er(e)}),this.currentUser=e,n.forEach(function(e){r.addPendingMutation(e)})}},{key:"setOnlineState",value:function(e){this.br(e)}},{key:"notifyBundleLoaded",value:function(e){this.Pr(e)}},{key:"shutdown",value:function(){this.started&&(this.window.removeEventListener("storage",this.ir),this.removeItem(this.ar),this.started=!1)}},{key:"getItem",value:function(e){var t=this.storage.getItem(e);return B("SharedClientState","READ",e,t),t}},{key:"setItem",value:function(e,t){B("SharedClientState","SET",e,t),this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){B("SharedClientState","REMOVE",e),this.storage.removeItem(e)}},{key:"rr",value:function(e){var t=this,n=e;if(n.storageArea===this.storage){if(B("SharedClientState","EVENT",n.key,n.newValue),n.key===this.ar)return void G("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Hs.enqueueRetryable(function(){var e,r,i,a,u,o,s;return y().async(function(c){for(;;)switch(c.prev=c.next){case 0:if(!t.started){c.next=43;break}if(null===n.key){c.next=41;break}if(!t.lr.test(n.key)){c.next=11;break}if(null!=n.newValue){c.next=6;break}return e=t.vr(n.key),c.abrupt("return",t.Vr(e,null));case 6:if(!(r=t.Sr(n.key,n.newValue))){c.next=9;break}return c.abrupt("return",t.Vr(r.clientId,r));case 9:c.next=41;break;case 11:if(!t.dr.test(n.key)){c.next=18;break}if(null===n.newValue){c.next=16;break}if(!(i=t.Dr(n.key,n.newValue))){c.next=16;break}return c.abrupt("return",t.Cr(i));case 16:c.next=41;break;case 18:if(!t._r.test(n.key)){c.next=25;break}if(null===n.newValue){c.next=23;break}if(!(a=t.Nr(n.key,n.newValue))){c.next=23;break}return c.abrupt("return",t.kr(a));case 23:c.next=41;break;case 25:if(n.key!==t.wr){c.next=32;break}if(null===n.newValue){c.next=30;break}if(!(u=t.yr(n.newValue))){c.next=30;break}return c.abrupt("return",t.pr(u));case 30:c.next=41;break;case 32:if(n.key!==t.hr){c.next=37;break}(o=function(e){var t=je.at;if(null!=e)try{var n=JSON.parse(e);z("number"==typeof n),t=n}catch(e){G("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(n.newValue))!==je.at&&t.sequenceNumberHandler(o),c.next=41;break;case 37:if(n.key!==t.mr){c.next=41;break}return s=t.Or(n.newValue),c.next=41,y().awrap(Promise.all(s.map(function(e){return t.syncEngine.Mr(e)})));case 41:c.next=44;break;case 43:t.cr.push(n);case 44:case"end":return c.stop()}},null,null,null,Promise)})}}},{key:"Ar",get:function(){return this.ur.get(this.sr)}},{key:"gr",value:function(){this.setItem(this.ar,this.Ar.tr())}},{key:"Tr",value:function(e,t,n){var r=new yo(this.currentUser,e,t,n),i=ho(this.persistenceKey,this.currentUser,e);this.setItem(i,r.tr())}},{key:"Er",value:function(e){var t=ho(this.persistenceKey,this.currentUser,e);this.removeItem(t)}},{key:"br",value:function(e){var t={clientId:this.sr,onlineState:e};this.storage.setItem(this.wr,JSON.stringify(t))}},{key:"Rr",value:function(e,t,n){var r=vo(this.persistenceKey,e),i=new po(e,t,n);this.setItem(r,i.tr())}},{key:"Pr",value:function(e){var t=JSON.stringify(Array.from(e));this.setItem(this.mr,t)}},{key:"vr",value:function(e){var t=this.lr.exec(e);return t?t[1]:null}},{key:"Sr",value:function(e,t){var n=this.vr(e);return mo.Zi(n,t)}},{key:"Dr",value:function(e,t){var n=this.dr.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return yo.Zi(new R(i),r,t)}},{key:"Nr",value:function(e,t){var n=this._r.exec(e),r=Number(n[1]);return po.Zi(r,t)}},{key:"yr",value:function(e){return go.Zi(e)}},{key:"Or",value:function(e){return JSON.parse(e)}},{key:"Cr",value:function(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(e.user.uid!==this.currentUser.uid){t.next=2;break}return t.abrupt("return",this.syncEngine.Fr(e.batchId,e.state,e.error));case 2:B("SharedClientState","Ignoring mutation for non-active user ".concat(e.user.uid));case 3:case"end":return t.stop()}},null,this,null,Promise)}},{key:"kr",value:function(e){return this.syncEngine.$r(e.targetId,e.state,e.error)}},{key:"Vr",value:function(e,t){var n=this,r=t?this.ur.insert(e,t):this.ur.remove(e),i=this.Ir(this.ur),a=this.Ir(r),u=[],o=[];return a.forEach(function(e){i.has(e)||u.push(e)}),i.forEach(function(e){a.has(e)||o.push(e)}),this.syncEngine.Br(u,o).then(function(){n.ur=r})}},{key:"pr",value:function(e){this.ur.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}},{key:"Ir",value:function(e){var t=Fr();return e.forEach(function(e,n){t=t.unionWith(n.activeTargetIds)}),t}}],[{key:"C",value:function(e){return!(!e||!e.localStorage)}}]),e}(),xo=function(){function e(){C(this,e),this.Lr=new ko,this.qr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}return P(e,[{key:"addPendingMutation",value:function(e){}},{key:"updateMutationState",value:function(e,t,n){}},{key:"addLocalQueryTarget",value:function(e){return this.Lr.er(e),this.qr[e]||"not-current"}},{key:"updateQueryState",value:function(e,t,n){this.qr[e]=t}},{key:"removeLocalQueryTarget",value:function(e){this.Lr.nr(e)}},{key:"isLocalQueryTarget",value:function(e){return this.Lr.activeTargetIds.has(e)}},{key:"clearQueryState",value:function(e){delete this.qr[e]}},{key:"getAllActiveQueryTargets",value:function(){return this.Lr.activeTargetIds}},{key:"isActiveQueryTarget",value:function(e){return this.Lr.activeTargetIds.has(e)}},{key:"start",value:function(){return this.Lr=new ko,Promise.resolve()}},{key:"handleUserChange",value:function(e,t,n){}},{key:"setOnlineState",value:function(e){}},{key:"shutdown",value:function(){}},{key:"writeSequenceNumber",value:function(e){}},{key:"notifyBundleLoaded",value:function(e){}}]),e}(),bo=function(){function e(){C(this,e)}return P(e,[{key:"Ur",value:function(e){}},{key:"shutdown",value:function(){}}]),e}(),Io=function(){function e(){var t=this;C(this,e),this.Kr=function(){return t.Gr()},this.Qr=function(){return t.jr()},this.Wr=[],this.zr()}return P(e,[{key:"Ur",value:function(e){this.Wr.push(e)}},{key:"shutdown",value:function(){window.removeEventListener("online",this.Kr),window.removeEventListener("offline",this.Qr)}},{key:"zr",value:function(){window.addEventListener("online",this.Kr),window.addEventListener("offline",this.Qr)}},{key:"Gr",value:function(){B("ConnectivityMonitor","Network connectivity changed: AVAILABLE");var e,t=v(this.Wr);try{for(t.s();!(e=t.n()).done;){(0,e.value)(0)}}catch(n){t.e(n)}finally{t.f()}}},{key:"jr",value:function(){B("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");var e,t=v(this.Wr);try{for(t.s();!(e=t.n()).done;){(0,e.value)(1)}}catch(n){t.e(n)}finally{t.f()}}}],[{key:"C",value:function(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}]),e}(),Eo={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},To=function(){function e(t){C(this,e),this.Hr=t.Hr,this.Jr=t.Jr}return P(e,[{key:"Yr",value:function(e){this.Xr=e}},{key:"Zr",value:function(e){this.eo=e}},{key:"onMessage",value:function(e){this.no=e}},{key:"close",value:function(){this.Jr()}},{key:"send",value:function(e){this.Hr(e)}},{key:"so",value:function(){this.Xr()}},{key:"io",value:function(e){this.eo(e)}},{key:"ro",value:function(e){this.no(e)}}]),e}(),So=function(e){p(n,function(){function e(t){C(this,e);this.databaseInfo=t,this.databaseId=t.databaseId;var n=t.ssl?"https":"http";this.oo=n+"://"+t.host,this.uo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}P(e,[{key:"co",get:function e(){return!1}},{key:"ao",value:function e(t,n,r,i,a){var u=this.ho(t,n);B("RestConnection","Sending: ",u,r);var o={};return this.lo(o,i,a),this.fo(t,u,o,r).then(function(e){return B("RestConnection","Received: ",e),e},function(e){throw K("RestConnection","".concat(t," failed with error: "),e,"url: ",u,"request:",r),e})}},{key:"_o",value:function e(t,n,r,i,a,u){return this.ao(t,n,r,i,a)}},{key:"lo",value:function e(t,n,r){t["X-Goog-Api-Client"]="gl-js/ fire/"+V,t["Content-Type"]="text/plain",this.databaseInfo.appId&&(t["X-Firebase-GMPID"]=this.databaseInfo.appId),n&&n.headers.forEach(function(e,n){return t[n]=e}),r&&r.headers.forEach(function(e,n){return t[n]=e})}},{key:"ho",value:function e(t,n){var r=Eo[t];return"".concat(this.oo,"/v1/").concat(n,":").concat(r)}}]);return e}());var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this,e)).forceLongPolling=e.forceLongPolling,r.autoDetectLongPolling=e.autoDetectLongPolling,r.useFetchStreams=e.useFetchStreams,r}return P(n,[{key:"fo",value:function(e,t,n,r){return new Promise(function(i,a){var o=new u.XhrIo;o.setWithCredentials(!0),o.listenOnce(u.EventType.COMPLETE,function(){try{switch(o.getLastErrorCode()){case u.ErrorCode.NO_ERROR:var t=o.getResponseJson();B("Connection","XHR received:",JSON.stringify(t)),i(t);break;case u.ErrorCode.TIMEOUT:B("Connection",'RPC "'+e+'" timed out'),a(new X(Y.DEADLINE_EXCEEDED,"Request time out"));break;case u.ErrorCode.HTTP_ERROR:var n=o.getStatus();if(B("Connection",'RPC "'+e+'" failed with status:',n,"response text:",o.getResponseText()),n>0){var r=o.getResponseJson();Array.isArray(r)&&(r=r[0]);var s=null==r?void 0:r.error;if(s&&s.status&&s.message){var c=(l=s.status.toLowerCase().replace(/_/g,"-"),Object.values(Y).indexOf(l)>=0?l:Y.UNKNOWN);a(new X(c,s.message))}else a(new X(Y.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new X(Y.UNAVAILABLE,"Connection failed."));break;default:j()}}finally{B("Connection",'RPC "'+e+'" completed.')}var l});var s=JSON.stringify(r);o.send(t,"POST",s,n,15)})}},{key:"wo",value:function(e,t,n){var r=[this.oo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=(0,u.createWebChannelTransport)(),a=(0,u.getStatEventTarget)(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/".concat(this.databaseId.projectId,"/databases/").concat(this.databaseId.database)},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(o.xmlHttpFactory=new u.FetchXmlHttpFactory({})),this.lo(o.initMessageHeaders,t,n),o.encodeInitMessageHeaders=!0;var s=r.join("");B("Connection","Creating WebChannel: "+s,o);var c=i.createWebChannel(s,o),l=!1,f=!1,h=new To({Hr:function(e){f?B("Connection","Not sending because WebChannel is closed:",e):(l||(B("Connection","Opening WebChannel transport."),c.open(),l=!0),B("Connection","WebChannel sending:",e),c.send(e))},Jr:function(){return c.close()}}),d=function(e,t,n){e.listen(t,function(e){try{n(e)}catch(e){setTimeout(function(){throw e},0)}})};return d(c,u.WebChannel.EventType.OPEN,function(){f||B("Connection","WebChannel transport opened.")}),d(c,u.WebChannel.EventType.CLOSE,function(){f||(f=!0,B("Connection","WebChannel transport closed"),h.io())}),d(c,u.WebChannel.EventType.ERROR,function(e){f||(f=!0,K("Connection","WebChannel transport errored:",e),h.io(new X(Y.UNAVAILABLE,"The operation could not be completed")))}),d(c,u.WebChannel.EventType.MESSAGE,function(e){var t;if(!f){var n=e.data[0];z(!!n);var r=n,i=r.error||(null===(t=r[0])||void 0===t?void 0:t.error);if(i){B("Connection","WebChannel received error:",i);var a=i.status,u=function(e){var t=vr[a];if(void 0!==t)return wr(t)}(),o=i.message;void 0===u&&(u=Y.INTERNAL,o="Unknown error status: "+a+" with message "+i.message),f=!0,h.io(new X(u,o)),c.close()}else B("Connection","WebChannel received:",n),h.ro(n)}}),d(a,u.Event.STAT_EVENT,function(e){e.stat===u.Stat.PROXY?B("Connection","Detected buffering proxy"):e.stat===u.Stat.NOPROXY&&B("Connection","Detected no buffering proxy")}),setTimeout(function(){h.so()},0),h}}]),n}();function _o(){return"undefined"!=typeof window?window:null}function Do(){return"undefined"!=typeof document?document:null}function Ao(e){return new Wr(e,!0)}var Co=function(){function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1.5,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4;C(this,e),this.Hs=t,this.timerId=n,this.mo=r,this.yo=i,this.po=a,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}return P(e,[{key:"reset",value:function(){this.Io=0}},{key:"Ao",value:function(){this.Io=this.po}},{key:"Ro",value:function(e){var t=this;this.cancel();var n=Math.floor(this.Io+this.bo()),r=Math.max(0,Date.now()-this.Eo),i=Math.max(0,n-r);i>0&&B("ExponentialBackoff","Backing off for ".concat(i," ms (base delay: ").concat(this.Io," ms, delay with jitter: ").concat(n," ms, last attempt: ").concat(r," ms ago)")),this.To=this.Hs.enqueueAfterDelay(this.timerId,i,function(){return t.Eo=Date.now(),e()}),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}},{key:"Po",value:function(){null!==this.To&&(this.To.skipDelay(),this.To=null)}},{key:"cancel",value:function(){null!==this.To&&(this.To.cancel(),this.To=null)}},{key:"bo",value:function(){return(Math.random()-.5)*this.Io}}]),e}(),No=function(){function e(t,n,r,i,a,u,o,s){C(this,e),this.Hs=t,this.vo=r,this.Vo=i,this.connection=a,this.authCredentialsProvider=u,this.appCheckCredentialsProvider=o,this.listener=s,this.state=0,this.So=0,this.Do=null,this.Co=null,this.stream=null,this.xo=new Co(t,n)}return P(e,[{key:"No",value:function(){return 1===this.state||5===this.state||this.ko()}},{key:"ko",value:function(){return 2===this.state||3===this.state}},{key:"start",value:function(){4!==this.state?this.auth():this.Oo()}},{key:"stop",value:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.No(),!e.t0){e.next=4;break}return e.next=4,y().awrap(this.close(0));case 4:case"end":return e.stop()}},null,this,null,Promise)}},{key:"Mo",value:function(){this.state=0,this.xo.reset()}},{key:"Fo",value:function(){var e=this;this.ko()&&null===this.Do&&(this.Do=this.Hs.enqueueAfterDelay(this.vo,6e4,function(){return e.$o()}))}},{key:"Bo",value:function(e){this.Lo(),this.stream.send(e)}},{key:"$o",value:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.ko()){e.next=2;break}return e.abrupt("return",this.close(0));case 2:case"end":return e.stop()}},null,this,null,Promise)}},{key:"Lo",value:function(){this.Do&&(this.Do.cancel(),this.Do=null)}},{key:"qo",value:function(){this.Co&&(this.Co.cancel(),this.Co=null)}},{key:"close",value:function(e,t){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return this.Lo(),this.qo(),this.xo.cancel(),this.So++,4!==e?this.xo.reset():t&&t.code===Y.RESOURCE_EXHAUSTED?(G(t.toString()),G("Using maximum backoff delay to prevent overloading the backend."),this.xo.Ao()):t&&t.code===Y.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Uo(),this.stream.close(),this.stream=null),this.state=e,n.next=9,y().awrap(this.listener.Zr(t));case 9:case"end":return n.stop()}},null,this,null,Promise)}},{key:"Uo",value:function(){}},{key:"auth",value:function(){var e=this;this.state=1;var t=this.Ko(this.So),n=this.So;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(function(t){var r=l(t,2),i=r[0],a=r[1];e.So===n&&e.Go(i,a)},function(n){t(function(){var t=new X(Y.UNKNOWN,"Fetching auth token failed: "+n.message);return e.Qo(t)})})}},{key:"Go",value:function(e,t){var n=this,r=this.Ko(this.So);this.stream=this.jo(e,t),this.stream.Yr(function(){r(function(){return n.state=2,n.Co=n.Hs.enqueueAfterDelay(n.Vo,1e4,function(){return n.ko()&&(n.state=3),Promise.resolve()}),n.listener.Yr()})}),this.stream.Zr(function(e){r(function(){return n.Qo(e)})}),this.stream.onMessage(function(e){r(function(){return n.onMessage(e)})})}},{key:"Oo",value:function(){var e=this;this.state=5,this.xo.Ro(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:e.state=0,e.start();case 1:case"end":return t.stop()}},null,null,null,Promise)})}},{key:"Qo",value:function(e){return B("PersistentStream","close with error: ".concat(e)),this.stream=null,this.close(4,e)}},{key:"Ko",value:function(e){var t=this;return function(n){t.Hs.enqueueAndForget(function(){return t.So===e?n():(B("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}}}]),e}(),Po=function(e){p(n,No);var t=g(n);function n(e,r,i,a,u,o){var s;return C(this,n),(s=t.call(this,e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",r,i,a,o)).yt=u,s}return P(n,[{key:"jo",value:function(e,t){return this.connection.wo("Listen",e,t)}},{key:"onMessage",value:function(e){this.xo.reset();var t=ci(this.yt,e),n=function(e){if(!("targetChange"in e))return de.min();var t=e.targetChange;return t.targetIds&&t.targetIds.length?de.min():t.readTime?Zr(t.readTime):de.min()}(e);return this.listener.Wo(t,n)}},{key:"zo",value:function(e){var t={};t.database=ii(this.yt),t.addTarget=function(e,t){var n,r=t.target;return(n=yn(r)?{documents:di(e,r)}:{query:vi(e,r)}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0?n.resumeToken=Yr(e,t.resumeToken):t.snapshotVersion.compareTo(de.min())>0&&(n.readTime=Hr(e,t.snapshotVersion.toTimestamp())),n}(this.yt,e);var n=pi(this.yt,e);n&&(t.labels=n),this.Bo(t)}},{key:"Ho",value:function(e){var t={};t.database=ii(this.yt),t.removeTarget=e,this.Bo(t)}}]),n}(),Lo=function(e){p(n,No);var t=g(n);function n(e,r,i,a,u,o){var s;return C(this,n),(s=t.call(this,e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",r,i,a,o)).yt=u,s.Jo=!1,s}return P(n,[{key:"Yo",get:function(){return this.Jo}},{key:"start",value:function(){this.Jo=!1,this.lastStreamToken=void 0,s(b(n.prototype),"start",this).call(this)}},{key:"Uo",value:function(){this.Jo&&this.Xo([])}},{key:"jo",value:function(e,t){return this.connection.wo("Write",e,t)}},{key:"onMessage",value:function(e){if(z(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Jo){this.xo.reset();var t=hi(e.writeResults,e.commitTime),n=Zr(e.commitTime);return this.listener.Zo(n,t)}return z(!e.writeResults||0===e.writeResults.length),this.Jo=!0,this.listener.tu()}},{key:"eu",value:function(){var e={};e.database=ii(this.yt),this.Bo(e)}},{key:"Xo",value:function(e){var t=this,n={streamToken:this.lastStreamToken,writes:e.map(function(e){return li(t.yt,e)})};this.Bo(n)}}]),n}(),Fo=function(e){p(n,function(){function e(){C(this,e)}return P(e)}());var t=g(n);function n(e,r,i,a){var u;return C(this,n),(u=t.call(this)).authCredentials=e,u.appCheckCredentials=r,u.connection=i,u.yt=a,u.nu=!1,u}return P(n,[{key:"su",value:function(){if(this.nu)throw new X(Y.FAILED_PRECONDITION,"The client has already been terminated.")}},{key:"ao",value:function(e,t,n){var r=this;return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(function(i){var a=l(i,2),u=a[0],o=a[1];return r.connection.ao(e,t,n,u,o)}).catch(function(e){throw"FirebaseError"===e.name?(e.code===Y.UNAUTHENTICATED&&(r.authCredentials.invalidateToken(),r.appCheckCredentials.invalidateToken()),e):new X(Y.UNKNOWN,e.toString())})}},{key:"_o",value:function(e,t,n,r){var i=this;return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(function(a){var u=l(a,2),o=u[0],s=u[1];return i.connection._o(e,t,n,o,s,r)}).catch(function(e){throw"FirebaseError"===e.name?(e.code===Y.UNAUTHENTICATED&&(i.authCredentials.invalidateToken(),i.appCheckCredentials.invalidateToken()),e):new X(Y.UNKNOWN,e.toString())})}},{key:"terminate",value:function(){this.nu=!0}}]),n}();function Mo(e,t){var n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=H(e),r=function(e,t){var n=vi(e,t);return{structuredAggregationQuery:{aggregations:[{count:{},alias:"count_alias"}],structuredQuery:n.structuredQuery},parent:n.parent}}(n.yt,_n(t)),i=r.parent,n.connection.co||delete r.parent,a.next=4,y().awrap(n._o("RunAggregationQuery",i,r,1));case 4:return a.abrupt("return",a.sent.filter(function(e){return!!e.result}).map(function(e){return e.result.aggregateFields}));case 5:case"end":return a.stop()}},null,null,null,Promise)}var Ro=function(){function e(t,n){C(this,e),this.asyncQueue=t,this.onlineStateHandler=n,this.state="Unknown",this.iu=0,this.ru=null,this.ou=!0}return P(e,[{key:"uu",value:function(){var e=this;0===this.iu&&(this.cu("Unknown"),this.ru=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,function(){return e.ru=null,e.au("Backend didn't respond within 10 seconds."),e.cu("Offline"),Promise.resolve()}))}},{key:"hu",value:function(e){"Online"===this.state?this.cu("Unknown"):(this.iu++,this.iu>=1&&(this.lu(),this.au("Connection failed 1 times. Most recent error: ".concat(e.toString())),this.cu("Offline")))}},{key:"set",value:function(e){this.lu(),this.iu=0,"Online"===e&&(this.ou=!1),this.cu(e)}},{key:"cu",value:function(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}},{key:"au",value:function(e){var t="Could not reach Cloud Firestore backend. ".concat(e,"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.");this.ou?(G(t),this.ou=!1):B("OnlineStateTracker",t)}},{key:"lu",value:function(){null!==this.ru&&(this.ru.cancel(),this.ru=null)}}]),e}(),Vo=P(function e(t,n,r,i,a){var u=this;C(this,e),this.localStore=t,this.datastore=n,this.asyncQueue=r,this.remoteSyncer={},this.fu=[],this.du=new Map,this._u=new Set,this.wu=[],this.mu=a,this.mu.Ur(function(e){r.enqueueAndForget(function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=zo(u),!e.t0){e.next=5;break}return B("RemoteStore","Restarting streams for network reachability change."),e.next=5,y().awrap(function(e){var t;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return(t=H(e))._u.add(4),n.next=4,y().awrap(qo(t));case 4:return t.gu.set("Unknown"),t._u.delete(4),n.next=8,y().awrap(Oo(t));case 8:case"end":return n.stop()}},null,null,null,Promise)}(u));case 5:case"end":return e.stop()}},null,null,null,Promise)})}),this.gu=new Ro(r,i)});function Oo(e){var t,n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(!zo(e)){i.next=18;break}t=v(e.wu),i.prev=2,t.s();case 4:if((n=t.n()).done){i.next=10;break}return r=n.value,i.next=8,y().awrap(r(!0));case 8:i.next=4;break;case 10:i.next=15;break;case 12:i.prev=12,i.t0=i.catch(2),t.e(i.t0);case 15:return i.prev=15,t.f(),i.finish(15);case 18:case"end":return i.stop()}},null,null,[[2,12,15,18]],Promise)}function qo(e){var t,n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:t=v(e.wu),i.prev=1,t.s();case 3:if((n=t.n()).done){i.next=9;break}return r=n.value,i.next=7,y().awrap(r(!1));case 7:i.next=3;break;case 9:i.next=14;break;case 11:i.prev=11,i.t0=i.catch(1),t.e(i.t0);case 14:return i.prev=14,t.f(),i.finish(14);case 17:case"end":return i.stop()}},null,null,[[1,11,14,17]],Promise)}function Uo(e,t){var n=H(e);n.du.has(t.targetId)||(n.du.set(t.targetId,t),jo(n)?Qo(n):ls(n).ko()&&Go(n,t))}function Bo(e,t){var n=H(e),r=ls(n);n.du.delete(t),r.ko()&&Ko(n,t),0===n.du.size&&(r.ko()?r.Fo():zo(n)&&n.gu.set("Unknown"))}function Go(e,t){e.yu.Ot(t.targetId),ls(e).zo(t)}function Ko(e,t){e.yu.Ot(t),ls(e).Ho(t)}function Qo(e){e.yu=new Br({getRemoteKeysForTarget:function(t){return e.remoteSyncer.getRemoteKeysForTarget(t)},ne:function(t){return e.du.get(t)||null}}),ls(e).start(),e.gu.uu()}function jo(e){return zo(e)&&!ls(e).No()&&e.du.size>0}function zo(e){return 0===H(e)._u.size}function Wo(e){e.yu=void 0}function Ho(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:e.du.forEach(function(t,n){Go(e,t)});case 1:case"end":return t.stop()}},null,null,null,Promise)}function Yo(e,t){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:Wo(e),jo(e)?(e.gu.hu(t),Qo(e)):e.gu.set("Unknown");case 1:case"end":return n.stop()}},null,null,null,Promise)}function Xo(e,t,n){var r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(e.gu.set("Online"),!(t instanceof qr&&2===t.state&&t.cause)){i.next=13;break}return i.prev=1,i.next=4,y().awrap(function(e,t){var n,r,i,a;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:n=t.cause,r=v(t.targetIds),u.prev=2,r.s();case 4:if((i=r.n()).done){u.next=14;break}if(a=i.value,u.t0=e.du.has(a),!u.t0){u.next=12;break}return u.next=10,y().awrap(e.remoteSyncer.rejectListen(a,n));case 10:e.du.delete(a),e.yu.removeTarget(a);case 12:u.next=4;break;case 14:u.next=19;break;case 16:u.prev=16,u.t1=u.catch(2),r.e(u.t1);case 19:return u.prev=19,r.f(),u.finish(19);case 22:case"end":return u.stop()}},null,null,[[2,16,19,22]],Promise)}(e,t));case 4:i.next=11;break;case 6:return i.prev=6,i.t0=i.catch(1),B("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),i.t0),i.next=11,y().awrap(Zo(e,i.t0));case 11:i.next=29;break;case 13:if(t instanceof Vr?e.yu.Kt(t):t instanceof Or?e.yu.Jt(t):e.yu.jt(t),n.isEqual(de.min())){i.next=29;break}return i.prev=14,i.next=17,y().awrap($u(e.localStore));case 17:if(r=i.sent,i.t1=n.compareTo(r)>=0,!i.t1){i.next=22;break}return i.next=22,y().awrap(function(e,t){var n=e.yu.Zt(t);return n.targetChanges.forEach(function(n,r){if(n.resumeToken.approximateByteSize()>0){var i=e.du.get(r);i&&e.du.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach(function(t){var n=e.du.get(t);if(n){e.du.set(t,n.withResumeToken(tt.EMPTY_BYTE_STRING,n.snapshotVersion)),Ko(e,t);var r=new ia(n.target,t,1,n.sequenceNumber);Go(e,r)}}),e.remoteSyncer.applyRemoteEvent(n)}(e,n));case 22:i.next=29;break;case 24:return i.prev=24,i.t2=i.catch(14),B("RemoteStore","Failed to raise snapshot:",i.t2),i.next=29,y().awrap(Zo(e,i.t2));case 29:case"end":return i.stop()}},null,null,[[1,6],[14,24]],Promise)}function Zo(e,t,n){return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(Oe(t)){r.next=2;break}throw t;case 2:return e._u.add(1),r.next=5,y().awrap(qo(e));case 5:e.gu.set("Offline"),n||(n=function(){return $u(e.localStore)}),e.asyncQueue.enqueueRetryable(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return B("RemoteStore","Retrying IndexedDB access"),t.next=3,y().awrap(n());case 3:return e._u.delete(1),t.next=6,y().awrap(Oo(e));case 6:case"end":return t.stop()}},null,null,null,Promise)});case 8:case"end":return r.stop()}},null,null,null,Promise)}function Jo(e,t){return t().catch(function(n){return Zo(e,n,t)})}function $o(e){var t,n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:t=H(e),n=fs(t),r=t.fu.length>0?t.fu[t.fu.length-1].batchId:-1;case 2:if(!es(t)){a.next=19;break}return a.prev=3,a.next=6,y().awrap(no(t.localStore,r));case 6:if(null!==(i=a.sent)){a.next=10;break}return 0===t.fu.length&&n.Fo(),a.abrupt("break",19);case 10:r=i.batchId,ts(t,i),a.next=17;break;case 13:return a.prev=13,a.t0=a.catch(3),a.next=17,y().awrap(Zo(t,a.t0));case 17:a.next=2;break;case 19:ns(t)&&rs(t);case 20:case"end":return a.stop()}},null,null,[[3,13]],Promise)}function es(e){return zo(e)&&e.fu.length<10}function ts(e,t){e.fu.push(t);var n=fs(e);n.ko()&&n.Yo&&n.Xo(t.mutations)}function ns(e){return zo(e)&&!fs(e).No()&&e.fu.length>0}function rs(e){fs(e).start()}function is(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:fs(e).eu();case 1:case"end":return t.stop()}},null,null,null,Promise)}function as(e){var t,n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:t=fs(e),n=v(e.fu);try{for(n.s();!(r=n.n()).done;)i=r.value,t.Xo(i.mutations)}catch(u){n.e(u)}finally{n.f()}case 3:case"end":return a.stop()}},null,null,null,Promise)}function us(e,t,n){var r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return r=e.fu.shift(),i=na.from(r,t,n),a.next=3,y().awrap(Jo(e,function(){return e.remoteSyncer.applySuccessfulWrite(i)}));case 3:return a.next=5,y().awrap($o(e));case 5:case"end":return a.stop()}},null,null,null,Promise)}function os(e,t){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=t&&fs(e).Yo,!n.t0){n.next=4;break}return n.next=4,y().awrap(function(e,t){var n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(!kr(r=t.code)||r===Y.ABORTED){i.next=7;break}return n=e.fu.shift(),fs(e).Mo(),i.next=5,y().awrap(Jo(e,function(){return e.remoteSyncer.rejectFailedWrite(n.batchId,t)}));case 5:return i.next=7,y().awrap($o(e));case 7:case"end":return i.stop()}},null,null,null,Promise)}(e,t));case 4:ns(e)&&rs(e);case 5:case"end":return n.stop()}},null,null,null,Promise)}function ss(e,t){var n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return(n=H(e)).asyncQueue.verifyOperationInProgress(),B("RemoteStore","RemoteStore received new credentials"),r=zo(n),n._u.add(3),i.next=6,y().awrap(qo(n));case 6:return r&&n.gu.set("Unknown"),i.next=9,y().awrap(n.remoteSyncer.handleCredentialChange(t));case 9:return n._u.delete(3),i.next=12,y().awrap(Oo(n));case 12:case"end":return i.stop()}},null,null,null,Promise)}function cs(e,t){var n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(n=H(e),!t){r.next=7;break}return n._u.delete(2),r.next=5,y().awrap(Oo(n));case 5:r.next=13;break;case 7:if(r.t0=t,r.t0){r.next=13;break}return n._u.add(2),r.next=12,y().awrap(qo(n));case 12:n.gu.set("Unknown");case 13:case"end":return r.stop()}},null,null,null,Promise)}function ls(e){return e.pu||(e.pu=function(e,t,n){var r=H(e);return r.su(),new Po(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(e.datastore,e.asyncQueue,{Yr:Ho.bind(null,e),Zr:Yo.bind(null,e),Wo:Xo.bind(null,e)}),e.wu.push(function(t){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!t){n.next=4;break}e.pu.Mo(),jo(e)?Qo(e):e.gu.set("Unknown"),n.next=7;break;case 4:return n.next=6,y().awrap(e.pu.stop());case 6:Wo(e);case 7:case"end":return n.stop()}},null,null,null,Promise)})),e.pu}function fs(e){return e.Iu||(e.Iu=function(e,t,n){var r=H(e);return r.su(),new Lo(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(e.datastore,e.asyncQueue,{Yr:is.bind(null,e),Zr:os.bind(null,e),tu:as.bind(null,e),Zo:us.bind(null,e)}),e.wu.push(function(t){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!t){n.next=6;break}return e.Iu.Mo(),n.next=4,y().awrap($o(e));case 4:n.next=9;break;case 6:return n.next=8,y().awrap(e.Iu.stop());case 8:e.fu.length>0&&(B("RemoteStore","Stopping write stream with ".concat(e.fu.length," pending writes")),e.fu=[]);case 9:case"end":return n.stop()}},null,null,null,Promise)})),e.Iu}var hs=function(){function e(t,n,r,i,a){C(this,e),this.asyncQueue=t,this.timerId=n,this.targetTimeMs=r,this.op=i,this.removalCallback=a,this.deferred=new Z,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(function(e){})}return P(e,[{key:"start",value:function(e){var t=this;this.timerHandle=setTimeout(function(){return t.handleDelayElapsed()},e)}},{key:"skipDelay",value:function(){return this.handleDelayElapsed()}},{key:"cancel",value:function(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new X(Y.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}},{key:"handleDelayElapsed",value:function(){var e=this;this.asyncQueue.enqueueAndForget(function(){return null!==e.timerHandle?(e.clearTimeout(),e.op().then(function(t){return e.deferred.resolve(t)})):Promise.resolve()})}},{key:"clearTimeout",value:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)})}],[{key:"createAndSchedule",value:function(t,n,r,i,a){var u=new e(t,n,Date.now()+r,i,a);return u.start(r),u}}]),e}();function ds(e,t){if(G("AsyncQueue","".concat(t,": ").concat(e)),Oe(e))return new X(Y.UNAVAILABLE,"".concat(t,": ").concat(e));throw e}var vs=function(){function e(t){C(this,e),this.comparator=t?function(e,n){return t(e,n)||ge.comparator(e.key,n.key)}:function(e,t){return ge.comparator(e.key,t.key)},this.keyedMap=Tr(),this.sortedSet=new en(this.comparator)}return P(e,[{key:"has",value:function(e){return null!=this.keyedMap.get(e)}},{key:"get",value:function(e){return this.keyedMap.get(e)}},{key:"first",value:function(){return this.sortedSet.minKey()}},{key:"last",value:function(){return this.sortedSet.maxKey()}},{key:"isEmpty",value:function(){return this.sortedSet.isEmpty()}},{key:"indexOf",value:function(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}},{key:"size",get:function(){return this.sortedSet.size}},{key:"forEach",value:function(e){this.sortedSet.inorderTraversal(function(t,n){return e(t),!1})}},{key:"add",value:function(e){var t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}},{key:"delete",value:function(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}},{key:"isEqual",value:function(t){if(!(t instanceof e))return!1;if(this.size!==t.size)return!1;for(var n=this.sortedSet.getIterator(),r=t.sortedSet.getIterator();n.hasNext();){var i=n.getNext().key,a=r.getNext().key;if(!i.isEqual(a))return!1}return!0}},{key:"toString",value:function(){var e=[];return this.forEach(function(t){e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}},{key:"copy",value:function(t,n){var r=new e;return r.comparator=this.comparator,r.keyedMap=t,r.sortedSet=n,r}}],[{key:"emptySet",value:function(t){return new e(t.comparator)}}]),e}(),ys=function(){function e(){C(this,e),this.Tu=new en(ge.comparator)}return P(e,[{key:"track",value:function(e){var t=e.doc.key,n=this.Tu.get(t);n?0!==e.type&&3===n.type?this.Tu=this.Tu.insert(t,e):3===e.type&&1!==n.type?this.Tu=this.Tu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Tu=this.Tu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Tu=this.Tu.remove(t):1===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):j():this.Tu=this.Tu.insert(t,e)}},{key:"Eu",value:function(){var e=[];return this.Tu.inorderTraversal(function(t,n){e.push(n)}),e}}]),e}(),ps=function(){function e(t,n,r,i,a,u,o,s,c){C(this,e),this.query=t,this.docs=n,this.oldDocs=r,this.docChanges=i,this.mutatedKeys=a,this.fromCache=u,this.syncStateChanged=o,this.excludesMetadataChanges=s,this.hasCachedResults=c}return P(e,[{key:"hasPendingWrites",get:function(){return!this.mutatedKeys.isEmpty()}},{key:"isEqual",value:function(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Cn(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;var t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(var r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}],[{key:"fromInitialDocuments",value:function(t,n,r,i,a){var u=[];return n.forEach(function(e){u.push({type:0,doc:e})}),new e(t,n,vs.emptySet(n),u,r,i,!0,!1,a)}}]),e}(),ms=P(function e(){C(this,e),this.Au=void 0,this.listeners=[]}),gs=P(function e(){C(this,e),this.queries=new xr(function(e){return Nn(e)},Cn),this.onlineState="Unknown",this.Ru=new Set});function ks(e,t){var n,r,i,a,u;return y().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(n=H(e),r=t.query,i=!1,(a=n.queries.get(r))||(i=!0,a=new ms),!i){o.next=13;break}return o.prev=3,o.next=6,y().awrap(n.onListen(r));case 6:a.Au=o.sent,o.next=13;break;case 9:return o.prev=9,o.t0=o.catch(3),u=ds(o.t0,"Initialization of query '".concat(Pn(t.query),"' failed")),o.abrupt("return",void t.onError(u));case 13:n.queries.set(r,a),a.listeners.push(t),t.bu(n.onlineState),a.Au&&t.Pu(a.Au)&&Is(n);case 14:case"end":return o.stop()}},null,null,[[3,9]],Promise)}function ws(e,t){var n,r,i,a,u;return y().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(n=H(e),r=t.query,i=!1,(a=n.queries.get(r))&&(u=a.listeners.indexOf(t))>=0&&(a.listeners.splice(u,1),i=0===a.listeners.length),!i){o.next=6;break}return o.abrupt("return",(n.queries.delete(r),n.onUnlisten(r)));case 6:case"end":return o.stop()}},null,null,null,Promise)}function xs(e,t){var n,r=H(e),i=!1,a=v(t);try{for(a.s();!(n=a.n()).done;){var u=n.value,o=u.query,s=r.queries.get(o);if(s){var c,l=v(s.listeners);try{for(l.s();!(c=l.n()).done;){c.value.Pu(u)&&(i=!0)}}catch(f){l.e(f)}finally{l.f()}s.Au=u}}}catch(f){a.e(f)}finally{a.f()}i&&Is(r)}function bs(e,t,n){var r=H(e),i=r.queries.get(t);if(i){var a,u=v(i.listeners);try{for(u.s();!(a=u.n()).done;){a.value.onError(n)}}catch(o){u.e(o)}finally{u.f()}}r.queries.delete(t)}function Is(e){e.Ru.forEach(function(e){e.next()})}var Es=function(){function e(t,n,r){C(this,e),this.query=t,this.vu=n,this.Vu=!1,this.Su=null,this.onlineState="Unknown",this.options=r||{}}return P(e,[{key:"Pu",value:function(e){if(!this.options.includeMetadataChanges){var t,n=[],r=v(e.docChanges);try{for(r.s();!(t=r.n()).done;){var i=t.value;3!==i.type&&n.push(i)}}catch(u){r.e(u)}finally{r.f()}e=new ps(e.query,e.docs,e.oldDocs,n,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}var a=!1;return this.Vu?this.Du(e)&&(this.vu.next(e),a=!0):this.Cu(e,this.onlineState)&&(this.xu(e),a=!0),this.Su=e,a}},{key:"onError",value:function(e){this.vu.error(e)}},{key:"bu",value:function(e){this.onlineState=e;var t=!1;return this.Su&&!this.Vu&&this.Cu(this.Su,e)&&(this.xu(this.Su),t=!0),t}},{key:"Cu",value:function(e,t){if(!e.fromCache)return!0;var n="Offline"!==t;return(!this.options.Nu||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}},{key:"Du",value:function(e){if(e.docChanges.length>0)return!0;var t=this.Su&&this.Su.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}},{key:"xu",value:function(e){e=ps.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Vu=!0,this.vu.next(e)}}]),e}(),Ts=function(){function e(t,n){C(this,e),this.ku=t,this.byteLength=n}return P(e,[{key:"Ou",value:function(){return"metadata"in this.ku}}]),e}(),Ss=function(){function e(t){C(this,e),this.yt=t}return P(e,[{key:"Ji",value:function(e){return ti(this.yt,e)}},{key:"Yi",value:function(e){return e.metadata.exists?oi(this.yt,e.document,!1):ln.newNoDocument(this.Ji(e.metadata.name),this.Xi(e.metadata.readTime))}},{key:"Xi",value:function(e){return Zr(e)}}]),e}(),_s=function(){function e(t,n,r){C(this,e),this.Mu=t,this.localStore=n,this.yt=r,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Ds(t)}return P(e,[{key:"Fu",value:function(e){this.progress.bytesLoaded+=e.byteLength;var t=this.progress.documentsLoaded;if(e.ku.namedQuery)this.queries.push(e.ku.namedQuery);else if(e.ku.documentMetadata){this.documents.push({metadata:e.ku.documentMetadata}),e.ku.documentMetadata.exists||++t;var n=ye.fromString(e.ku.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ku.document&&(this.documents[this.documents.length-1].document=e.ku.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}},{key:"$u",value:function(e){var t,n=new Map,r=new Ss(this.yt),i=v(e);try{for(i.s();!(t=i.n()).done;){var a=t.value;if(a.metadata.queries){var u,o=r.Ji(a.metadata.name),s=v(a.metadata.queries);try{for(s.s();!(u=s.n()).done;){var c=u.value,l=(n.get(c)||Pr()).add(o);n.set(c,l)}}catch(f){s.e(f)}finally{s.f()}}}}catch(f){i.e(f)}finally{i.f()}return n}},{key:"complete",value:function(){var e,t,n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.next=2,y().awrap(co(this.localStore,new Ss(this.yt),this.documents,this.Mu.id));case 2:e=a.sent,t=this.$u(this.documents),n=v(this.queries),a.prev=5,n.s();case 7:if((r=n.n()).done){a.next=13;break}return i=r.value,a.next=11,y().awrap(lo(this.localStore,i,t.get(i.name)));case 11:a.next=7;break;case 13:a.next=18;break;case 15:a.prev=15,a.t0=a.catch(5),n.e(a.t0);case 18:return a.prev=18,n.f(),a.finish(18);case 21:return a.abrupt("return",(this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}));case 22:case"end":return a.stop()}},null,this,[[5,15,18,21]],Promise)}}]),e}();function Ds(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}var As=P(function e(t){C(this,e),this.key=t}),Cs=P(function e(t){C(this,e),this.key=t}),Ns=function(){function e(t,n){C(this,e),this.query=t,this.qu=n,this.Uu=null,this.hasCachedResults=!1,this.current=!1,this.Ku=Pr(),this.mutatedKeys=Pr(),this.Gu=Mn(t),this.Qu=new vs(this.Gu)}return P(e,[{key:"ju",get:function(){return this.qu}},{key:"Wu",value:function(e,t){var n=this,r=t?t.zu:new ys,i=t?t.Qu:this.Qu,a=t?t.mutatedKeys:this.mutatedKeys,u=i,o=!1,s="F"===this.query.limitType&&i.size===this.query.limit?i.last():null,c="L"===this.query.limitType&&i.size===this.query.limit?i.first():null;if(e.inorderTraversal(function(e,t){var l=i.get(e),f=Ln(n.query,t)?t:null,h=!!l&&n.mutatedKeys.has(l.key),d=!!f&&(f.hasLocalMutations||n.mutatedKeys.has(f.key)&&f.hasCommittedMutations),v=!1;l&&f?l.data.isEqual(f.data)?h!==d&&(r.track({type:3,doc:f}),v=!0):n.Hu(l,f)||(r.track({type:2,doc:f}),v=!0,(s&&n.Gu(f,s)>0||c&&n.Gu(f,c)<0)&&(o=!0)):!l&&f?(r.track({type:0,doc:f}),v=!0):l&&!f&&(r.track({type:1,doc:l}),v=!0,(s||c)&&(o=!0)),v&&(f?(u=u.add(f),a=d?a.add(e):a.delete(e)):(u=u.delete(e),a=a.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){var l="F"===this.query.limitType?u.last():u.first();u=u.delete(l.key),a=a.delete(l.key),r.track({type:1,doc:l})}return{Qu:u,zu:r,$i:o,mutatedKeys:a}}},{key:"Hu",value:function(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}},{key:"applyChanges",value:function(e,t,n){var r=this,i=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;var a=e.zu.Eu();a.sort(function(e,t){return function(e,t){var n=function(e){switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return j()}};return n(e)-n(t)}(e.type,t.type)||r.Gu(e.doc,t.doc)}),this.Ju(n);var u=t?this.Yu():[],o=0===this.Ku.size&&this.current?1:0,s=o!==this.Uu;return this.Uu=o,0!==a.length||s?{snapshot:new ps(this.query,e.Qu,i,a,e.mutatedKeys,0===o,s,!1,!!n&&n.resumeToken.approximateByteSize()>0),Xu:u}:{Xu:u}}},{key:"bu",value:function(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new ys,mutatedKeys:this.mutatedKeys,$i:!1},!1)):{Xu:[]}}},{key:"Zu",value:function(e){return!this.qu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}},{key:"Ju",value:function(e){var t=this;e&&(e.addedDocuments.forEach(function(e){return t.qu=t.qu.add(e)}),e.modifiedDocuments.forEach(function(e){}),e.removedDocuments.forEach(function(e){return t.qu=t.qu.delete(e)}),this.current=e.current)}},{key:"Yu",value:function(){var e=this;if(!this.current)return[];var t=this.Ku;this.Ku=Pr(),this.Qu.forEach(function(t){e.Zu(t.key)&&(e.Ku=e.Ku.add(t.key))});var n=[];return t.forEach(function(t){e.Ku.has(t)||n.push(new Cs(t))}),this.Ku.forEach(function(e){t.has(e)||n.push(new As(e))}),n}},{key:"tc",value:function(e){this.qu=e.Hi,this.Ku=Pr();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}},{key:"ec",value:function(){return ps.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.Uu,this.hasCachedResults)}}]),e}(),Ps=P(function e(t,n,r){C(this,e),this.query=t,this.targetId=n,this.view=r}),Ls=P(function e(t){C(this,e),this.key=t,this.nc=!1}),Fs=function(){function e(t,n,r,i,a,u){C(this,e),this.localStore=t,this.remoteStore=n,this.eventManager=r,this.sharedClientState=i,this.currentUser=a,this.maxConcurrentLimboResolutions=u,this.sc={},this.ic=new xr(function(e){return Nn(e)},Cn),this.rc=new Map,this.oc=new Set,this.uc=new en(ge.comparator),this.cc=new Map,this.ac=new Nu,this.hc={},this.lc=new Map,this.fc=ou.vn(),this.onlineState="Unknown",this.dc=void 0}return P(e,[{key:"isPrimaryClient",get:function(){return!0===this.dc}}]),e}();function Ms(e,t){var n,r,i,a,u,o;return y().async(function(s){for(;;)switch(s.prev=s.next){case 0:if(n=lc(e),!(a=n.ic.get(t))){s.next=6;break}r=a.targetId,n.sharedClientState.addLocalQueryTarget(r),i=a.view.ec(),s.next=15;break;case 6:return s.next=8,y().awrap(ro(n.localStore,_n(t)));case 8:return u=s.sent,n.isPrimaryClient&&Uo(n.remoteStore,u),o=n.sharedClientState.addLocalQueryTarget(u.targetId),r=u.targetId,s.next=14,y().awrap(Rs(n,t,r,"current"===o,u.resumeToken));case 14:i=s.sent;case 15:return s.abrupt("return",i);case 16:case"end":return s.stop()}},null,null,null,Promise)}function Rs(e,t,n,r,i){var a,u,o,s,c,l;return y().async(function(f){for(;;)switch(f.prev=f.next){case 0:return e._c=function(t,n,r){return function(e,t,n,r){var i,a,u;return y().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(i=t.view.Wu(n),o.t0=i.$i,!o.t0){o.next=6;break}return o.next=5,y().awrap(ao(e.localStore,t.query,!1).then(function(e){var n=e.documents;return t.view.Wu(n,i)}));case 5:i=o.sent;case 6:return a=r&&r.targetChanges.get(t.targetId),u=t.view.applyChanges(i,e.isPrimaryClient,a),o.abrupt("return",(Ys(e,t.targetId,u.Xu),u.snapshot));case 8:case"end":return o.stop()}},null,null,null,Promise)}(e,t,n,r)},f.next=3,y().awrap(ao(e.localStore,t,!0));case 3:return a=f.sent,u=new Ns(t,a.Hi),o=u.Wu(a.documents),s=Rr.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),c=u.applyChanges(o,e.isPrimaryClient,s),Ys(e,n,c.Xu),l=new Ps(t,n,u),f.abrupt("return",(e.ic.set(t,l),e.rc.has(n)?e.rc.get(n).push(t):e.rc.set(n,[t]),c.snapshot));case 11:case"end":return f.stop()}},null,null,null,Promise)}function Vs(e,t){var n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:if(n=H(e),r=n.ic.get(t),!((i=n.rc.get(r.targetId)).length>1)){a.next=3;break}return a.abrupt("return",(n.rc.set(r.targetId,i.filter(function(e){return!Cn(e,t)})),void n.ic.delete(t)));case 3:if(!n.isPrimaryClient){a.next=11;break}if(n.sharedClientState.removeLocalQueryTarget(r.targetId),a.t0=n.sharedClientState.isActiveQueryTarget(r.targetId),a.t0){a.next=9;break}return a.next=9,y().awrap(io(n.localStore,r.targetId,!1).then(function(){n.sharedClientState.clearQueryState(r.targetId),Bo(n.remoteStore,r.targetId),Ws(n,r.targetId)}).catch(Pe));case 9:a.next=14;break;case 11:return Ws(n,r.targetId),a.next=14,y().awrap(io(n.localStore,r.targetId,!0));case 14:case"end":return a.stop()}},null,null,null,Promise)}function Os(e,t,n){var r,i,a;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:return r=fc(e),u.prev=1,u.next=4,y().awrap(function(e,t){var n,r,i=H(e),a=he.now(),u=t.reduce(function(e,t){return e.add(t.key)},Pr());return i.persistence.runTransaction("Locally write mutations","readwrite",function(e){var o=Ir(),s=Pr();return i.Gi.getEntries(e,u).next(function(e){(o=e).forEach(function(e,t){t.isValidDocument()||(s=s.add(e))})}).next(function(){return i.localDocuments.getOverlayedDocuments(e,o)}).next(function(r){n=r;var u,o=[],s=v(t);try{for(s.s();!(u=s.n()).done;){var c=u.value,l=or(c,n.get(c.key).overlayedDocument);null!=l&&o.push(new lr(c.key,l,cn(l.value.mapValue),tr.exists(!0)))}}catch(f){s.e(f)}finally{s.f()}return i.mutationQueue.addMutationBatch(e,a,o,t)}).next(function(t){r=t;var a=t.applyToLocalDocumentSet(n,s);return i.documentOverlayCache.saveOverlays(e,t.batchId,a)})}).then(function(){return{batchId:r.batchId,changes:Sr(n)}})}(r.localStore,t));case 4:return i=u.sent,r.sharedClientState.addPendingMutation(i.batchId),function(e,t,n){var r=e.hc[e.currentUser.toKey()];r||(r=new en(ce)),r=r.insert(t,n),e.hc[e.currentUser.toKey()]=r}(r,i.batchId,n),u.next=9,y().awrap(Js(r,i.changes));case 9:return u.next=11,y().awrap($o(r.remoteStore));case 11:u.next=17;break;case 13:u.prev=13,u.t0=u.catch(1),a=ds(u.t0,"Failed to persist write"),n.reject(a);case 17:case"end":return u.stop()}},null,null,[[1,13]],Promise)}function qs(e,t){var n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return n=H(e),i.prev=1,i.next=4,y().awrap(eo(n.localStore,t));case 4:return r=i.sent,t.targetChanges.forEach(function(e,t){var r=n.cc.get(t);r&&(z(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.nc=!0:e.modifiedDocuments.size>0?z(r.nc):e.removedDocuments.size>0&&(z(r.nc),r.nc=!1))}),i.next=8,y().awrap(Js(n,r,t));case 8:i.next=14;break;case 10:return i.prev=10,i.t0=i.catch(1),i.next=14,y().awrap(Pe(i.t0));case 14:case"end":return i.stop()}},null,null,[[1,10]],Promise)}function Us(e,t,n){var r=H(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){var i=[];r.ic.forEach(function(e,n){var r=n.view.bu(t);r.snapshot&&i.push(r.snapshot)}),function(e,t){var n=H(e);n.onlineState=t;var r=!1;n.queries.forEach(function(e,n){var i,a=v(n.listeners);try{for(a.s();!(i=a.n()).done;){i.value.bu(t)&&(r=!0)}}catch(u){a.e(u)}finally{a.f()}}),r&&Is(n)}(r.eventManager,t),i.length&&r.sc.Wo(i),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}function Bs(e,t,n){var r,i,a,u,o,s;return y().async(function(c){for(;;)switch(c.prev=c.next){case 0:if((r=H(e)).sharedClientState.updateQueryState(t,"rejected",n),i=r.cc.get(t),!(a=i&&i.key)){c.next=14;break}return u=(u=new en(ge.comparator)).insert(a,ln.newNoDocument(a,de.min())),o=Pr().add(a),s=new Mr(de.min(),new Map,new rn(ce),u,o),c.next=9,y().awrap(qs(r,s));case 9:r.uc=r.uc.remove(a),r.cc.delete(t),Zs(r),c.next=16;break;case 14:return c.next=16,y().awrap(io(r.localStore,t,!1).then(function(){return Ws(r,t,n)}).catch(Pe));case 16:case"end":return c.stop()}},null,null,null,Promise)}function Gs(e,t){var n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=H(e),r=t.batch.batchId,a.prev=1,a.next=4,y().awrap(Ju(n.localStore,t));case 4:return i=a.sent,zs(n,r,null),js(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),a.next=10,y().awrap(Js(n,i));case 10:a.next=16;break;case 12:return a.prev=12,a.t0=a.catch(1),a.next=16,y().awrap(Pe(a.t0));case 16:case"end":return a.stop()}},null,null,[[1,12]],Promise)}function Ks(e,t,n){var r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return r=H(e),a.prev=1,a.next=4,y().awrap(function(e,t){var n=H(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",function(e){var r;return n.mutationQueue.lookupMutationBatch(e,t).next(function(t){return z(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)}).next(function(){return n.mutationQueue.performConsistencyCheck(e)}).next(function(){return n.documentOverlayCache.removeOverlaysForBatchId(e,r,t)}).next(function(){return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r)}).next(function(){return n.localDocuments.getDocuments(e,r)})})}(r.localStore,t));case 4:return i=a.sent,zs(r,t,n),js(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),a.next=10,y().awrap(Js(r,i));case 10:a.next=16;break;case 12:return a.prev=12,a.t0=a.catch(1),a.next=16,y().awrap(Pe(a.t0));case 16:case"end":return a.stop()}},null,null,[[1,12]],Promise)}function Qs(e,t){var n,r,i,a;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:return zo((n=H(e)).remoteStore)||B("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),u.prev=2,u.next=5,y().awrap(function(e){var t=H(n.localStore);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",function(e){return t.mutationQueue.getHighestUnacknowledgedBatchId(e)})}());case 5:if(-1!==(r=u.sent)){u.next=8;break}return u.abrupt("return",void t.resolve());case 8:(i=n.lc.get(r)||[]).push(t),n.lc.set(r,i),u.next=16;break;case 12:u.prev=12,u.t0=u.catch(2),a=ds(u.t0,"Initialization of waitForPendingWrites() operation failed"),t.reject(a);case 16:case"end":return u.stop()}},null,null,[[2,12]],Promise)}function js(e,t){(e.lc.get(t)||[]).forEach(function(e){e.resolve()}),e.lc.delete(t)}function zs(e,t,n){var r=H(e),i=r.hc[r.currentUser.toKey()];if(i){var a=i.get(t);a&&(n?a.reject(n):a.resolve(),i=i.remove(t)),r.hc[r.currentUser.toKey()]=i}}function Ws(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;e.sharedClientState.removeLocalQueryTarget(t);var r,i=v(e.rc.get(t));try{for(i.s();!(r=i.n()).done;){var a=r.value;e.ic.delete(a),n&&e.sc.wc(a,n)}}catch(u){i.e(u)}finally{i.f()}e.rc.delete(t),e.isPrimaryClient&&e.ac.ls(t).forEach(function(t){e.ac.containsKey(t)||Hs(e,t)})}function Hs(e,t){e.oc.delete(t.path.canonicalString());var n=e.uc.get(t);null!==n&&(Bo(e.remoteStore,n),e.uc=e.uc.remove(t),e.cc.delete(n),Zs(e))}function Ys(e,t,n){var r,i=v(n);try{for(i.s();!(r=i.n()).done;){var a=r.value;a instanceof As?(e.ac.addReference(a.key,t),Xs(e,a)):a instanceof Cs?(B("SyncEngine","Document no longer in limbo: "+a.key),e.ac.removeReference(a.key,t),e.ac.containsKey(a.key)||Hs(e,a.key)):j()}}catch(u){i.e(u)}finally{i.f()}}function Xs(e,t){var n=t.key,r=n.path.canonicalString();e.uc.get(n)||e.oc.has(r)||(B("SyncEngine","New document in limbo: "+n),e.oc.add(r),Zs(e))}function Zs(e){for(;e.oc.size>0&&e.uc.size<e.maxConcurrentLimboResolutions;){var t=e.oc.values().next().value;e.oc.delete(t);var n=new ge(ye.fromString(t)),r=e.fc.next();e.cc.set(r,new Ls(n)),e.uc=e.uc.insert(n,r),Uo(e.remoteStore,new ia(_n(xn(n.path)),r,2,je.at))}}function Js(e,t,n){var r,i,a,u;return y().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(r=H(e),i=[],a=[],u=[],o.t0=r.ic.isEmpty(),o.t0){o.next=9;break}return r.ic.forEach(function(e,o){u.push(r._c(o,t,n).then(function(e){if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(o.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){i.push(e);var t=Wu.Ci(o.targetId,e);a.push(t)}}))}),o.next=6,y().awrap(Promise.all(u));case 6:return r.sc.Wo(i),o.next=9,y().awrap(function(e,t){var n,r,i,a,u,o,s,c;return y().async(function(l){for(;;)switch(l.prev=l.next){case 0:return n=H(e),l.prev=1,l.next=4,y().awrap(n.persistence.runTransaction("notifyLocalViewChanges","readwrite",function(e){return Le.forEach(t,function(t){return Le.forEach(t.Si,function(r){return n.persistence.referenceDelegate.addReference(e,t.targetId,r)}).next(function(){return Le.forEach(t.Di,function(r){return n.persistence.referenceDelegate.removeReference(e,t.targetId,r)})})})}));case 4:l.next=11;break;case 6:if(l.prev=6,l.t0=l.catch(1),Oe(l.t0)){l.next=10;break}throw l.t0;case 10:B("LocalStore","Failed to update sequence numbers: "+l.t0);case 11:r=v(t);try{for(r.s();!(i=r.n()).done;)a=i.value,u=a.targetId,a.fromCache||(o=n.qi.get(u),s=o.snapshotVersion,c=o.withLastLimboFreeSnapshotVersion(s),n.qi=n.qi.insert(u,c))}catch(f){r.e(f)}finally{r.f()}case 13:case"end":return l.stop()}},null,null,[[1,6]],Promise)}(r.localStore,a));case 9:case"end":return o.stop()}},null,null,null,Promise)}function $s(e,t){var n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:if((n=H(e)).currentUser.isEqual(t)){i.next=11;break}return B("SyncEngine","User change. New user:",t.toKey()),i.next=5,y().awrap(Zu(n.localStore,t));case 5:return r=i.sent,n.currentUser=t,function(e,t){e.lc.forEach(function(e){e.forEach(function(e){e.reject(new X(Y.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.lc.clear()}(n),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),i.next=11,y().awrap(Js(n,r.ji));case 11:case"end":return i.stop()}},null,null,null,Promise)}function ec(e,t){var n=H(e),r=n.cc.get(t);if(r&&r.nc)return Pr().add(r.key);var i=Pr(),a=n.rc.get(t);if(!a)return i;var u,o=v(a);try{for(o.s();!(u=o.n()).done;){var s=u.value,c=n.ic.get(s);i=i.unionWith(c.view.ju)}}catch(l){o.e(l)}finally{o.f()}return i}function tc(e,t){var n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=H(e),a.next=3,y().awrap(ao(n.localStore,t.query,!0));case 3:return r=a.sent,i=t.view.tc(r),a.abrupt("return",(n.isPrimaryClient&&Ys(n,t.targetId,i.Xu),i));case 6:case"end":return a.stop()}},null,null,null,Promise)}function nc(e,t){var n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return n=H(e),r.abrupt("return",oo(n.localStore,t).then(function(e){return Js(n,e)}));case 2:case"end":return r.stop()}},null,null,null,Promise)}function rc(e,t,n,r){var i,a;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:return i=H(e),u.next=3,y().awrap(function(e,t){var n=H(e),r=H(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",function(e){return r.Tn(e,t).next(function(t){return t?n.localDocuments.getDocuments(e,t):Le.resolve(null)})})}(i.localStore,t));case 3:if(null===(a=u.sent)){u.next=15;break}if("pending"!==n){u.next=10;break}return u.next=8,y().awrap($o(i.remoteStore));case 8:u.next=11;break;case 10:"acknowledged"===n||"rejected"===n?(zs(i,t,r||null),js(i,t),function(e,t){H(H(e).mutationQueue).An(t)}(i.localStore,t)):j();case 11:return u.next=13,y().awrap(Js(i,a));case 13:u.next=16;break;case 15:B("SyncEngine","Cannot apply mutation batch with id: "+t);case 16:case"end":return u.stop()}},null,null,null,Promise)}function ic(e,t){var n,r,i,a,u,o,s,c;return y().async(function(l){for(;;)switch(l.prev=l.next){case 0:if(lc(n=H(e)),fc(n),!0!==t||!0===n.dc){l.next=13;break}return r=n.sharedClientState.getAllActiveQueryTargets(),l.next=5,y().awrap(ac(n,r.toArray()));case 5:return i=l.sent,n.dc=!0,l.next=9,y().awrap(cs(n.remoteStore,!0));case 9:a=v(i);try{for(a.s();!(u=a.n()).done;)o=u.value,Uo(n.remoteStore,o)}catch(f){a.e(f)}finally{a.f()}l.next=25;break;case 13:if(!1!==t||!1===n.dc){l.next=25;break}return s=[],c=Promise.resolve(),n.rc.forEach(function(e,t){n.sharedClientState.isLocalQueryTarget(t)?s.push(t):c=c.then(function(){return Ws(n,t),io(n.localStore,t,!0)}),Bo(n.remoteStore,t)}),l.next=19,y().awrap(c);case 19:return l.next=21,y().awrap(ac(n,s));case 21:return function(e){var t=H(n);t.cc.forEach(function(e,n){Bo(t.remoteStore,n)}),t.ac.fs(),t.cc=new Map,t.uc=new en(ge.comparator)}(),n.dc=!1,l.next=25,y().awrap(cs(n.remoteStore,!1));case 25:case"end":return l.stop()}},null,null,null,Promise)}function ac(e,t,n){var r,i,a,u,o,s,c,l,f,h,d,p,m,g;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:r=H(e),i=[],a=[],u=v(t),n.prev=2,u.s();case 4:if((o=u.n()).done){n.next=45;break}if(s=o.value,c=void 0,!(l=r.rc.get(s))||0===l.length){n.next=34;break}return n.next=11,y().awrap(ro(r.localStore,_n(l[0])));case 11:c=n.sent,f=v(l),n.prev=13,f.s();case 15:if((h=f.n()).done){n.next=24;break}return d=h.value,p=r.ic.get(d),n.next=20,y().awrap(tc(r,p));case 20:(m=n.sent).snapshot&&a.push(m.snapshot);case 22:n.next=15;break;case 24:n.next=29;break;case 26:n.prev=26,n.t0=n.catch(13),f.e(n.t0);case 29:return n.prev=29,f.f(),n.finish(29);case 32:n.next=42;break;case 34:return n.next=36,y().awrap(uo(r.localStore,s));case 36:return g=n.sent,n.next=39,y().awrap(ro(r.localStore,g));case 39:return c=n.sent,n.next=42,y().awrap(Rs(r,uc(g),s,!1,c.resumeToken));case 42:i.push(c);case 43:n.next=4;break;case 45:n.next=50;break;case 47:n.prev=47,n.t1=n.catch(2),u.e(n.t1);case 50:return n.prev=50,u.f(),n.finish(50);case 53:return n.abrupt("return",(r.sc.Wo(a),i));case 54:case"end":return n.stop()}},null,null,[[2,47,50,53],[13,26,29,32]],Promise)}function uc(e){return wn(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function oc(e){var t=H(e);return H(H(t.localStore).persistence).vi()}function sc(e,t,n,r){var i,a,u,o;return y().async(function(s){for(;;)switch(s.prev=s.next){case 0:if(!(i=H(e)).dc){s.next=3;break}return s.abrupt("return",void B("SyncEngine","Ignoring unexpected query state notification."));case 3:if(!((a=i.rc.get(t))&&a.length>0)){s.next=20;break}s.t0=n,s.next="current"===s.t0?8:"not-current"===s.t0?8:"rejected"===s.t0?15:19;break;case 8:return s.next=10,y().awrap(oo(i.localStore,Fn(a[0])));case 10:return u=s.sent,o=Mr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,tt.EMPTY_BYTE_STRING),s.next=14,y().awrap(Js(i,u,o));case 14:return s.abrupt("break",20);case 15:return s.next=17,y().awrap(io(i.localStore,t,!0));case 17:return Ws(i,t,r),s.abrupt("break",20);case 19:j();case 20:case"end":return s.stop()}},null,null,null,Promise)}function cc(e,t,n){var r,i,a,u,o,s,c,l,f;return y().async(function(h){for(;;)switch(h.prev=h.next){case 0:if(!(r=lc(e)).dc){h.next=46;break}i=v(t),h.prev=3,i.s();case 5:if((a=i.n()).done){h.next=21;break}if(u=a.value,!r.rc.has(u)){h.next=10;break}return B("SyncEngine","Adding an already active target "+u),h.abrupt("continue",19);case 10:return h.next=12,y().awrap(uo(r.localStore,u));case 12:return o=h.sent,h.next=15,y().awrap(ro(r.localStore,o));case 15:return s=h.sent,h.next=18,y().awrap(Rs(r,uc(o),s.targetId,!1,s.resumeToken));case 18:Uo(r.remoteStore,s);case 19:h.next=5;break;case 21:h.next=26;break;case 23:h.prev=23,h.t0=h.catch(3),i.e(h.t0);case 26:return h.prev=26,i.f(),h.finish(26);case 29:c=v(n),h.prev=30,f=function(){var e;return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(e=l.value,t.t0=r.rc.has(e),!t.t0){t.next=5;break}return t.next=5,y().awrap(io(r.localStore,e,!1).then(function(){Bo(r.remoteStore,e),Ws(r,e)}).catch(Pe));case 5:case"end":return t.stop()}},null,null,null,Promise)},c.s();case 33:if((l=c.n()).done){h.next=38;break}return h.next=36,y().awrap(f());case 36:h.next=33;break;case 38:h.next=43;break;case 40:h.prev=40,h.t1=h.catch(30),c.e(h.t1);case 43:return h.prev=43,c.f(),h.finish(43);case 46:case"end":return h.stop()}},null,null,[[3,23,26,29],[30,40,43,46]],Promise)}function lc(e){var t=H(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=qs.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=ec.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Bs.bind(null,t),t.sc.Wo=xs.bind(null,t.eventManager),t.sc.wc=bs.bind(null,t.eventManager),t}function fc(e){var t=H(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Gs.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Ks.bind(null,t),t}function hc(e,t,n){var r=H(e);(function(e,t,n){var r,i,a,u,o;return y().async(function(s){for(;;)switch(s.prev=s.next){case 0:return s.prev=0,s.next=3,y().awrap(t.getMetadata());case 3:return r=s.sent,s.next=6,y().awrap(function(e,t){var n=H(e),r=Zr(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",function(e){return n.Ns.getBundleMetadata(e,t.id)}).then(function(e){return!!e&&e.createTime.compareTo(r)>=0})}(e.localStore,r));case 6:if(!s.sent){s.next=11;break}return s.next=9,y().awrap(t.close());case 9:return n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),s.abrupt("return",Promise.resolve(new Set));case 11:return n._updateProgress(Ds(r)),i=new _s(r,e.localStore,t.yt),s.next=15,y().awrap(t.mc());case 15:a=s.sent;case 16:if(!a){s.next=26;break}return s.next=19,y().awrap(i.Fu(a));case 19:return(u=s.sent)&&n._updateProgress(u),s.next=23,y().awrap(t.mc());case 23:a=s.sent;case 24:s.next=16;break;case 26:return s.next=28,y().awrap(i.complete());case 28:return o=s.sent,s.next=31,y().awrap(Js(e,o.Lu,void 0));case 31:return s.next=33,y().awrap(function(e,t){var n=H(e);return n.persistence.runTransaction("Save bundle","readwrite",function(e){return n.Ns.saveBundleMetadata(e,t)})}(e.localStore,r));case 33:return n._completeWith(o.progress),s.abrupt("return",Promise.resolve(o.Bu));case 37:return s.prev=37,s.t0=s.catch(0),s.abrupt("return",(K("SyncEngine","Loading bundle failed with ".concat(s.t0)),n._failWith(s.t0),Promise.resolve(new Set)));case 40:case"end":return s.stop()}},null,null,[[0,37]],Promise)})(r,t,n).then(function(e){r.sharedClientState.notifyBundleLoaded(e)})}var dc=function(){function e(){C(this,e),this.synchronizeTabs=!1}return P(e,[{key:"initialize",value:function(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return this.yt=Ao(e.databaseInfo.databaseId),this.sharedClientState=this.gc(e),this.persistence=this.yc(e),t.next=5,y().awrap(this.persistence.start());case 5:this.localStore=this.Ic(e),this.gcScheduler=this.Tc(e,this.localStore),this.indexBackfillerScheduler=this.Ec(e,this.localStore);case 8:case"end":return t.stop()}},null,this,null,Promise)}},{key:"Tc",value:function(e,t){return null}},{key:"Ec",value:function(e,t){return null}},{key:"Ic",value:function(e){return Xu(this.persistence,new Hu,e.initialUser,this.yt)}},{key:"yc",value:function(e){return new Vu(qu.Bs,this.yt)}},{key:"gc",value:function(e){return new xo}},{key:"terminate",value:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return this.gcScheduler&&this.gcScheduler.stop(),e.next=3,y().awrap(this.sharedClientState.shutdown());case 3:return e.next=5,y().awrap(this.persistence.shutdown());case 5:case"end":return e.stop()}},null,this,null,Promise)}}]),e}(),vc=function(e){p(n,dc);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this)).Ac=e,a.cacheSizeBytes=r,a.forceOwnership=i,a.synchronizeTabs=!1,a}return P(n,[{key:"initialize",value:function(e){var t=this;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,y().awrap(s(b(n.prototype),"initialize",this).call(this,e));case 2:return r.next=4,y().awrap(this.Ac.initialize(this,e));case 4:return r.next=6,y().awrap(fc(this.Ac.syncEngine));case 6:return r.next=8,y().awrap($o(this.Ac.remoteStore));case 8:return r.next=10,y().awrap(this.persistence.li(function(){return t.gcScheduler&&!t.gcScheduler.started&&t.gcScheduler.start(),t.indexBackfillerScheduler&&!t.indexBackfillerScheduler.started&&t.indexBackfillerScheduler.start(),Promise.resolve()}));case 10:case"end":return r.stop()}},null,this,null,Promise)}},{key:"Ic",value:function(e){return Xu(this.persistence,new Hu,e.initialUser,this.yt)}},{key:"Tc",value:function(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new vu(n,e.asyncQueue,t)}},{key:"Ec",value:function(e,t){var n=new Qe(t,this.persistence);return new Ke(e.asyncQueue,n)}},{key:"yc",value:function(e){var t=zu(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?$a.withCacheSize(this.cacheSizeBytes):$a.DEFAULT;return new Ku(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,_o(),Do(),this.yt,this.sharedClientState,!!this.forceOwnership)}},{key:"gc",value:function(e){return new xo}}]),n}(),yc=function(e){p(n,vc);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e,r,!1)).Ac=e,i.cacheSizeBytes=r,i.synchronizeTabs=!0,i}return P(n,[{key:"initialize",value:function(e){var t,r=this;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,y().awrap(s(b(n.prototype),"initialize",this).call(this,e));case 2:if(t=this.Ac.syncEngine,i.t0=this.sharedClientState instanceof wo,!i.t0){i.next=8;break}return this.sharedClientState.syncEngine={Fr:rc.bind(null,t),$r:sc.bind(null,t),Br:cc.bind(null,t),vi:oc.bind(null,t),Mr:nc.bind(null,t)},i.next=8,y().awrap(this.sharedClientState.start());case 8:return i.next=10,y().awrap(this.persistence.li(function(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,y().awrap(ic(r.Ac.syncEngine,e));case 2:r.gcScheduler&&(e&&!r.gcScheduler.started?r.gcScheduler.start():e||r.gcScheduler.stop()),r.indexBackfillerScheduler&&(e&&!r.indexBackfillerScheduler.started?r.indexBackfillerScheduler.start():e||r.indexBackfillerScheduler.stop());case 4:case"end":return t.stop()}},null,null,null,Promise)}));case 10:case"end":return i.stop()}},null,this,null,Promise)}},{key:"gc",value:function(e){var t=_o();if(!wo.C(t))throw new X(Y.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=zu(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new wo(t,e.asyncQueue,n,e.clientId,e.initialUser)}}]),n}(),pc=function(){function e(){C(this,e)}return P(e,[{key:"initialize",value:function(e,t){var n=this;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(r.t0=this.localStore,r.t0){r.next=12;break}return 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=function(e){return Us(n.syncEngine,e,1)},this.remoteStore.remoteSyncer.handleCredentialChange=$s.bind(null,this.syncEngine),r.next=12,y().awrap(cs(this.remoteStore,this.syncEngine.isPrimaryClient));case 12:case"end":return r.stop()}},null,this,null,Promise)}},{key:"createEventManager",value:function(e){return new gs}},{key:"createDatastore",value:function(e){var t,n=Ao(e.databaseInfo.databaseId),r=(t=e.databaseInfo,new So(t));return function(e,t,n,r){return new Fo(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,r,n)}},{key:"createRemoteStore",value:function(e){var t,n,r,i,a,u=this;return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=function(e){return Us(u.syncEngine,e,0)},a=Io.C()?new Io:new bo,new Vo(t,n,r,i,a)}},{key:"createSyncEngine",value:function(e,t){return function(e,t,n,r,i,a,u){var o=new Fs(e,t,n,r,i,a);return u&&(o.dc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}},{key:"terminate",value:function(){return e=this.remoteStore,y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return t=H(e),B("RemoteStore","RemoteStore shutting down."),t._u.add(5),n.next=5,y().awrap(qo(t));case 5:t.mu.shutdown(),t.gu.set("Unknown");case 7:case"end":return n.stop()}},null,null,null,Promise);var e,t}}]),e}();function mc(e,t,n){if(!n)throw new X(Y.INVALID_ARGUMENT,"Function ".concat(e,"() cannot be called with an empty ").concat(t,"."))}function gc(e,t,n,r){if(!0===t&&!0===r)throw new X(Y.INVALID_ARGUMENT,"".concat(e," and ").concat(n," cannot be used together."))}function kc(e){if(!ge.isDocumentKey(e))throw new X(Y.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but ".concat(e," has ").concat(e.length,"."))}function wc(e){if(ge.isDocumentKey(e))throw new X(Y.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but ".concat(e," has ").concat(e.length,"."))}function xc(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e="".concat(e.substring(0,20),"...")),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==A(e)){if(e instanceof Array)return"an array";var t=function(e){return e.constructor?e.constructor.name:null}(e);return t?"a custom ".concat(t," object"):"an object"}return"function"==typeof e?"a function":j()}function bc(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new X(Y.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=xc(e);throw new X(Y.INVALID_ARGUMENT,"Expected type '".concat(t.name,"', but it was: ").concat(n))}return e}function Ic(e,t){if(t<=0)throw new X(Y.INVALID_ARGUMENT,"Function ".concat(e,"() requires a positive number, but it was: ").concat(t,"."))}var Ec=new Map,Tc=function(){function e(t){var n;if(C(this,e),void 0===t.host){if(void 0!==t.ssl)throw new X(Y.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=t.host,this.ssl=null===(n=t.ssl)||void 0===n||n;if(this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,void 0===t.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new X(Y.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=t.cacheSizeBytes}this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.useFetchStreams=!!t.useFetchStreams,gc("experimentalForceLongPolling",t.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",t.experimentalAutoDetectLongPolling)}return P(e,[{key:"isEqual",value:function(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}}]),e}(),Sc=function(){function e(t,n,r,i){C(this,e),this._authCredentials=t,this._appCheckCredentials=n,this._databaseId=r,this._app=i,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Tc({}),this._settingsFrozen=!1}return P(e,[{key:"app",get:function(){if(!this._app)throw new X(Y.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}},{key:"_initialized",get:function(){return this._settingsFrozen}},{key:"_terminated",get:function(){return void 0!==this._terminateTask}},{key:"_setSettings",value:function(e){if(this._settingsFrozen)throw new X(Y.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 Tc(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new $;switch(e.type){case"gapi":var t=e.client;return new re(t,e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new X(Y.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}},{key:"_getSettings",value:function(){return this._settings}},{key:"_freezeSettings",value:function(){return this._settingsFrozen=!0,this._settings}},{key:"_delete",value:function(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}},{key:"toJSON",value:function(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}},{key:"_terminate",value:function(){return e=this,(t=Ec.get(e))&&(B("ComponentProvider","Removing Datastore"),Ec.delete(e),t.terminate()),Promise.resolve();var e,t}}]),e}();function _c(e,t,n){var r,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},u=(e=bc(e,Sc))._getSettings();if("firestore.googleapis.com"!==u.host&&u.host!==t&&K("Host has been set in both settings() and useEmulator(), emulator host will be used"),e._setSettings(Object.assign(Object.assign({},u),{host:"".concat(t,":").concat(n),ssl:!1})),i.mockUserToken){var o,s;if("string"==typeof i.mockUserToken)o=i.mockUserToken,s=R.MOCK_USER;else{o=(0,a.createMockUserToken)(i.mockUserToken,null===(r=e._app)||void 0===r?void 0:r.options.projectId);var c=i.mockUserToken.sub||i.mockUserToken.user_id;if(!c)throw new X(Y.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");s=new R(c)}e._authCredentials=new ee(new J(o,s))}}var Dc=function(){function e(t,n,r){C(this,e),this.converter=n,this._key=r,this.type="document",this.firestore=t}return P(e,[{key:"_path",get:function(){return this._key.path}},{key:"id",get:function(){return this._key.path.lastSegment()}},{key:"path",get:function(){return this._key.path.canonicalString()}},{key:"parent",get:function(){return new Cc(this.firestore,this.converter,this._key.path.popLast())}},{key:"withConverter",value:function(t){return new e(this.firestore,t,this._key)}}]),e}();exports.DocumentReference=Dc;var Ac=function(){function e(t,n,r){C(this,e),this.converter=n,this._query=r,this.type="query",this.firestore=t}return P(e,[{key:"withConverter",value:function(t){return new e(this.firestore,t,this._query)}}]),e}();exports.Query=Ac;var Cc=function(e){p(n,Ac);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this,e,r,xn(i)))._path=i,a.type="collection",a}return P(n,[{key:"id",get:function(){return this._query.path.lastSegment()}},{key:"path",get:function(){return this._query.path.canonicalString()}},{key:"parent",get:function(){var e=this._path.popLast();return e.isEmpty()?null:new Dc(this.firestore,null,new ge(e))}},{key:"withConverter",value:function(e){return new n(this.firestore,e,this._path)}}]),n}();function Nc(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=(0,a.getModularInstance)(e),mc("collection","path",t),e instanceof Sc){var u=ye.fromString.apply(ye,[t].concat(r));return wc(u),new Cc(e,null,u)}if(!(e instanceof Dc||e instanceof Cc))throw new X(Y.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");var o=e._path.child(ye.fromString.apply(ye,[t].concat(r)));return wc(o),new Cc(e.firestore,null,o)}function Pc(e,t){if(e=bc(e,Sc),mc("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new X(Y.INVALID_ARGUMENT,"Invalid collection ID '".concat(t,"' passed to function collectionGroup(). Collection IDs must not contain '/'."));return new Ac(e,null,function(e){return new kn(ye.emptyPath(),e)}(t))}function Lc(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=(0,a.getModularInstance)(e),1===arguments.length&&(t=se.R()),mc("doc","path",t),e instanceof Sc){var u=ye.fromString.apply(ye,[t].concat(r));return kc(u),new Dc(e,null,new ge(u))}if(!(e instanceof Dc||e instanceof Cc))throw new X(Y.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");var o=e._path.child(ye.fromString.apply(ye,[t].concat(r)));return kc(o),new Dc(e.firestore,e instanceof Cc?e.converter:null,new ge(o))}function Fc(e,t){return e=(0,a.getModularInstance)(e),t=(0,a.getModularInstance)(t),(e instanceof Dc||e instanceof Cc)&&(t instanceof Dc||t instanceof Cc)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Mc(e,t){return e=(0,a.getModularInstance)(e),t=(0,a.getModularInstance)(t),e instanceof Ac&&t instanceof Ac&&e.firestore===t.firestore&&Cn(e._query,t._query)&&e.converter===t.converter}function Rc(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10240,n=0;return{read:function(){var r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(!(n<e.byteLength)){i.next=3;break}return r={value:e.slice(n,n+t),done:!1},i.abrupt("return",(n+=t,r));case 3:return i.abrupt("return",{done:!0});case 4:case"end":return i.stop()}},null,null,null,Promise)},cancel:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}},null,null,null,Promise)},releaseLock:function(){},closed:Promise.reject("unimplemented")}}exports.CollectionReference=Cc;var Vc=function(){function e(t){C(this,e),this.observer=t,this.muted=!1}return P(e,[{key:"next",value:function(e){this.observer.next&&this.Rc(this.observer.next,e)}},{key:"error",value:function(e){this.observer.error?this.Rc(this.observer.error,e):G("Uncaught Error in snapshot listener:",e.toString())}},{key:"bc",value:function(){this.muted=!0}},{key:"Rc",value:function(e,t){var n=this;this.muted||setTimeout(function(){n.muted||e(t)},0)}}]),e}(),Oc=function(){function e(t,n){var r=this;C(this,e),this.Pc=t,this.yt=n,this.metadata=new Z,this.buffer=new Uint8Array,this.vc=new TextDecoder("utf-8"),this.Vc().then(function(e){e&&e.Ou()?r.metadata.resolve(e.ku.metadata):r.metadata.reject(new Error("The first element of the bundle is not a metadata, it is\n ".concat(JSON.stringify(null==e?void 0:e.ku))))},function(e){return r.metadata.reject(e)})}return P(e,[{key:"close",value:function(){return this.Pc.cancel()}},{key:"getMetadata",value:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.metadata.promise);case 1:case"end":return e.stop()}},null,this,null,Promise)}},{key:"mc",value:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,y().awrap(this.getMetadata());case 2:return e.abrupt("return",this.Vc());case 3:case"end":return e.stop()}},null,this,null,Promise)}},{key:"Vc",value:function(){var e,t,n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,y().awrap(this.Sc());case 2:if(null!==(e=i.sent)){i.next=5;break}return i.abrupt("return",null);case 5:return t=this.vc.decode(e),n=Number(t),isNaN(n)&&this.Dc("length string (".concat(t,") is not valid number")),i.next=9,y().awrap(this.Cc(n));case 9:return r=i.sent,i.abrupt("return",new Ts(JSON.parse(r),e.length+n));case 11:case"end":return i.stop()}},null,this,null,Promise)}},{key:"xc",value:function(){return this.buffer.findIndex(function(e){return e==="{".charCodeAt(0)})}},{key:"Sc",value:function(){var e,t;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!(this.xc()<0)){n.next=7;break}return n.next=3,y().awrap(this.Nc());case 3:if(!n.sent){n.next=5;break}return n.abrupt("break",7);case 5:n.next=0;break;case 7:if(0!==this.buffer.length){n.next=9;break}return n.abrupt("return",null);case 9:return(e=this.xc())<0&&this.Dc("Reached the end of bundle when a length string is expected."),t=this.buffer.slice(0,e),n.abrupt("return",(this.buffer=this.buffer.slice(e),t));case 13:case"end":return n.stop()}},null,this,null,Promise)}},{key:"Cc",value:function(e){var t;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!(this.buffer.length<e)){n.next=8;break}return n.next=3,y().awrap(this.Nc());case 3:if(n.t0=n.sent,!n.t0){n.next=6;break}this.Dc("Reached the end of bundle when more is expected.");case 6:n.next=0;break;case 8:return t=this.vc.decode(this.buffer.slice(0,e)),n.abrupt("return",(this.buffer=this.buffer.slice(e),t));case 10:case"end":return n.stop()}},null,this,null,Promise)}},{key:"Dc",value:function(e){throw this.Pc.cancel(),new Error("Invalid bundle format: ".concat(e))}},{key:"Nc",value:function(){var e,t;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,y().awrap(this.Pc.read());case 2:return(e=n.sent).done||((t=new Uint8Array(this.buffer.length+e.value.length)).set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t),n.abrupt("return",e.done);case 5:case"end":return n.stop()}},null,this,null,Promise)}}]),e}(),qc=P(function e(){C(this,e),this.type="AggregateField"});exports.AggregateField=qc;var Uc=function(){function e(t,n){C(this,e),this._data=n,this.type="AggregateQuerySnapshot",this.query=t}return P(e,[{key:"data",value:function(){return this._data}}]),e}();exports.AggregateQuerySnapshot=Uc;var Bc=function(){function e(t,n,r){C(this,e),this.query=t,this.datastore=n,this.userDataWriter=r}return P(e,[{key:"run",value:function(){var e=this;return Mo(this.datastore,this.query._query).then(function(t){z(void 0!==t[0]);var n=Object.entries(t[0]).filter(function(e){var t=l(e,2),n=t[0];t[1];return"count_alias"===n}).map(function(t){var n=l(t,2),r=(n[0],n[1]);return e.userDataWriter.convertValue(r)})[0];return z("number"==typeof n),Promise.resolve(new Uc(e.query,{count:n}))})}}]),e}(),Gc=function(){function e(t){C(this,e),this.datastore=t,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}return P(e,[{key:"lookup",value:function(e){var t,n=this;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(this.ensureCommitNotCalled(),!(this.mutations.length>0)){r.next=2;break}throw new X(Y.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");case 2:return r.next=4,y().awrap(function(e,t){var n,r,i,a,u,o;return y().async(function(s){for(;;)switch(s.prev=s.next){case 0:return n=H(e),r=ii(n.yt)+"/documents",i={documents:t.map(function(e){return ei(n.yt,e)})},s.next=5,y().awrap(n._o("BatchGetDocuments",r,i,t.length));case 5:return a=s.sent,u=new Map,a.forEach(function(e){var t=si(n.yt,e);u.set(t.key.toString(),t)}),o=[],s.abrupt("return",(t.forEach(function(e){var t=u.get(e.toString());z(!!t),o.push(t)}),o));case 10:case"end":return s.stop()}},null,null,null,Promise)}(this.datastore,e));case 4:return t=r.sent,r.abrupt("return",(t.forEach(function(e){return n.recordVersion(e)}),t));case 6:case"end":return r.stop()}},null,this,null,Promise)}},{key:"set",value:function(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}},{key:"update",value:function(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}},{key:"delete",value:function(e){this.write(new pr(e,this.precondition(e))),this.writtenDocs.add(e.toString())}},{key:"commit",value:function(){var e,t=this;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(this.ensureCommitNotCalled(),!this.lastWriteError){n.next=2;break}throw this.lastWriteError;case 2:return e=this.readVersions,this.mutations.forEach(function(t){e.delete(t.key.toString())}),e.forEach(function(e,n){var r=ge.fromPath(n);t.mutations.push(new mr(r,t.precondition(r)))}),n.next=7,y().awrap(function(e,t){var n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=H(e),r=ii(n.yt)+"/documents",i={writes:t.map(function(e){return li(n.yt,e)})},a.next=3,y().awrap(n.ao("Commit",r,i));case 3:case"end":return a.stop()}},null,null,null,Promise)}(this.datastore,this.mutations));case 7:this.committed=!0;case 8:case"end":return n.stop()}},null,this,null,Promise)}},{key:"recordVersion",value:function(e){var t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw j();t=de.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new X(Y.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}},{key:"precondition",value:function(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(de.min())?tr.exists(!1):tr.updateTime(t):tr.none()}},{key:"preconditionForUpdate",value:function(e){var t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(de.min()))throw new X(Y.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return tr.updateTime(t)}return tr.exists(!0)}},{key:"write",value:function(e){this.ensureCommitNotCalled(),this.mutations.push(e)}},{key:"ensureCommitNotCalled",value:function(){}}]),e}(),Kc=function(){function e(t,n,r,i,a){C(this,e),this.asyncQueue=t,this.datastore=n,this.options=r,this.updateFunction=i,this.deferred=a,this.kc=r.maxAttempts,this.xo=new Co(this.asyncQueue,"transaction_retry")}return P(e,[{key:"run",value:function(){this.kc-=1,this.Oc()}},{key:"Oc",value:function(){var e=this;this.xo.Ro(function(){var t,n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:t=new Gc(e.datastore),(n=e.Mc(t))&&n.then(function(n){e.asyncQueue.enqueueAndForget(function(){return t.commit().then(function(){e.deferred.resolve(n)}).catch(function(t){e.Fc(t)})})}).catch(function(t){e.Fc(t)});case 2:case"end":return r.stop()}},null,null,null,Promise)})}},{key:"Mc",value:function(e){try{var t=this.updateFunction(e);return!Ze(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}},{key:"Fc",value:function(e){var t=this;this.kc>0&&this.$c(e)?(this.kc-=1,this.asyncQueue.enqueueAndForget(function(){return t.Oc(),Promise.resolve()})):this.deferred.reject(e)}},{key:"$c",value:function(e){if("FirebaseError"===e.name){var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!kr(t)}return!1}}]),e}(),Qc=function(){function e(t,n,r,i){var a=this;C(this,e),this.authCredentials=t,this.appCheckCredentials=n,this.asyncQueue=r,this.databaseInfo=i,this.user=R.UNAUTHENTICATED,this.clientId=se.R(),this.authCredentialListener=function(){return Promise.resolve()},this.appCheckCredentialListener=function(){return Promise.resolve()},this.authCredentials.start(r,function(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return B("FirestoreClient","Received user=",e.uid),t.next=3,y().awrap(a.authCredentialListener(e));case 3:a.user=e;case 4:case"end":return t.stop()}},null,null,null,Promise)}),this.appCheckCredentials.start(r,function(e){return B("FirestoreClient","Received new app check token=",e),a.appCheckCredentialListener(e,a.user)})}return P(e,[{key:"getConfiguration",value:function(){return y().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100});case 1:case"end":return e.stop()}},null,this,null,Promise)}},{key:"setCredentialChangeListener",value:function(e){this.authCredentialListener=e}},{key:"setAppCheckTokenChangeListener",value:function(e){this.appCheckCredentialListener=e}},{key:"verifyNotTerminated",value:function(){if(this.asyncQueue.isShuttingDown)throw new X(Y.FAILED_PRECONDITION,"The client has already been terminated.")}},{key:"terminate",value:function(){var e=this;this.asyncQueue.enterRestrictedMode();var t=new Z;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(function(){var n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(r.prev=0,r.t0=e.onlineComponents,!r.t0){r.next=5;break}return r.next=5,y().awrap(e.onlineComponents.terminate());case 5:if(r.t1=e.offlineComponents,!r.t1){r.next=9;break}return r.next=9,y().awrap(e.offlineComponents.terminate());case 9:e.authCredentials.shutdown(),e.appCheckCredentials.shutdown(),t.resolve(),r.next=18;break;case 14:r.prev=14,r.t2=r.catch(0),n=ds(r.t2,"Failed to shutdown persistence"),t.reject(n);case 18:case"end":return r.stop()}},null,null,[[0,14]],Promise)}),t.promise}}]),e}();function jc(e,t){var n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return e.asyncQueue.verifyOperationInProgress(),B("FirestoreClient","Initializing OfflineComponentProvider"),i.next=3,y().awrap(e.getConfiguration());case 3:return n=i.sent,i.next=6,y().awrap(t.initialize(n));case 6:r=n.initialUser,e.setCredentialChangeListener(function(e){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=r.isEqual(e),n.t0){n.next=5;break}return n.next=4,y().awrap(Zu(t.localStore,e));case 4:r=e;case 5:case"end":return n.stop()}},null,null,null,Promise)}),t.persistence.setDatabaseDeletedListener(function(){return e.terminate()}),e.offlineComponents=t;case 8:case"end":return i.stop()}},null,null,null,Promise)}function zc(e,t){var n,r;return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return e.asyncQueue.verifyOperationInProgress(),i.next=3,y().awrap(Wc(e));case 3:return n=i.sent,B("FirestoreClient","Initializing OnlineComponentProvider"),i.next=7,y().awrap(e.getConfiguration());case 7:return r=i.sent,i.next=10,y().awrap(t.initialize(n,r));case 10:e.setCredentialChangeListener(function(e){return ss(t.remoteStore,e)}),e.setAppCheckTokenChangeListener(function(e,n){return ss(t.remoteStore,n)}),e.onlineComponents=t;case 13:case"end":return i.stop()}},null,null,null,Promise)}function Wc(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=e.offlineComponents,t.t0){t.next=5;break}return B("FirestoreClient","Using default OfflineComponentProvider"),t.next=5,y().awrap(jc(e,new dc));case 5:return t.abrupt("return",e.offlineComponents);case 6:case"end":return t.stop()}},null,null,null,Promise)}function Hc(e){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=e.onlineComponents,t.t0){t.next=5;break}return B("FirestoreClient","Using default OnlineComponentProvider"),t.next=5,y().awrap(zc(e,new pc));case 5:return t.abrupt("return",e.onlineComponents);case 6:case"end":return t.stop()}},null,null,null,Promise)}function Yc(e){return Wc(e).then(function(e){return e.persistence})}function Xc(e){return Wc(e).then(function(e){return e.localStore})}function Zc(e){return Hc(e).then(function(e){return e.remoteStore})}function Jc(e){return Hc(e).then(function(e){return e.syncEngine})}function $c(e){return Hc(e).then(function(e){return e.datastore})}function el(e){var t,n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,y().awrap(Hc(e));case 2:return t=r.sent,n=t.eventManager,r.abrupt("return",(n.onListen=Ms.bind(null,t.syncEngine),n.onUnlisten=Vs.bind(null,t.syncEngine),n));case 5:case"end":return r.stop()}},null,null,null,Promise)}function tl(e){return e.asyncQueue.enqueue(function(){var t,n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,y().awrap(Yc(e));case 2:return t=r.sent,r.next=5,y().awrap(Zc(e));case 5:return n=r.sent,r.abrupt("return",(t.setNetworkEnabled(!0),function(e){var t=H(n);return t._u.delete(0),Oo(t)}()));case 7:case"end":return r.stop()}},null,null,null,Promise)})}function nl(e){return e.asyncQueue.enqueue(function(){var t,n;return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,y().awrap(Yc(e));case 2:return t=r.sent,r.next=5,y().awrap(Zc(e));case 5:return n=r.sent,r.abrupt("return",(t.setNetworkEnabled(!1),function(e){var t;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return(t=H(e))._u.add(0),n.next=4,y().awrap(qo(t));case 4:t.gu.set("Offline");case 5:case"end":return n.stop()}},null,null,null,Promise)}(n)));case 7:case"end":return r.stop()}},null,null,null,Promise)})}function rl(e,t){var n=new Z;return e.asyncQueue.enqueueAndForget(function(){return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.t0=function(e,t,n){var r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.prev=0,a.next=3,y().awrap(function(e,t){var n=H(e);return n.persistence.runTransaction("read document","readonly",function(e){return n.localDocuments.getDocument(e,t)})}(e,t));case 3:(r=a.sent).isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new X(Y.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")),a.next=11;break;case 7:a.prev=7,a.t0=a.catch(0),i=ds(a.t0,"Failed to get document '".concat(t," from cache")),n.reject(i);case 11:case"end":return a.stop()}},null,null,[[0,7]],Promise)},r.next=3,y().awrap(Xc(e));case 3:return r.t1=r.sent,r.t2=t,r.t3=n,r.abrupt("return",(0,r.t0)(r.t1,r.t2,r.t3));case 7:case"end":return r.stop()}},null,null,null,Promise)}),n.promise}function il(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new Z;return e.asyncQueue.enqueueAndForget(function(){return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.t0=function(e,t,n,r,i){var a=new Vc({next:function(a){t.enqueueAndForget(function(){return ws(e,u)});var o=a.docs.has(n);!o&&a.fromCache?i.reject(new X(Y.UNAVAILABLE,"Failed to get document because the client is offline.")):o&&a.fromCache&&r&&"server"===r.source?i.reject(new X(Y.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(a)},error:function(e){return i.reject(e)}}),u=new Es(xn(n.path),a,{includeMetadataChanges:!0,Nu:!0});return ks(e,u)},i.next=3,y().awrap(el(e));case 3:return i.t1=i.sent,i.t2=e.asyncQueue,i.t3=t,i.t4=n,i.t5=r,i.abrupt("return",(0,i.t0)(i.t1,i.t2,i.t3,i.t4,i.t5));case 9:case"end":return i.stop()}},null,null,null,Promise)}),r.promise}function al(e,t){var n=new Z;return e.asyncQueue.enqueueAndForget(function(){return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.t0=function(e,t,n){var r,i,a,u,o;return y().async(function(s){for(;;)switch(s.prev=s.next){case 0:return s.prev=0,s.next=3,y().awrap(ao(e,t,!0));case 3:r=s.sent,i=new Ns(t,r.Hi),a=i.Wu(r.documents),u=i.applyChanges(a,!1),n.resolve(u.snapshot),s.next=14;break;case 10:s.prev=10,s.t0=s.catch(0),o=ds(s.t0,"Failed to execute query '".concat(t," against cache")),n.reject(o);case 14:case"end":return s.stop()}},null,null,[[0,10]],Promise)},r.next=3,y().awrap(Xc(e));case 3:return r.t1=r.sent,r.t2=t,r.t3=n,r.abrupt("return",(0,r.t0)(r.t1,r.t2,r.t3));case 7:case"end":return r.stop()}},null,null,null,Promise)}),n.promise}function ul(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new Z;return e.asyncQueue.enqueueAndForget(function(){return y().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.t0=function(e,t,n,r,i){var a=new Vc({next:function(n){t.enqueueAndForget(function(){return ws(e,u)}),n.fromCache&&"server"===r.source?i.reject(new X(Y.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:function(e){return i.reject(e)}}),u=new Es(n,a,{includeMetadataChanges:!0,Nu:!0});return ks(e,u)},i.next=3,y().awrap(el(e));case 3:return i.t1=i.sent,i.t2=e.asyncQueue,i.t3=t,i.t4=n,i.t5=r,i.abrupt("return",(0,i.t0)(i.t1,i.t2,i.t3,i.t4,i.t5));case 9:case"end":return i.stop()}},null,null,null,Promise)}),r.promise}function ol(e,t){var n=new Vc(t);return e.asyncQueue.enqueueAndForget(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=function(e,t){H(e).Ru.add(t),t.next()},t.next=3,y().awrap(el(e));case 3:return t.t1=t.sent,t.t2=n,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)}),function(){n.bc(),e.asyncQueue.enqueueAndForget(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=function(e,t){H(e).Ru.delete(t)},t.next=3,y().awrap(el(e));case 3:return t.t1=t.sent,t.t2=n,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)})}}function sl(e,t,n,r){var i=function(e,t){return function(e,t){return new Oc(e,t)}(function(e,t){if(e instanceof Uint8Array)return Rc(e,t);if(e instanceof ArrayBuffer)return Rc(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}("string"==typeof e?(new TextEncoder).encode(e):e),t)}(n,Ao(t));e.asyncQueue.enqueueAndForget(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=hc,t.next=3,y().awrap(Jc(e));case 3:t.t1=t.sent,t.t2=i,t.t3=r,(0,t.t0)(t.t1,t.t2,t.t3);case 7:case"end":return t.stop()}},null,null,null,Promise)})}function cl(e,t){return e.asyncQueue.enqueue(function(){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.t0=function(e,t){var n=H(e);return n.persistence.runTransaction("Get named query","readonly",function(e){return n.Ns.getNamedQuery(e,t)})},n.next=3,y().awrap(Xc(e));case 3:return n.t1=n.sent,n.t2=t,n.abrupt("return",(0,n.t0)(n.t1,n.t2));case 6:case"end":return n.stop()}},null,null,null,Promise)})}var ll=function(){function e(){var t=this;C(this,e),this.Bc=Promise.resolve(),this.Lc=[],this.qc=!1,this.Uc=[],this.Kc=null,this.Gc=!1,this.Qc=!1,this.jc=[],this.xo=new Co(this,"async_queue_retry"),this.Wc=function(){var e=Do();e&&B("AsyncQueue","Visibility state changed to "+e.visibilityState),t.xo.Po()};var n=Do();n&&"function"==typeof n.addEventListener&&n.addEventListener("visibilitychange",this.Wc)}return P(e,[{key:"isShuttingDown",get:function(){return this.qc}},{key:"enqueueAndForget",value:function(e){this.enqueue(e)}},{key:"enqueueAndForgetEvenWhileRestricted",value:function(e){this.zc(),this.Hc(e)}},{key:"enterRestrictedMode",value:function(e){if(!this.qc){this.qc=!0,this.Qc=e||!1;var t=Do();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Wc)}}},{key:"enqueue",value:function(e){var t=this;if(this.zc(),this.qc)return new Promise(function(){});var n=new Z;return this.Hc(function(){return t.qc&&t.Qc?Promise.resolve():(e().then(n.resolve,n.reject),n.promise)}).then(function(){return n.promise})}},{key:"enqueueRetryable",value:function(e){var t=this;this.enqueueAndForget(function(){return t.Lc.push(e),t.Jc()})}},{key:"Jc",value:function(){var e=this;return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(0===this.Lc.length){t.next=14;break}return t.prev=1,t.next=4,y().awrap(this.Lc[0]());case 4:this.Lc.shift(),this.xo.reset(),t.next=13;break;case 8:if(t.prev=8,t.t0=t.catch(1),Oe(t.t0)){t.next=12;break}throw t.t0;case 12:B("AsyncQueue","Operation failed with retryable error: "+t.t0);case 13:this.Lc.length>0&&this.xo.Ro(function(){return e.Jc()});case 14:case"end":return t.stop()}},null,this,[[1,8]],Promise)}},{key:"Hc",value:function(e){var t=this,n=this.Bc.then(function(){return t.Gc=!0,e().catch(function(e){throw t.Kc=e,t.Gc=!1,G("INTERNAL UNHANDLED ERROR: ",function(e){var t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(function(e){return t.Gc=!1,e})});return this.Bc=n,n}},{key:"enqueueAfterDelay",value:function(e,t,n){var r=this;this.zc(),this.jc.indexOf(e)>-1&&(t=0);var i=hs.createAndSchedule(this,e,t,n,function(e){return r.Yc(e)});return this.Uc.push(i),i}},{key:"zc",value:function(){this.Kc&&j()}},{key:"verifyOperationInProgress",value:function(){}},{key:"Xc",value:function(){var e;return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return e=this.Bc,t.next=3,y().awrap(e);case 3:if(e!==this.Bc){t.next=0;break}case 4:case"end":return t.stop()}},null,this,null,Promise)}},{key:"Zc",value:function(e){var t,n=v(this.Uc);try{for(n.s();!(t=n.n()).done;){if(t.value.timerId===e)return!0}}catch(r){n.e(r)}finally{n.f()}return!1}},{key:"ta",value:function(e){var t=this;return this.Xc().then(function(){t.Uc.sort(function(e,t){return e.targetTimeMs-t.targetTimeMs});var n,r=v(t.Uc);try{for(r.s();!(n=r.n()).done;){var i=n.value;if(i.skipDelay(),"all"!==e&&i.timerId===e)break}}catch(a){r.e(a)}finally{r.f()}return t.Xc()})}},{key:"ea",value:function(e){this.jc.push(e)}},{key:"Yc",value:function(e){var t=this.Uc.indexOf(e);this.Uc.splice(t,1)}}]),e}();function fl(e){return function(e,t){if("object"!=A(e)||null===e)return!1;var n,r=e,i=v(["next","error","complete"]);try{for(i.s();!(n=i.n()).done;){var a=n.value;if(a in r&&"function"==typeof r[a])return!0}}catch(u){i.e(u)}finally{i.f()}return!1}(e)}var hl=function(){function e(){C(this,e),this._progressObserver={},this._taskCompletionResolver=new Z,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}return P(e,[{key:"onProgress",value:function(e,t,n){this._progressObserver={next:e,error:t,complete:n}}},{key:"catch",value:function(e){return this._taskCompletionResolver.promise.catch(e)}},{key:"then",value:function(e,t){return this._taskCompletionResolver.promise.then(e,t)}},{key:"_completeWith",value:function(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}},{key:"_failWith",value:function(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}},{key:"_updateProgress",value:function(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}]),e}();exports.LoadBundleTask=hl;var dl=-1;exports.CACHE_SIZE_UNLIMITED=dl;var vl=function(e){p(n,Sc);var t=g(n);function n(e,r,i,a){var u;return C(this,n),(u=t.call(this,e,r,i,a)).type="firestore",u._queue=new ll,u._persistenceKey=(null==a?void 0:a.name)||"[DEFAULT]",u}return P(n,[{key:"_terminate",value:function(){return this._firestoreClient||gl(this),this._firestoreClient.terminate()}}]),n}();function yl(e,t,r){r||(r="(default)");var i=(0,n._getProvider)(e,"firestore");if(i.isInitialized(r)){var u=i.getImmediate({identifier:r}),o=i.getOptions(r);if((0,a.deepEqual)(o,t))return u;throw new X(Y.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new X(Y.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return i.initialize({options:t,instanceIdentifier:r})}function pl(e,t){var r="object"==A(e)?e:(0,n.getApp)(),i="string"==typeof e?e:t||"(default)",u=(0,n._getProvider)(r,"firestore").getImmediate({identifier:i});if(!u._initialized){var o=(0,a.getDefaultEmulatorHostnameAndPort)("firestore");o&&_c.apply(void 0,[u].concat(I(o)))}return u}function ml(e){return e._firestoreClient||gl(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function gl(e){var t,n=e._freezeSettings(),r=function(e,t,n,r){return new ze(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 Qc(e._authCredentials,e._appCheckCredentials,e._queue,r)}function kl(e,t){Al(e=bc(e,vl));var n=ml(e),r=e._freezeSettings(),i=new pc;return xl(n,i,new vc(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}function wl(e){Al(e=bc(e,vl));var t=ml(e),n=e._freezeSettings(),r=new pc;return xl(t,r,new yc(r,n.cacheSizeBytes))}function xl(e,t,n){var r=new Z;return e.asyncQueue.enqueue(function(){var i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.prev=0,a.next=3,y().awrap(jc(e,n));case 3:return a.next=5,y().awrap(zc(e,t));case 5:r.resolve(),a.next=14;break;case 8:if(a.prev=8,a.t0=a.catch(0),function(e){return"FirebaseError"===e.name?e.code===Y.FAILED_PRECONDITION||e.code===Y.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||(22===e.code||20===e.code||11===e.code)}(i=a.t0)){a.next=13;break}throw i;case 13:K("Error enabling offline persistence. Falling back to persistence disabled: "+i),r.reject(i);case 14:case"end":return a.stop()}},null,null,[[0,8]],Promise)}).then(function(){return r.promise})}function bl(e){if(e._initialized&&!e._terminated)throw new X(Y.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");var t=new Z;return e._queue.enqueueAndForgetEvenWhileRestricted(function(){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,y().awrap(function(e){var t;return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(Me.C()){n.next=2;break}return n.abrupt("return",Promise.resolve());case 2:return t=e+"main",n.next=5,y().awrap(Me.delete(t));case 5:case"end":return n.stop()}},null,null,null,Promise)}(zu(e._databaseId,e._persistenceKey)));case 3:t.resolve(),n.next=9;break;case 6:n.prev=6,n.t0=n.catch(0),t.reject(n.t0);case 9:case"end":return n.stop()}},null,null,[[0,6]],Promise)}),t.promise}function Il(e){return function(e){var t=new Z;return e.asyncQueue.enqueueAndForget(function(){return y().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.t0=Qs,n.next=3,y().awrap(Jc(e));case 3:return n.t1=n.sent,n.t2=t,n.abrupt("return",(0,n.t0)(n.t1,n.t2));case 6:case"end":return n.stop()}},null,null,null,Promise)}),t.promise}(ml(e=bc(e,vl)))}function El(e){return tl(ml(e=bc(e,vl)))}function Tl(e){return nl(ml(e=bc(e,vl)))}function Sl(e){return(0,n._removeServiceInstance)(e.app,"firestore",e._databaseId.database),e._delete()}function _l(e,t){var n=ml(e=bc(e,vl)),r=new hl;return sl(n,e._databaseId,t,r),r}function Dl(e,t){return cl(ml(e=bc(e,vl)),t).then(function(t){return t?new Ac(e,null,t.query):null})}function Al(e){if(e._initialized||e._terminated)throw new X(Y.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}exports.Firestore=vl;var Cl=function(){function e(t){C(this,e),this._byteString=t}return P(e,[{key:"toBase64",value:function(){return this._byteString.toBase64()}},{key:"toUint8Array",value:function(){return this._byteString.toUint8Array()}},{key:"toString",value:function(){return"Bytes(base64: "+this.toBase64()+")"}},{key:"isEqual",value:function(e){return this._byteString.isEqual(e._byteString)}}],[{key:"fromBase64String",value:function(t){try{return new e(tt.fromBase64String(t))}catch(t){throw new X(Y.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}},{key:"fromUint8Array",value:function(t){return new e(tt.fromUint8Array(t))}}]),e}();exports.Bytes=Cl;var Nl=function(){function e(){C(this,e);for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0;i<n.length;++i)if(0===n[i].length)throw new X(Y.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new me(n)}return P(e,[{key:"isEqual",value:function(e){return this._internalPath.isEqual(e._internalPath)}}]),e}();function Pl(){return new Nl("__name__")}exports.FieldPath=Nl;var Ll=P(function e(t){C(this,e),this._methodName=t});exports.FieldValue=Ll;var Fl=function(){function e(t,n){if(C(this,e),!isFinite(t)||t<-90||t>90)throw new X(Y.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(n)||n<-180||n>180)throw new X(Y.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=t,this._long=n}return P(e,[{key:"latitude",get:function(){return this._lat}},{key:"longitude",get:function(){return this._long}},{key:"isEqual",value:function(e){return this._lat===e._lat&&this._long===e._long}},{key:"toJSON",value:function(){return{latitude:this._lat,longitude:this._long}}},{key:"_compareTo",value:function(e){return ce(this._lat,e._lat)||ce(this._long,e._long)}}]),e}();exports.GeoPoint=Fl;var Ml=/^__.*__$/,Rl=function(){function e(t,n,r){C(this,e),this.data=t,this.fieldMask=n,this.fieldTransforms=r}return P(e,[{key:"toMutation",value:function(e,t){return null!==this.fieldMask?new lr(e,this.data,this.fieldMask,t,this.fieldTransforms):new cr(e,this.data,t,this.fieldTransforms)}}]),e}(),Vl=function(){function e(t,n,r){C(this,e),this.data=t,this.fieldMask=n,this.fieldTransforms=r}return P(e,[{key:"toMutation",value:function(e,t){return new lr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}]),e}();function Ol(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw j()}}var ql=function(){function e(t,n,r,i,a,u){C(this,e),this.settings=t,this.databaseId=n,this.yt=r,this.ignoreUndefinedProperties=i,void 0===a&&this.na(),this.fieldTransforms=a||[],this.fieldMask=u||[]}return P(e,[{key:"path",get:function(){return this.settings.path}},{key:"sa",get:function(){return this.settings.sa}},{key:"ia",value:function(t){return new e(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.yt,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}},{key:"ra",value:function(e){var t,n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.ua(e),r}},{key:"ca",value:function(e){var t,n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.na(),r}},{key:"aa",value:function(e){return this.ia({path:void 0,oa:!0})}},{key:"ha",value:function(e){return uf(e,this.settings.methodName,this.settings.la||!1,this.path,this.settings.fa)}},{key:"contains",value:function(e){return void 0!==this.fieldMask.find(function(t){return e.isPrefixOf(t)})||void 0!==this.fieldTransforms.find(function(t){return e.isPrefixOf(t.field)})}},{key:"na",value:function(){if(this.path)for(var e=0;e<this.path.length;e++)this.ua(this.path.get(e))}},{key:"ua",value:function(e){if(0===e.length)throw this.ha("Document fields must not be empty");if(Ol(this.sa)&&Ml.test(e))throw this.ha('Document fields cannot begin and end with "__"')}}]),e}(),Ul=function(){function e(t,n,r){C(this,e),this.databaseId=t,this.ignoreUndefinedProperties=n,this.yt=r||Ao(t)}return P(e,[{key:"da",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new ql({sa:e,methodName:t,fa:n,path:me.emptyPath(),oa:!1,la:r},this.databaseId,this.yt,this.ignoreUndefinedProperties)}}]),e}();function Bl(e){var t=e._freezeSettings(),n=Ao(e._databaseId);return new Ul(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Gl(e,t,n,r,i){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},u=e.da(a.merge||a.mergeFields?2:0,t,n,i);tf("Data must be an object, but it was:",u,r);var o,s,c=$l(r,u);if(a.merge)o=new on(u.fieldMask),s=u.fieldTransforms;else if(a.mergeFields){var l,f=[],h=v(a.mergeFields);try{for(h.s();!(l=h.n()).done;){var d=nf(t,l.value,n);if(!u.contains(d))throw new X(Y.INVALID_ARGUMENT,"Field '".concat(d,"' is specified in your field mask but missing from your input data."));of(f,d)||f.push(d)}}catch(y){h.e(y)}finally{h.f()}o=new on(f),s=u.fieldTransforms.filter(function(e){return o.covers(e.field)})}else o=null,s=u.fieldTransforms;return new Rl(new sn(c),o,s)}var Kl=function(e){p(n,Ll);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n,[{key:"_toFieldTransform",value:function(e){if(2!==e.sa)throw 1===e.sa?e.ha("".concat(this._methodName,"() can only appear at the top level of your update data")):e.ha("".concat(this._methodName,"() cannot be used with set() unless you pass {merge:true}"));return e.fieldMask.push(e.path),null}},{key:"isEqual",value:function(e){return e instanceof n}}]),n}();function Ql(e,t,n){return new ql({sa:3,fa:t.settings.fa,methodName:e._methodName,oa:n},t.databaseId,t.yt,t.ignoreUndefinedProperties)}var jl=function(e){p(n,Ll);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n,[{key:"_toFieldTransform",value:function(e){return new Jn(e.path,new Qn)}},{key:"isEqual",value:function(e){return e instanceof n}}]),n}(),zl=function(e){p(n,Ll);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e))._a=r,i}return P(n,[{key:"_toFieldTransform",value:function(e){var t=Ql(this,e,!0),n=this._a.map(function(e){return Jl(e,t)}),r=new jn(n);return new Jn(e.path,r)}},{key:"isEqual",value:function(e){return this===e}}]),n}(),Wl=function(e){p(n,Ll);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e))._a=r,i}return P(n,[{key:"_toFieldTransform",value:function(e){var t=Ql(this,e,!0),n=this._a.map(function(e){return Jl(e,t)}),r=new Wn(n);return new Jn(e.path,r)}},{key:"isEqual",value:function(e){return this===e}}]),n}(),Hl=function(e){p(n,Ll);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e)).wa=r,i}return P(n,[{key:"_toFieldTransform",value:function(e){var t=new Yn(e.yt,qn(e.yt,this.wa));return new Jn(e.path,t)}},{key:"isEqual",value:function(e){return this===e}}]),n}();function Yl(e,t,n,r){var i=e.da(1,t,n);tf("Data must be an object, but it was:",i,r);var u=[],o=sn.empty();Ye(r,function(e,r){var s=af(t,e,n);r=(0,a.getModularInstance)(r);var c=i.ca(s);if(r instanceof Kl)u.push(s);else{var l=Jl(r,c);null!=l&&(u.push(s),o.set(s,l))}});var s=new on(u);return new Vl(o,s,i.fieldTransforms)}function Xl(e,t,n,r,i,u){var o=e.da(1,t,n),s=[nf(t,r,n)],c=[i];if(u.length%2!=0)throw new X(Y.INVALID_ARGUMENT,"Function ".concat(t,"() needs to be called with an even number of arguments that alternate between field names and values."));for(var l=0;l<u.length;l+=2)s.push(nf(t,u[l])),c.push(u[l+1]);for(var f=[],h=sn.empty(),d=s.length-1;d>=0;--d)if(!of(f,s[d])){var v=s[d],y=c[d];y=(0,a.getModularInstance)(y);var p=o.ca(v);if(y instanceof Kl)f.push(v);else{var m=Jl(y,p);null!=m&&(f.push(v),h.set(v,m))}}var g=new on(f);return new Vl(h,g,o.fieldTransforms)}function Zl(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return Jl(n,e.da(r?4:3,t))}function Jl(e,t){if(ef(e=(0,a.getModularInstance)(e)))return tf("Unsupported field value:",t,e),$l(e,t);if(e instanceof Ll)return function(e,t){if(!Ol(t.sa))throw t.ha("".concat(e._methodName,"() can only be used with update() and set()"));if(!t.path)throw t.ha("".concat(e._methodName,"() is not currently supported inside arrays"));var 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.sa)throw t.ha("Nested arrays are not supported");return function(e,t){var n,r=[],i=0,a=v(e);try{for(a.s();!(n=a.n()).done;){var u=Jl(n.value,t.aa(i));null==u&&(u={nullValue:"NULL_VALUE"}),r.push(u),i++}}catch(o){a.e(o)}finally{a.f()}return{arrayValue:{values:r}}}(e,t)}return function(e,t){if(null===(e=(0,a.getModularInstance)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return qn(t.yt,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=he.fromDate(e);return{timestampValue:Hr(t.yt,n)}}if(e instanceof he){var r=new he(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Hr(t.yt,r)}}if(e instanceof Fl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Cl)return{bytesValue:Yr(t.yt,e._byteString)};if(e instanceof Dc){var i=t.databaseId,u=e.firestore._databaseId;if(!u.isEqual(i))throw t.ha("Document reference is for database ".concat(u.projectId,"/").concat(u.database," but should be for database ").concat(i.projectId,"/").concat(i.database));return{referenceValue:Jr(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ha("Unsupported field value: ".concat(xc(e)))}(e,t)}function $l(e,t){var n={};return Xe(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ye(e,function(e,r){var i=Jl(r,t.ra(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function ef(e){return!("object"!=A(e)||null===e||e instanceof Array||e instanceof Date||e instanceof he||e instanceof Fl||e instanceof Cl||e instanceof Dc||e instanceof Ll)}function tf(e,t,n){if(!ef(n)||!function(e){return"object"==A(e)&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){var r=xc(n);throw"an object"===r?t.ha(e+" a custom object"):t.ha(e+" "+r)}}function nf(e,t,n){if((t=(0,a.getModularInstance)(t))instanceof Nl)return t._internalPath;if("string"==typeof t)return af(e,t);throw uf("Field path arguments must be of type string or ",e,!1,void 0,n)}var rf=new RegExp("[~\\*/\\[\\]]");function af(e,t,n){if(t.search(rf)>=0)throw uf("Invalid field path (".concat(t,"). Paths must not contain '~', '*', '/', '[', or ']'"),e,!1,void 0,n);try{return o(Nl,I(t.split(".")))._internalPath}catch(r){throw uf("Invalid field path (".concat(t,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"),e,!1,void 0,n)}}function uf(e,t,n,r,i){var a=r&&!r.isEmpty(),u=void 0!==i,o="Function ".concat(t,"() called with invalid data");n&&(o+=" (via `toFirestore()`)"),o+=". ";var s="";return(a||u)&&(s+=" (found",a&&(s+=" in field ".concat(r)),u&&(s+=" in document ".concat(i)),s+=")"),new X(Y.INVALID_ARGUMENT,o+e+s)}function of(e,t){return e.some(function(e){return e.isEqual(t)})}var sf=function(){function e(t,n,r,i,a){C(this,e),this._firestore=t,this._userDataWriter=n,this._key=r,this._document=i,this._converter=a}return P(e,[{key:"id",get:function(){return this._key.path.lastSegment()}},{key:"ref",get:function(){return new Dc(this._firestore,this._converter,this._key)}},{key:"exists",value:function(){return null!==this._document}},{key:"data",value:function(){if(this._document){if(this._converter){var e=new cf(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}},{key:"get",value:function(e){if(this._document){var t=this._document.data.field(lf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}]),e}(),cf=function(e){p(n,sf);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n,[{key:"data",value:function(){return s(b(n.prototype),"data",this).call(this)}}]),n}();function lf(e,t){return"string"==typeof t?af(e,t):t instanceof Nl?t._internalPath:t._delegate._internalPath}function ff(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new X(Y.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var hf=P(function e(){C(this,e)}),df=function(e){p(n,hf);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n)}();function vf(e,t){for(var n=[],r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a];t instanceof hf&&n.push(t),function(e){var t=e.filter(function(e){return e instanceof mf}).length,n=e.filter(function(e){return e instanceof yf}).length;if(t>1||t>0&&n>0)throw new X(Y.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(n=n.concat(i));var u,o=v(n);try{for(o.s();!(u=o.n()).done;){e=u.value._apply(e)}}catch(s){o.e(s)}finally{o.f()}return e}exports.QueryConstraint=df;var yf=function(e){p(n,df);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this))._field=e,a._op=r,a._value=i,a.type="where",a}return P(n,[{key:"_apply",value:function(e){var t=this._parse(e);return Ff(e._query,t),new Ac(e.firestore,e.converter,Dn(e._query,t))}},{key:"_parse",value:function(e){var t=Bl(e.firestore);return function(e,t,n,r,i,a,u){var o;if(i.isKeyField()){if("array-contains"===a||"array-contains-any"===a)throw new X(Y.INVALID_ARGUMENT,"Invalid Query. You can't perform '".concat(a,"' queries on documentId()."));if("in"===a||"not-in"===a){Lf(u,a);var s,c=[],l=v(u);try{for(l.s();!(s=l.n()).done;){var f=s.value;c.push(Pf(r,e,f))}}catch(h){l.e(h)}finally{l.f()}o={arrayValue:{values:c}}}else o=Pf(r,e,u)}else"in"!==a&&"not-in"!==a&&"array-contains-any"!==a||Lf(u,a),o=Zl(n,"where",u,"in"===a||"not-in"===a);return Ft.create(i,a,o)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value)}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function pf(e,t,n){var r=t,i=lf("where",e);return yf._create(i,r,n)}exports.QueryFieldFilterConstraint=yf;var mf=function(e){p(n,hf);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this)).type=e,i._queryConstraints=r,i}return P(n,[{key:"_parse",value:function(e){var t=this._queryConstraints.map(function(t){return t._parse(e)}).filter(function(e){return e.getFilters().length>0});return 1===t.length?t[0]:Mt.create(t,this._getOperator())}},{key:"_apply",value:function(e){var t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){var n,r=e,i=v(t.getFlattenedFilters());try{for(i.s();!(n=i.n()).done;){var a=n.value;Ff(r,a),r=Dn(r,a)}}catch(u){i.e(u)}finally{i.f()}}(e._query,t),new Ac(e.firestore,e.converter,Dn(e._query,t)))}},{key:"_getQueryConstraints",value:function(){return this._queryConstraints}},{key:"_getOperator",value:function(){return"and"===this.type?"and":"or"}}],[{key:"_create",value:function(e,t){return new n(e,t)}}]),n}();function gf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.forEach(function(e){return Rf("or",e)}),mf._create("or",t)}function kf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.forEach(function(e){return Rf("and",e)}),mf._create("and",t)}exports.QueryCompositeFilterConstraint=mf;var wf=function(e){p(n,df);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this))._field=e,i._direction=r,i.type="orderBy",i}return P(n,[{key:"_apply",value:function(e){var t=function(e,t,n){if(null!==e.startAt)throw new X(Y.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new X(Y.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r=new Jt(t,n);return function(e,t){if(null===In(e)){var n=En(e);null!==n&&Mf(e,n,t.field)}}(e,r),r}(e._query,this._field,this._direction);return new Ac(e.firestore,e.converter,function(e,t){var n=e.explicitOrderBy.concat([t]);return new kn(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}],[{key:"_create",value:function(e,t){return new n(e,t)}}]),n}();function xf(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"asc",n=lf("orderBy",e);return wf._create(n,t)}exports.QueryOrderByConstraint=wf;var bf=function(e){p(n,df);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this)).type=e,a._limit=r,a._limitType=i,a}return P(n,[{key:"_apply",value:function(e){return new Ac(e.firestore,e.converter,An(e._query,this._limit,this._limitType))}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function If(e){return Ic("limit",e),bf._create("limit",e,"F")}function Ef(e){return Ic("limitToLast",e),bf._create("limitToLast",e,"L")}exports.QueryLimitConstraint=bf;var Tf=function(e){p(n,df);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this)).type=e,a._docOrFields=r,a._inclusive=i,a}return P(n,[{key:"_apply",value:function(e){var t=Nf(e,this.type,this._docOrFields,this._inclusive);return new Ac(e.firestore,e.converter,function(e,t){return new kn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function Sf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Tf._create("startAt",t,!0)}function _f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Tf._create("startAfter",t,!1)}exports.QueryStartAtConstraint=Tf;var Df=function(e){p(n,df);var t=g(n);function n(e,r,i){var a;return C(this,n),(a=t.call(this)).type=e,a._docOrFields=r,a._inclusive=i,a}return P(n,[{key:"_apply",value:function(e){var t=Nf(e,this.type,this._docOrFields,this._inclusive);return new Ac(e.firestore,e.converter,function(e,t){return new kn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function Af(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Df._create("endBefore",t,!1)}function Cf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Df._create("endAt",t,!0)}function Nf(e,t,n,r){if(n[0]=(0,a.getModularInstance)(n[0]),n[0]instanceof sf)return function(e,t,n,r,i){if(!r)throw new X(Y.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for ".concat(n,"()."));var a,u=[],o=v(Sn(e));try{for(o.s();!(a=o.n()).done;){var s=a.value;if(s.field.isKeyField())u.push(gt(t,r.key));else{var c=r.data.field(s.field);if(ut(c))throw new X(Y.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+s.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===c){var l=s.field.canonicalString();throw new X(Y.INVALID_ARGUMENT,"Invalid query. You are trying to start or end a query using a document for which the field '".concat(l,"' (used as the orderBy) does not exist."))}u.push(c)}}}catch(f){o.e(f)}finally{o.f()}return new Ct(u,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=Bl(e.firestore);return function(e,t,n,r,i,a){var u=e.explicitOrderBy;if(i.length>u.length)throw new X(Y.INVALID_ARGUMENT,"Too many arguments provided to ".concat(r,"(). The number of arguments must be less than or equal to the number of orderBy() clauses"));for(var o=[],s=0;s<i.length;s++){var c=i[s];if(u[s].field.isKeyField()){if("string"!=typeof c)throw new X(Y.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in ".concat(r,"(), but got a ").concat(A(c)));if(!Tn(e)&&-1!==c.indexOf("/"))throw new X(Y.INVALID_ARGUMENT,"Invalid query. When querying a collection and ordering by documentId(), the value passed to ".concat(r,"() must be a plain document ID, but '").concat(c,"' contains a slash."));var l=e.path.child(ye.fromString(c));if(!ge.isDocumentKey(l))throw new X(Y.INVALID_ARGUMENT,"Invalid query. When querying a collection group and ordering by documentId(), the value passed to ".concat(r,"() must result in a valid document path, but '").concat(l,"' is not because it contains an odd number of segments."));var f=new ge(l);o.push(gt(t,f))}else{var h=Zl(n,r,c);o.push(h)}}return new Ct(o,a)}(e._query,e.firestore._databaseId,i,t,n,r)}function Pf(e,t,n){if("string"==typeof(n=(0,a.getModularInstance)(n))){if(""===n)throw new X(Y.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Tn(t)&&-1!==n.indexOf("/"))throw new X(Y.INVALID_ARGUMENT,"Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '".concat(n,"' contains a '/' character."));var r=t.path.child(ye.fromString(n));if(!ge.isDocumentKey(r))throw new X(Y.INVALID_ARGUMENT,"Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '".concat(r,"' is not because it has an odd number of segments (").concat(r.length,")."));return gt(e,new ge(r))}if(n instanceof Dc)return gt(e,n._key);throw new X(Y.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ".concat(xc(n),"."))}function Lf(e,t){if(!Array.isArray(e)||0===e.length)throw new X(Y.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '".concat(t.toString(),"' filters."));if(e.length>10)throw new X(Y.INVALID_ARGUMENT,"Invalid Query. '".concat(t.toString(),"' filters support a maximum of 10 elements in the value array."))}function Ff(e,t){if(t.isInequality()){var n=En(e),r=t.field;if(null!==n&&!n.isEqual(r))throw new X(Y.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '".concat(n.toString(),"' and '").concat(r.toString(),"'"));var i=In(e);null!==i&&Mf(e,r,i)}var a=function(e,t){var n,r=v(e);try{for(r.s();!(n=r.n()).done;){var i,a=v(n.value.getFlattenedFilters());try{for(a.s();!(i=a.n()).done;){var u=i.value;if(t.indexOf(u.op)>=0)return u.op}}catch(o){a.e(o)}finally{a.f()}}}catch(o){r.e(o)}finally{r.f()}return null}(e.filters,function(e){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==a)throw a===t.op?new X(Y.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '".concat(t.op.toString(),"' filter.")):new X(Y.INVALID_ARGUMENT,"Invalid query. You cannot use '".concat(t.op.toString(),"' filters with '").concat(a.toString(),"' filters."))}function Mf(e,t,n){if(!n.isEqual(t))throw new X(Y.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '".concat(t.toString(),"' and so you must also use '").concat(t.toString(),"' as your first argument to orderBy(), but your first orderBy() is on field '").concat(n.toString(),"' instead."))}function Rf(e,t){if(!(t instanceof yf||t instanceof mf))throw new X(Y.INVALID_ARGUMENT,"Function ".concat(e,"() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'."))}exports.QueryEndAtConstraint=Df;var Vf=function(){function e(){C(this,e)}return P(e,[{key:"convertValue",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none";switch(ft(e)){case 0:return null;case 1:return e.booleanValue;case 2:return it(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(at(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 j()}}},{key:"convertObject",value:function(e,t){var n=this,r={};return Ye(e.fields,function(e,i){r[e]=n.convertValue(i,t)}),r}},{key:"convertGeoPoint",value:function(e){return new Fl(it(e.latitude),it(e.longitude))}},{key:"convertArray",value:function(e,t){var n=this;return(e.values||[]).map(function(e){return n.convertValue(e,t)})}},{key:"convertServerTimestamp",value:function(e,t){switch(t){case"previous":var n=ot(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(st(e));default:return null}}},{key:"convertTimestamp",value:function(e){var t=rt(e);return new he(t.seconds,t.nanos)}},{key:"convertDocumentKey",value:function(e,t){var n=ye.fromString(e);z(Ti(n));var r=new We(n.get(1),n.get(3)),i=new ge(n.popFirst(5));return r.isEqual(t)||G("Document ".concat(i," contains a document reference within a different database (").concat(r.projectId,"/").concat(r.database,") which is not supported. It will be treated as a reference in the current database (").concat(t.projectId,"/").concat(t.database,") instead.")),i}}]),e}();function Of(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}exports.AbstractUserDataWriter=Vf;var qf=function(e){p(n,Vf);var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this)).firestore=e,r}return P(n,[{key:"convertBytes",value:function(e){return new Cl(e)}},{key:"convertReference",value:function(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Dc(this.firestore,null,t)}}]),n}(),Uf=function(){function e(t,n){C(this,e),this.hasPendingWrites=t,this.fromCache=n}return P(e,[{key:"isEqual",value:function(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}]),e}();exports.SnapshotMetadata=Uf;var Bf=function(e){p(n,sf);var t=g(n);function n(e,r,i,a,u,o){var s;return C(this,n),(s=t.call(this,e,r,i,a,o))._firestore=e,s._firestoreImpl=e,s.metadata=u,s}return P(n,[{key:"exists",value:function(){return s(b(n.prototype),"exists",this).call(this)}},{key:"data",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this._document){if(this._converter){var t=new Gf(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)}}},{key:"get",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._document){var n=this._document.data.field(lf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}]),n}();exports.DocumentSnapshot=Bf;var Gf=function(e){p(n,Bf);var t=g(n);function n(){return C(this,n),t.apply(this,arguments)}return P(n,[{key:"data",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s(b(n.prototype),"data",this).call(this,e)}}]),n}();exports.QueryDocumentSnapshot=Gf;var Kf=function(){function e(t,n,r,i){C(this,e),this._firestore=t,this._userDataWriter=n,this._snapshot=i,this.metadata=new Uf(i.hasPendingWrites,i.fromCache),this.query=r}return P(e,[{key:"docs",get:function(){var e=[];return this.forEach(function(t){return e.push(t)}),e}},{key:"size",get:function(){return this._snapshot.docs.size}},{key:"empty",get:function(){return 0===this.size}},{key:"forEach",value:function(e,t){var n=this;this._snapshot.docs.forEach(function(r){e.call(t,new Gf(n._firestore,n._userDataWriter,r.key,r,new Uf(n._snapshot.mutatedKeys.has(r.key),n._snapshot.fromCache),n.query.converter))})}},{key:"docChanges",value:function(){var e=!!(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new X(Y.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){var n=0;return e._snapshot.docChanges.map(function(t){var r=new Gf(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Uf(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);return t.doc,{type:"added",doc:r,oldIndex:-1,newIndex:n++}})}var r=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(function(e){return t||3!==e.type}).map(function(t){var n=new Gf(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Uf(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,a=-1;return 0!==t.type&&(i=r.indexOf(t.doc.key),r=r.delete(t.doc.key)),1!==t.type&&(a=(r=r.add(t.doc)).indexOf(t.doc.key)),{type:Qf(t.type),doc:n,oldIndex:i,newIndex:a}})}(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}]),e}();function Qf(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return j()}}function jf(e,t){return e instanceof Bf&&t instanceof Bf?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof Kf&&t instanceof Kf&&e._firestore===t._firestore&&Mc(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function zf(e){e=bc(e,Dc);var t=bc(e.firestore,vl);return il(ml(t),e._key).then(function(n){return uh(t,e,n)})}exports.QuerySnapshot=Kf;var Wf=function(e){p(n,Vf);var t=g(n);function n(e){var r;return C(this,n),(r=t.call(this)).firestore=e,r}return P(n,[{key:"convertBytes",value:function(e){return new Cl(e)}},{key:"convertReference",value:function(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Dc(this.firestore,null,t)}}]),n}();function Hf(e){e=bc(e,Dc);var t=bc(e.firestore,vl),n=ml(t),r=new Wf(t);return rl(n,e._key).then(function(n){return new Bf(t,r,e._key,n,new Uf(null!==n&&n.hasLocalMutations,!0),e.converter)})}function Yf(e){e=bc(e,Dc);var t=bc(e.firestore,vl);return il(ml(t),e._key,{source:"server"}).then(function(n){return uh(t,e,n)})}function Xf(e){e=bc(e,Ac);var t=bc(e.firestore,vl),n=ml(t),r=new Wf(t);return ff(e._query),ul(n,e._query).then(function(n){return new Kf(t,r,e,n)})}function Zf(e){e=bc(e,Ac);var t=bc(e.firestore,vl),n=ml(t),r=new Wf(t);return al(n,e._query).then(function(n){return new Kf(t,r,e,n)})}function Jf(e){e=bc(e,Ac);var t=bc(e.firestore,vl),n=ml(t),r=new Wf(t);return ul(n,e._query,{source:"server"}).then(function(n){return new Kf(t,r,e,n)})}function $f(e,t,n){e=bc(e,Dc);var r=bc(e.firestore,vl),i=Of(e.converter,t,n);return ah(r,[Gl(Bl(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,tr.none())])}function eh(e,t,n){e=bc(e,Dc);for(var r=bc(e.firestore,vl),i=Bl(r),u=arguments.length,o=new Array(u>3?u-3:0),s=3;s<u;s++)o[s-3]=arguments[s];return ah(r,[("string"==typeof(t=(0,a.getModularInstance)(t))||t instanceof Nl?Xl(i,"updateDoc",e._key,t,n,o):Yl(i,"updateDoc",e._key,t)).toMutation(e._key,tr.exists(!0))])}function th(e){return ah(bc(e.firestore,vl),[new pr(e._key,tr.none())])}function nh(e,t){var n=bc(e.firestore,vl),r=Lc(e),i=Of(e.converter,t);return ah(n,[Gl(Bl(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,tr.exists(!1))]).then(function(){return r})}function rh(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var i,u,o;e=(0,a.getModularInstance)(e);var s={includeMetadataChanges:!1},c=0;"object"!=A(n[c])||fl(n[c])||(s=n[c],c++);var l,f,h,d={includeMetadataChanges:s.includeMetadataChanges};if(fl(n[c])){var v=n[c];n[c]=null===(i=v.next)||void 0===i?void 0:i.bind(v),n[c+1]=null===(u=v.error)||void 0===u?void 0:u.bind(v),n[c+2]=null===(o=v.complete)||void 0===o?void 0:o.bind(v)}if(e instanceof Dc)f=bc(e.firestore,vl),h=xn(e._key.path),l={next:function(t){n[c]&&n[c](uh(f,e,t))},error:n[c+1],complete:n[c+2]};else{var p=bc(e,Ac);f=bc(p.firestore,vl),h=p._query;var m=new Wf(f);l={next:function(e){n[c]&&n[c](new Kf(f,m,p,e))},error:n[c+1],complete:n[c+2]},ff(e._query)}return function(e,t,n,r){var i=new Vc(l),a=new Es(t,i,n);return e.asyncQueue.enqueueAndForget(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=ks,t.next=3,y().awrap(el(e));case 3:return t.t1=t.sent,t.t2=a,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)}),function(){i.bc(),e.asyncQueue.enqueueAndForget(function(){return y().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=ws,t.next=3,y().awrap(el(e));case 3:return t.t1=t.sent,t.t2=a,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)})}}(ml(f),h,d)}function ih(e,t){return ol(ml(e=bc(e,vl)),fl(t)?t:{next:t})}function ah(e,t){return function(e,t){var n=new Z;return e.asyncQueue.enqueueAndForget(function(){return y().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.t0=Os,r.next=3,y().awrap(Jc(e));case 3:return r.t1=r.sent,r.t2=t,r.t3=n,r.abrupt("return",(0,r.t0)(r.t1,r.t2,r.t3));case 7:case"end":return r.stop()}},null,null,null,Promise)}),n.promise}(ml(e),t)}function uh(e,t,n){var r=n.docs.get(t._key),i=new Wf(e);return new Bf(e,i,t._key,r,new Uf(n.hasPendingWrites,n.fromCache),t.converter)}function oh(e,t){return Mc(e.query,t.query)&&(0,a.deepEqual)(e.data(),t.data())}function sh(e){var t=bc(e.firestore,vl);return function(e,t,n){var r=new Z;return e.asyncQueue.enqueueAndForget(function(){var i,a;return y().async(function(u){for(;;)switch(u.prev=u.next){case 0:return u.prev=0,u.t0=zo,u.next=4,y().awrap(Zc(e));case 4:if(u.t1=u.sent,!(0,u.t0)(u.t1)){u.next=13;break}return u.next=8,y().awrap($c(e));case 8:i=u.sent,a=new Bc(t,i,n).run(),r.resolve(a),u.next=14;break;case 13:r.reject(new X(Y.UNAVAILABLE,"Failed to get count result because the client is offline."));case 14:u.next=19;break;case 16:u.prev=16,u.t2=u.catch(0),r.reject(u.t2);case 19:case"end":return u.stop()}},null,null,[[0,16]],Promise)}),r.promise}(ml(t),e,new Wf(t))}var ch={maxAttempts:5},lh=function(){function e(t,n){C(this,e),this._firestore=t,this._commitHandler=n,this._mutations=[],this._committed=!1,this._dataReader=Bl(t)}return P(e,[{key:"set",value:function(e,t,n){this._verifyNotCommitted();var r=fh(e,this._firestore),i=Of(r.converter,t,n),a=Gl(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(a.toMutation(r._key,tr.none())),this}},{key:"update",value:function(e,t,n){this._verifyNotCommitted();for(var r,i=fh(e,this._firestore),u=arguments.length,o=new Array(u>3?u-3:0),s=3;s<u;s++)o[s-3]=arguments[s];return r="string"==typeof(t=(0,a.getModularInstance)(t))||t instanceof Nl?Xl(this._dataReader,"WriteBatch.update",i._key,t,n,o):Yl(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(r.toMutation(i._key,tr.exists(!0))),this}},{key:"delete",value:function(e){this._verifyNotCommitted();var t=fh(e,this._firestore);return this._mutations=this._mutations.concat(new pr(t._key,tr.none())),this}},{key:"commit",value:function(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}},{key:"_verifyNotCommitted",value:function(){if(this._committed)throw new X(Y.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}]),e}();function fh(e,t){if((e=(0,a.getModularInstance)(e)).firestore!==t)throw new X(Y.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}exports.WriteBatch=lh;var hh=function(e){p(n,e);var t=g(n);function n(e,r){var i;return C(this,n),(i=t.call(this,e,r))._firestore=e,i}return P(n,[{key:"get",value:function(e){var t=this,r=fh(e,this._firestore),i=new Wf(this._firestore);return s(b(n.prototype),"get",this).call(this,e).then(function(e){return new Bf(t._firestore,i,r._key,e._document,new Uf(!1,!1),r.converter)})}}]),n}(function(){function e(t,n){C(this,e),this._firestore=t,this._transaction=n,this._dataReader=Bl(t)}return P(e,[{key:"get",value:function(e){var t=this,n=fh(e,this._firestore),r=new qf(this._firestore);return this._transaction.lookup([n._key]).then(function(e){if(!e||1!==e.length)return j();var i=e[0];if(i.isFoundDocument())return new sf(t._firestore,r,i.key,i,n.converter);if(i.isNoDocument())return new sf(t._firestore,r,n._key,null,n.converter);throw j()})}},{key:"set",value:function(e,t,n){var r=fh(e,this._firestore),i=Of(r.converter,t,n),a=Gl(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,a),this}},{key:"update",value:function(e,t,n){for(var r,i=fh(e,this._firestore),u=arguments.length,o=new Array(u>3?u-3:0),s=3;s<u;s++)o[s-3]=arguments[s];return r="string"==typeof(t=(0,a.getModularInstance)(t))||t instanceof Nl?Xl(this._dataReader,"Transaction.update",i._key,t,n,o):Yl(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,r),this}},{key:"delete",value:function(e){var t=fh(e,this._firestore);return this._transaction.delete(t._key),this}}]),e}());function dh(e,t,n){e=bc(e,vl);var r=Object.assign(Object.assign({},ch),n);return function(e){if(r.maxAttempts<1)throw new X(Y.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(e,t,n){var r=new Z;return e.asyncQueue.enqueueAndForget(function(){var i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.next=2,y().awrap($c(e));case 2:i=a.sent,new Kc(e.asyncQueue,i,n,t,r).run();case 4:case"end":return a.stop()}},null,null,null,Promise)}),r.promise}(ml(e),function(n){return t(new hh(e,n))},r)}function vh(){return new Kl("deleteField")}function yh(){return new jl("serverTimestamp")}function ph(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new zl("arrayUnion",t)}function mh(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new Wl("arrayRemove",t)}function gh(e){return new Hl("increment",e)}function kh(e){return ml(e=bc(e,vl)),new lh(e,function(t){return ah(e,t)})}function wh(e,t){var n,r=ml(e=bc(e,vl));if(!(null===(n=r.offlineComponents)||void 0===n?void 0:n.indexBackfillerScheduler))return K("Cannot enable indexes when persistence is disabled"),Promise.resolve();var i=function(e){var t="string"==typeof e?function(e){try{return JSON.parse(e)}catch(e){throw new X(Y.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,n=[];if(Array.isArray(t.indexes)){var r,i=v(t.indexes);try{for(i.s();!(r=i.n()).done;){var a=r.value,u=xh(a,"collectionGroup"),o=[];if(Array.isArray(a.fields)){var s,c=v(a.fields);try{for(c.s();!(s=c.n()).done;){var l=s.value,f=af("setIndexConfiguration",xh(l,"fieldPath"));"CONTAINS"===l.arrayConfig?o.push(new Ie(f,2)):"ASCENDING"===l.order?o.push(new Ie(f,0)):"DESCENDING"===l.order&&o.push(new Ie(f,1))}}catch(h){c.e(h)}finally{c.f()}}n.push(new ke(ke.UNKNOWN_ID,u,o,Te.empty()))}}catch(h){i.e(h)}finally{i.f()}}return n}(t);return Xc(r).then(function(e){return function(e,t){var n,r,i;return y().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=H(e),r=n.indexManager,i=[],a.abrupt("return",n.persistence.runTransaction("Configure indexes","readwrite",function(e){return r.getFieldIndexes(e).next(function(n){return function(e,t,n,r,i){e=I(e),t=I(t),e.sort(n),t.sort(n);for(var a=e.length,u=t.length,o=0,s=0;o<u&&s<a;){var c=n(e[s],t[o]);c<0?i(e[s++]):c>0?r(t[o++]):(o++,s++)}for(;o<u;)r(t[o++]);for(;s<a;)i(e[s++])}(n,t,be,function(t){i.push(r.addFieldIndex(e,t))},function(t){i.push(r.deleteFieldIndex(e,t))})}).next(function(){return Le.waitFor(i)})}));case 2:case"end":return a.stop()}},null,null,null,Promise)}(e,i)})}function xh(e,t){if("string"!=typeof e[t])throw new X(Y.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}exports.Transaction=hh,function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];!function(e){V=e}(n.SDK_VERSION),(0,n._registerComponent)(new r.Component("firestore",function(e,n){var r=n.instanceIdentifier,i=n.options,a=e.getProvider("app").getImmediate(),u=new vl(new te(e.getProvider("auth-internal")),new ae(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new X(Y.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new We(e.options.projectId,t)}(a,r),a);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u},"PUBLIC").setMultipleInstances(!0)),(0,n.registerVersion)(M,"3.8.3",e),(0,n.registerVersion)(M,"3.8.3","esm2017")}();
|
|
507
|
+
var e,t=require("process");Object.defineProperty(exports,"__esModule",{value:!0}),exports._FieldPath=exports._EmptyAuthCredentialsProvider=exports._EmptyAppCheckTokenProvider=exports._DocumentKey=exports._DatabaseId=exports.WriteBatch=exports.Transaction=exports.Timestamp=exports.SnapshotMetadata=exports.QueryStartAtConstraint=exports.QuerySnapshot=exports.QueryOrderByConstraint=exports.QueryLimitConstraint=exports.QueryFieldFilterConstraint=exports.QueryEndAtConstraint=exports.QueryDocumentSnapshot=exports.QueryConstraint=exports.QueryCompositeFilterConstraint=exports.Query=exports.LoadBundleTask=exports.GeoPoint=exports.FirestoreError=exports.Firestore=exports.FieldValue=exports.FieldPath=exports.DocumentSnapshot=exports.DocumentReference=exports.CollectionReference=exports.CACHE_SIZE_UNLIMITED=exports.Bytes=exports.AggregateQuerySnapshot=exports.AggregateField=exports.AbstractUserDataWriter=void 0,exports._cast=rl,exports._debugAssert=X,exports._isBase64Available=ut,exports._logWarn=j,exports._validateIsNotUsedTogether=$c,exports.addDoc=yh,exports.aggregateFieldEqual=Jf,exports.aggregateQuerySnapshotEqual=Zf,exports.and=_f,exports.arrayRemove=Nh,exports.arrayUnion=Dh,exports.average=Xf,exports.clearIndexedDbPersistence=Al,exports.collection=fl,exports.collectionGroup=hl,exports.connectFirestoreEmulator=ol,exports.count=Yf,exports.deleteDoc=vh,exports.deleteField=_h,exports.disableNetwork=Cl,exports.doc=dl,exports.documentId=Ul,exports.enableIndexedDbPersistence=El,exports.enableMultiTabIndexedDbPersistence=Sl,exports.enableNetwork=Nl,exports.endAt=Vf,exports.endBefore=Of,exports.ensureFirestoreConfigured=Il,exports.executeWrite=gh,exports.getAggregateFromServer=xh,exports.getCountFromServer=wh,exports.getDoc=ah,exports.getDocFromCache=oh,exports.getDocFromServer=sh,exports.getDocs=ch,exports.getDocsFromCache=lh,exports.getDocsFromServer=fh,exports.getFirestore=bl,exports.increment=Ch,exports.initializeFirestore=xl,exports.limit=Cf,exports.limitToLast=Pf,exports.loadBundle=Fl,exports.namedQuery=Ll,exports.onSnapshot=ph,exports.onSnapshotsInSync=mh,exports.or=Sf,exports.orderBy=Df,exports.query=bf,exports.queryEqual=yl,exports.refEqual=vl,exports.runTransaction=Sh,exports.serverTimestamp=Ah,exports.setDoc=hh,exports.setIndexConfiguration=Fh,exports.setLogLevel=K,exports.snapshotEqual=ih,exports.startAfter=Rf,exports.startAt=Lf,exports.sum=Hf,exports.terminate=Pl,exports.updateDoc=dh,exports.waitForPendingWrites=Dl,exports.where=Tf,exports.writeBatch=Ph;var n=require("@firebase/app"),r=require("@firebase/component"),i=require("@firebase/logger"),a=require("@firebase/util"),u=require("@firebase/webchannel-wrapper");function o(){return(o="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=s(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}}).apply(this,arguments)}function s(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=T(e)););return e}function c(e,t){return h(e)||f(e,t)||_(e,t)||l()}function l(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,u,o=[],s=!0,c=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;s=!1}else for(;!(s=(r=a.call(n)).done)&&(o.push(r.value),o.length!==t);s=!0);}catch(l){c=!0,i=l}finally{try{if(!s&&null!=n.return&&(u=n.return(),Object(u)!==u))return}finally{if(c)throw i}}return o}}function h(e){if(Array.isArray(e))return e}function d(e){var t="function"==typeof Map?new Map:void 0;return(d=function(e){if(null===e||!y(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return v(e,arguments,T(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),k(n,e)})(e)}function v(e,t,n){return(v=I()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&k(i,n.prototype),i}).apply(null,arguments)}function y(e){return-1!==Function.toString.call(e).indexOf("[native code]")}function p(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,u=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return u=e.done,e},e:function(e){o=!0,a=e},f:function(){try{u||null==n.return||n.return()}finally{if(o)throw a}}}}function m(){"use strict";m=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r=Object.defineProperty||function(e,t,n){e[t]=n.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",o=i.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(D){s=function(e,t,n){return e[t]=n}}function c(e,t,n,i){var a=t&&t.prototype instanceof h?t:h,u=Object.create(a.prototype),o=new S(i||[]);return r(u,"_invoke",{value:b(e,n,o)}),u}function l(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(D){return{type:"throw",arg:D}}}e.wrap=c;var f={};function h(){}function d(){}function v(){}var y={};s(y,a,function(){return this});var p=Object.getPrototypeOf,g=p&&p(p(_([])));g&&g!==t&&n.call(g,a)&&(y=g);var k=v.prototype=h.prototype=Object.create(y);function w(e){["next","throw","return"].forEach(function(t){s(e,t,function(e){return this._invoke(t,e)})})}function x(e,t){var i;r(this,"_invoke",{value:function(r,a){function u(){return new t(function(i,u){!function r(i,a,u,o){var s=l(e[i],e,a);if("throw"!==s.type){var c=s.arg,f=c.value;return f&&"object"==C(f)&&n.call(f,"__await")?t.resolve(f.__await).then(function(e){r("next",e,u,o)},function(e){r("throw",e,u,o)}):t.resolve(f).then(function(e){c.value=e,u(c)},function(e){return r("throw",e,u,o)})}o(s.arg)}(r,a,i,u)})}return i=i?i.then(u,u):u()}})}function b(e,t,n){var r="suspendedStart";return function(i,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw a;return A()}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var o=I(u,n);if(o){if(o===f)continue;return o}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var s=l(e,t,n);if("normal"===s.type){if(r=n.done?"completed":"suspendedYield",s.arg===f)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(r="completed",n.method="throw",n.arg=s.arg)}}}function I(e,t){var n=t.method,r=e.iterator[n];if(void 0===r)return t.delegate=null,"throw"===n&&e.iterator.return&&(t.method="return",t.arg=void 0,I(e,t),"throw"===t.method)||"return"!==n&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+n+"' method")),f;var i=l(r,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,f;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function S(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function _(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return i.next=i}}return{next:A}}function A(){return{value:void 0,done:!0}}return d.prototype=v,r(k,"constructor",{value:v,configurable:!0}),r(v,"constructor",{value:d,configurable:!0}),d.displayName=s(v,o,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,s(e,o,"GeneratorFunction")),e.prototype=Object.create(k),e},e.awrap=function(e){return{__await:e}},w(x.prototype),s(x.prototype,u,function(){return this}),e.AsyncIterator=x,e.async=function(t,n,r,i,a){void 0===a&&(a=Promise);var u=new x(c(t,n,r,i),a);return e.isGeneratorFunction(n)?u:u.next().then(function(e){return e.done?e.value:u.next()})},w(k),s(k,o,"Generator"),s(k,a,function(){return this}),s(k,"toString",function(){return"[object Generator]"}),e.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},e.values=_,S.prototype={constructor:S,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&n.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(n,r){return u.type="throw",u.arg=e,t.next=n,r&&(t.method="next",t.arg=void 0),!!r}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var o=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(o&&s){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(o){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var u=a?a.completion:{};return u.type=e,u.arg=t,a?(this.method="next",this.next=a.finallyLoc,f):this.complete(u)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),E(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;E(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:_(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},e}function g(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&k(e,t)}function k(e,t){return(k=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function w(e){var t=I();return function(){var n,r=T(e);if(t){var i=T(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x(this,n)}}function x(e,t){if(t&&("object"===C(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return b(e)}function b(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function I(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function T(e){return(T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function E(e){return D(e)||A(e)||_(e)||S()}function S(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _(e,t){if(e){if("string"==typeof e)return N(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?N(e,t):void 0}}function A(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function D(e){if(Array.isArray(e))return N(e)}function N(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function C(e){return(C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function P(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function F(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,R(r.key),r)}}function L(e,t,n){return t&&F(e.prototype,t),n&&F(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function R(e){var t=M(e,"string");return"symbol"===C(t)?t:String(t)}function M(e,t){if("object"!==C(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!==C(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}var O="@firebase/firestore",V=function(){function e(t){P(this,e),this.uid=t}return L(e,[{key:"isAuthenticated",value:function(){return null!=this.uid}},{key:"toKey",value:function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}},{key:"isEqual",value:function(e){return e.uid===this.uid}}]),e}();V.UNAUTHENTICATED=new V(null),V.GOOGLE_CREDENTIALS=new V("google-credentials-uid"),V.FIRST_PARTY=new V("first-party-uid"),V.MOCK_USER=new V("mock-user");var q="9.18.0",U=new i.Logger("@firebase/firestore");function B(){return U.logLevel}function K(e){U.setLogLevel(e)}function G(e){if(U.logLevel<=i.LogLevel.DEBUG){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a=n.map(z);U.debug.apply(U,["Firestore (".concat(q,"): ").concat(e)].concat(E(a)))}}function Q(e){if(U.logLevel<=i.LogLevel.ERROR){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a=n.map(z);U.error.apply(U,["Firestore (".concat(q,"): ").concat(e)].concat(E(a)))}}function j(e){if(U.logLevel<=i.LogLevel.WARN){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a=n.map(z);U.warn.apply(U,["Firestore (".concat(q,"): ").concat(e)].concat(E(a)))}}function z(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}var t}function W(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected state",t="FIRESTORE (".concat(q,") INTERNAL ASSERTION FAILED: ")+e;throw Q(t),new Error(t)}function H(e,t){e||W()}function X(e,t){e||W()}function Y(e,t){return e}var J={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"},Z=function(e){g(n,a.FirebaseError);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e,r)).code=e,i.message=r,i.toString=function(){return"".concat(i.name,": [code=").concat(i.code,"]: ").concat(i.message)},i}return L(n)}();exports.FirestoreError=Z;var $=L(function e(){var t=this;P(this,e),this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}),ee=L(function e(t,n){P(this,e),this.user=n,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization","Bearer ".concat(t))}),te=function(){function e(){P(this,e)}return L(e,[{key:"getToken",value:function(){return Promise.resolve(null)}},{key:"invalidateToken",value:function(){}},{key:"start",value:function(e,t){e.enqueueRetryable(function(){return t(V.UNAUTHENTICATED)})}},{key:"shutdown",value:function(){}}]),e}();exports._EmptyAuthCredentialsProvider=te;var ne=function(){function e(t){P(this,e),this.token=t,this.changeListener=null}return L(e,[{key:"getToken",value:function(){return Promise.resolve(this.token)}},{key:"invalidateToken",value:function(){}},{key:"start",value:function(e,t){var n=this;this.changeListener=t,e.enqueueRetryable(function(){return t(n.token.user)})}},{key:"shutdown",value:function(){this.changeListener=null}}]),e}(),re=function(){function e(t){P(this,e),this.t=t,this.currentUser=V.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}return L(e,[{key:"start",value:function(e,t){var n=this,r=this.i,i=function(e){return n.i!==r?(r=n.i,t(e)):Promise.resolve()},a=new $;this.o=function(){n.i++,n.currentUser=n.u(),a.resolve(),a=new $,e.enqueueRetryable(function(){return i(n.currentUser)})};var u=function(){var t=a;e.enqueueRetryable(function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,m().awrap(t.promise);case 2:return e.next=4,m().awrap(i(n.currentUser));case 4:case"end":return e.stop()}},null,null,null,Promise)})},o=function(e){G("FirebaseAuthCredentialsProvider","Auth detected"),n.auth=e,n.auth.addAuthTokenListener(n.o),u()};this.t.onInit(function(e){return o(e)}),setTimeout(function(){if(!n.auth){var e=n.t.getImmediate({optional:!0});e?o(e):(G("FirebaseAuthCredentialsProvider","Auth not yet detected"),a.resolve(),a=new $)}},0),u()}},{key:"getToken",value:function(){var e=this,t=this.i,n=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(n).then(function(n){return e.i!==t?(G("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),e.getToken()):n?(H("string"==typeof n.accessToken),new ee(n.accessToken,e.currentUser)):null}):Promise.resolve(null)}},{key:"invalidateToken",value:function(){this.forceRefresh=!0}},{key:"shutdown",value:function(){this.auth&&this.auth.removeAuthTokenListener(this.o)}},{key:"u",value:function(){var e=this.auth&&this.auth.getUid();return H(null===e||"string"==typeof e),new V(e)}}]),e}(),ie=function(){function e(t,n,r,i){P(this,e),this.h=t,this.l=n,this.m=r,this.g=i,this.type="FirstParty",this.user=V.FIRST_PARTY,this.p=new Map}return L(e,[{key:"I",value:function(){return this.g?this.g():(H(!("object"!=C(this.h)||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}},{key:"headers",get:function(){this.p.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}]),e}(),ae=function(){function e(t,n,r,i){P(this,e),this.h=t,this.l=n,this.m=r,this.g=i}return L(e,[{key:"getToken",value:function(){return Promise.resolve(new ie(this.h,this.l,this.m,this.g))}},{key:"start",value:function(e,t){e.enqueueRetryable(function(){return t(V.FIRST_PARTY)})}},{key:"shutdown",value:function(){}},{key:"invalidateToken",value:function(){}}]),e}(),ue=L(function e(t){P(this,e),this.value=t,this.type="AppCheck",this.headers=new Map,t&&t.length>0&&this.headers.set("x-firebase-appcheck",this.value)}),oe=function(){function e(t){P(this,e),this.T=t,this.forceRefresh=!1,this.appCheck=null,this.A=null}return L(e,[{key:"start",value:function(e,t){var n=this,r=function(e){null!=e.error&&G("FirebaseAppCheckTokenProvider","Error getting App Check token; using placeholder token instead. Error: ".concat(e.error.message));var r=e.token!==n.A;return n.A=e.token,G("FirebaseAppCheckTokenProvider","Received ".concat(r?"new":"existing"," token.")),r?t(e.token):Promise.resolve()};this.o=function(t){e.enqueueRetryable(function(){return r(t)})};var i=function(e){G("FirebaseAppCheckTokenProvider","AppCheck detected"),n.appCheck=e,n.appCheck.addTokenListener(n.o)};this.T.onInit(function(e){return i(e)}),setTimeout(function(){if(!n.appCheck){var e=n.T.getImmediate({optional:!0});e?i(e):G("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}},{key:"getToken",value:function(){var e=this,t=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(t).then(function(t){return t?(H("string"==typeof t.token),e.A=t.token,new ue(t.token)):null}):Promise.resolve(null)}},{key:"invalidateToken",value:function(){this.forceRefresh=!0}},{key:"shutdown",value:function(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}]),e}(),se=function(){function e(){P(this,e)}return L(e,[{key:"getToken",value:function(){return Promise.resolve(new ue(""))}},{key:"invalidateToken",value:function(){}},{key:"start",value:function(e,t){}},{key:"shutdown",value:function(){}}]),e}();function ce(e){var t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(var r=0;r<e;r++)n[r]=Math.floor(256*Math.random());return n}exports._EmptyAppCheckTokenProvider=se;var le=function(){function e(){P(this,e)}return L(e,null,[{key:"R",value:function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Math.floor(256/e.length)*e.length,n="";n.length<20;)for(var r=ce(40),i=0;i<r.length;++i)n.length<20&&r[i]<t&&(n+=e.charAt(r[i]%e.length));return n}}]),e}();function fe(e,t){return e<t?-1:e>t?1:0}function he(e,t,n){return e.length===t.length&&e.every(function(e,r){return n(e,t[r])})}function de(e){return e+"\0"}var ve=function(){function e(t,n){if(P(this,e),this.seconds=t,this.nanoseconds=n,n<0)throw new Z(J.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+n);if(n>=1e9)throw new Z(J.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+n);if(t<-62135596800)throw new Z(J.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new Z(J.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}return L(e,[{key:"toDate",value:function(){return new Date(this.toMillis())}},{key:"toMillis",value:function(){return 1e3*this.seconds+this.nanoseconds/1e6}},{key:"_compareTo",value:function(e){return this.seconds===e.seconds?fe(this.nanoseconds,e.nanoseconds):fe(this.seconds,e.seconds)}},{key:"isEqual",value:function(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}},{key:"toString",value:function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}},{key:"toJSON",value:function(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}},{key:"valueOf",value:function(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}],[{key:"now",value:function(){return e.fromMillis(Date.now())}},{key:"fromDate",value:function(t){return e.fromMillis(t.getTime())}},{key:"fromMillis",value:function(t){var n=Math.floor(t/1e3);return new e(n,Math.floor(1e6*(t-1e3*n)))}}]),e}();exports.Timestamp=ve;var ye=function(){function e(t){P(this,e),this.timestamp=t}return L(e,[{key:"compareTo",value:function(e){return this.timestamp._compareTo(e.timestamp)}},{key:"isEqual",value:function(e){return this.timestamp.isEqual(e.timestamp)}},{key:"toMicroseconds",value:function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}},{key:"toString",value:function(){return"SnapshotVersion("+this.timestamp.toString()+")"}},{key:"toTimestamp",value:function(){return this.timestamp}}],[{key:"fromTimestamp",value:function(t){return new e(t)}},{key:"min",value:function(){return new e(new ve(0,0))}},{key:"max",value:function(){return new e(new ve(253402300799,999999999))}}]),e}(),pe=function(){function e(t,n,r){P(this,e),void 0===n?n=0:n>t.length&&W(),void 0===r?r=t.length-n:r>t.length-n&&W(),this.segments=t,this.offset=n,this.len=r}return L(e,[{key:"length",get:function(){return this.len}},{key:"isEqual",value:function(t){return 0===e.comparator(this,t)}},{key:"child",value:function(t){var n=this.segments.slice(this.offset,this.limit());return t instanceof e?t.forEach(function(e){n.push(e)}):n.push(t),this.construct(n)}},{key:"limit",value:function(){return this.offset+this.length}},{key:"popFirst",value:function(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}},{key:"popLast",value:function(){return this.construct(this.segments,this.offset,this.length-1)}},{key:"firstSegment",value:function(){return this.segments[this.offset]}},{key:"lastSegment",value:function(){return this.get(this.length-1)}},{key:"get",value:function(e){return this.segments[this.offset+e]}},{key:"isEmpty",value:function(){return 0===this.length}},{key:"isPrefixOf",value:function(e){if(e.length<this.length)return!1;for(var t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}},{key:"isImmediateParentOf",value:function(e){if(this.length+1!==e.length)return!1;for(var t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}},{key:"forEach",value:function(e){for(var t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}},{key:"toArray",value:function(){return this.segments.slice(this.offset,this.limit())}}],[{key:"comparator",value:function(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var i=e.get(r),a=t.get(r);if(i<a)return-1;if(i>a)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}]),e}(),me=function(e){g(n,pe);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n,[{key:"construct",value:function(e,t,r){return new n(e,t,r)}},{key:"canonicalString",value:function(){return this.toArray().join("/")}},{key:"toString",value:function(){return this.canonicalString()}}],[{key:"fromString",value:function(){for(var e=[],t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];for(var a=0,u=r;a<u.length;a++){var o=u[a];if(o.indexOf("//")>=0)throw new Z(J.INVALID_ARGUMENT,"Invalid segment (".concat(o,"). Paths must not contain // in them."));e.push.apply(e,E(o.split("/").filter(function(e){return e.length>0})))}return new n(e)}},{key:"emptyPath",value:function(){return new n([])}}]),n}(),ge=/^[_a-zA-Z][_a-zA-Z0-9]*$/,ke=function(e){g(n,pe);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n,[{key:"construct",value:function(e,t,r){return new n(e,t,r)}},{key:"canonicalString",value:function(){return this.toArray().map(function(e){return e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),n.isValidIdentifier(e)||(e="`"+e+"`"),e}).join(".")}},{key:"toString",value:function(){return this.canonicalString()}},{key:"isKeyField",value:function(){return 1===this.length&&"__name__"===this.get(0)}}],[{key:"isValidIdentifier",value:function(e){return ge.test(e)}},{key:"keyField",value:function(){return new n(["__name__"])}},{key:"fromServerFormat",value:function(e){for(var t=[],r="",i=0,a=function(){if(0===r.length)throw new Z(J.INVALID_ARGUMENT,"Invalid field path (".concat(e,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"));t.push(r),r=""},u=!1;i<e.length;){var o=e[i];if("\\"===o){if(i+1===e.length)throw new Z(J.INVALID_ARGUMENT,"Path has trailing escape character: "+e);var s=e[i+1];if("\\"!==s&&"."!==s&&"`"!==s)throw new Z(J.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=s,i+=2}else"`"===o?(u=!u,i++):"."!==o||u?(r+=o,i++):(a(),i++)}if(a(),u)throw new Z(J.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new n(t)}},{key:"emptyPath",value:function(){return new n([])}}]),n}();exports._FieldPath=ke;var we=function(){function e(t){P(this,e),this.path=t}return L(e,[{key:"collectionGroup",get:function(){return this.path.popLast().lastSegment()}},{key:"hasCollectionId",value:function(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}},{key:"getCollectionGroup",value:function(){return this.path.get(this.path.length-2)}},{key:"getCollectionPath",value:function(){return this.path.popLast()}},{key:"isEqual",value:function(e){return null!==e&&0===me.comparator(this.path,e.path)}},{key:"toString",value:function(){return this.path.toString()}}],[{key:"fromPath",value:function(t){return new e(me.fromString(t))}},{key:"fromName",value:function(t){return new e(me.fromString(t).popFirst(5))}},{key:"empty",value:function(){return new e(me.emptyPath())}},{key:"comparator",value:function(e,t){return me.comparator(e.path,t.path)}},{key:"isDocumentKey",value:function(e){return e.length%2==0}},{key:"fromSegments",value:function(t){return new e(new me(t.slice()))}}]),e}();exports._DocumentKey=we;var xe=L(function e(t,n,r,i){P(this,e),this.indexId=t,this.collectionGroup=n,this.fields=r,this.indexState=i});function be(e){return e.fields.find(function(e){return 2===e.kind})}function Ie(e){return e.fields.filter(function(e){return 2!==e.kind})}function Te(e,t){var n=fe(e.collectionGroup,t.collectionGroup);if(0!==n)return n;for(var r=0;r<Math.min(e.fields.length,t.fields.length);++r)if(0!==(n=Se(e.fields[r],t.fields[r])))return n;return fe(e.fields.length,t.fields.length)}xe.UNKNOWN_ID=-1;var Ee=L(function e(t,n){P(this,e),this.fieldPath=t,this.kind=n});function Se(e,t){var n=ke.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:fe(e.kind,t.kind)}var _e=function(){function e(t,n){P(this,e),this.sequenceNumber=t,this.offset=n}return L(e,null,[{key:"empty",value:function(){return new e(0,Ne.min())}}]),e}();function Ae(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=ye.fromTimestamp(1e9===r?new ve(n+1,0):new ve(n,r));return new Ne(i,we.empty(),t)}function De(e){return new Ne(e.readTime,e.key,-1)}var Ne=function(){function e(t,n,r){P(this,e),this.readTime=t,this.documentKey=n,this.largestBatchId=r}return L(e,null,[{key:"min",value:function(){return new e(ye.min(),we.empty(),-1)}},{key:"max",value:function(){return new e(ye.max(),we.empty(),-1)}}]),e}();function Ce(e,t){var n=e.readTime.compareTo(t.readTime);return 0!==n?n:0!==(n=we.comparator(e.documentKey,t.documentKey))?n:fe(e.largestBatchId,t.largestBatchId)}var Pe="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",Fe=function(){function e(){P(this,e),this.onCommittedListeners=[]}return L(e,[{key:"addOnCommittedListener",value:function(e){this.onCommittedListeners.push(e)}},{key:"raiseOnCommittedEvent",value:function(){this.onCommittedListeners.forEach(function(e){return e()})}}]),e}();function Le(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(e.code===J.FAILED_PRECONDITION&&e.message===Pe){t.next=2;break}throw e;case 2:G("LocalStore","Unexpectedly lost primary lease");case 3:case"end":return t.stop()}},null,null,null,Promise)}var Re=function(){function e(t){var n=this;P(this,e),this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t(function(e){n.isDone=!0,n.result=e,n.nextCallback&&n.nextCallback(e)},function(e){n.isDone=!0,n.error=e,n.catchCallback&&n.catchCallback(e)})}return L(e,[{key:"catch",value:function(e){return this.next(void 0,e)}},{key:"next",value:function(t,n){var r=this;return this.callbackAttached&&W(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(t,this.result):new e(function(e,i){r.nextCallback=function(n){r.wrapSuccess(t,n).next(e,i)},r.catchCallback=function(t){r.wrapFailure(n,t).next(e,i)}})}},{key:"toPromise",value:function(){var e=this;return new Promise(function(t,n){e.next(t,n)})}},{key:"wrapUserFunction",value:function(t){try{var n=t();return n instanceof e?n:e.resolve(n)}catch(t){return e.reject(t)}}},{key:"wrapSuccess",value:function(t,n){return t?this.wrapUserFunction(function(){return t(n)}):e.resolve(n)}},{key:"wrapFailure",value:function(t,n){return t?this.wrapUserFunction(function(){return t(n)}):e.reject(n)}}],[{key:"resolve",value:function(t){return new e(function(e,n){e(t)})}},{key:"reject",value:function(t){return new e(function(e,n){n(t)})}},{key:"waitFor",value:function(t){return new e(function(e,n){var r=0,i=0,a=!1;t.forEach(function(t){++r,t.next(function(){++i,a&&i===r&&e()},function(e){return n(e)})}),a=!0,i===r&&e()})}},{key:"or",value:function(t){var n,r=e.resolve(!1),i=p(t);try{var a=function(){var t=n.value;r=r.next(function(n){return n?e.resolve(n):t()})};for(i.s();!(n=i.n()).done;)a()}catch(u){i.e(u)}finally{i.f()}return r}},{key:"forEach",value:function(e,t){var n=this,r=[];return e.forEach(function(e,i){r.push(t.call(n,e,i))}),this.waitFor(r)}},{key:"mapArray",value:function(t,n){return new e(function(e,r){for(var i=t.length,a=new Array(i),u=0,o=function(){var o=s;n(t[o]).next(function(t){a[o]=t,++u===i&&e(a)},function(e){return r(e)})},s=0;s<i;s++)o()})}},{key:"doWhile",value:function(t,n){return new e(function(e,r){!function i(){!0===t()?n().next(function(){i()},r):e()}()})}}]),e}(),Me=function(){function e(t,n){var r=this;P(this,e),this.action=t,this.transaction=n,this.aborted=!1,this.P=new $,this.transaction.oncomplete=function(){r.P.resolve()},this.transaction.onabort=function(){n.error?r.P.reject(new qe(t,n.error)):r.P.resolve()},this.transaction.onerror=function(e){var n=Qe(e.target.error);r.P.reject(new qe(t,n))}}return L(e,[{key:"v",get:function(){return this.P.promise}},{key:"abort",value:function(e){e&&this.P.reject(e),this.aborted||(G("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}},{key:"V",value:function(){var e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}},{key:"store",value:function(e){var t=this.transaction.objectStore(e);return new Be(t)}}],[{key:"open",value:function(t,n,r,i){try{return new e(n,t.transaction(i,r))}catch(t){throw new qe(n,t)}}}]),e}(),Oe=function(){function e(t,n,r){P(this,e),this.name=t,this.version=n,this.S=r,12.2===e.D((0,a.getUA)())&&Q("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}return L(e,[{key:"O",value:function(e){var t=this;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=this.db,n.t0){n.next=6;break}return G("SimpleDb","Opening database:",this.name),n.next=5,m().awrap(new Promise(function(n,r){var i=indexedDB.open(t.name,t.version);i.onsuccess=function(e){var t=e.target.result;n(t)},i.onblocked=function(){r(new qe(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=function(t){var n=t.target.error;"VersionError"===n.name?r(new Z(J.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===n.name?r(new Z(J.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+n)):r(new qe(e,n))},i.onupgradeneeded=function(e){G("SimpleDb",'Database "'+t.name+'" requires upgrade from version:',e.oldVersion);var n=e.target.result;t.S.F(n,i.transaction,e.oldVersion,t.version).next(function(){G("SimpleDb","Database upgrade to version "+t.version+" complete")})}}));case 5:this.db=n.sent;case 6:return this.B&&(this.db.onversionchange=function(e){return t.B(e)}),n.abrupt("return",this.db);case 8:case"end":return n.stop()}},null,this,null,Promise)}},{key:"L",value:function(e){this.B=e,this.db&&(this.db.onversionchange=function(t){return e(t)})}},{key:"runTransaction",value:function(e,t,n,r){var i,a,u,o,s=this;return m().async(function(c){for(;;)switch(c.prev=c.next){case 0:i="readonly"===t,a=0,u=function(){var t,u,o,c;return m().async(function(l){for(;;)switch(l.prev=l.next){case 0:return++a,l.prev=1,l.next=4,m().awrap(s.O(e));case 4:return s.db=l.sent,t=Me.open(s.db,e,i?"readonly":"readwrite",n),(u=r(t).next(function(e){return t.V(),e}).catch(function(e){return t.abort(e),Re.reject(e)}).toPromise()).catch(function(){}),l.next=9,m().awrap(t.v);case 9:return l.t0=u,l.abrupt("return",{v:l.t0});case 13:if(l.prev=13,l.t1=l.catch(1),o=l.t1,c="FirebaseError"!==o.name&&a<3,G("SimpleDb","Transaction failed with error:",o.message,"Retrying:",c),s.close(),c){l.next=18;break}return l.abrupt("return",{v:Promise.reject(o)});case 18:case"end":return l.stop()}},null,null,[[1,13]],Promise)};case 3:return c.next=5,m().awrap(u());case 5:if("object"!==C(o=c.sent)){c.next=8;break}return c.abrupt("return",o.v);case 8:c.next=3;break;case 10:case"end":return c.stop()}},null,null,null,Promise)}},{key:"close",value:function(){this.db&&this.db.close(),this.db=void 0}}],[{key:"delete",value:function(e){return G("SimpleDb","Removing database:",e),Ke(window.indexedDB.deleteDatabase(e)).toPromise()}},{key:"C",value:function(){if(!(0,a.isIndexedDBAvailable)())return!1;if(e.N())return!0;var t=(0,a.getUA)(),n=e.D(t),r=0<n&&n<10,i=e.k(t),u=0<i&&i<4.5;return!(t.indexOf("MSIE ")>0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0||r||u)}},{key:"N",value:function(){var e;return void 0!==t&&"YES"===(null===(e=t.env)||void 0===e?void 0:e.$)}},{key:"M",value:function(e,t){return e.store(t)}},{key:"D",value:function(e){var t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}},{key:"k",value:function(e){var t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}}]),e}(),Ve=function(){function e(t){P(this,e),this.q=t,this.U=!1,this.K=null}return L(e,[{key:"isDone",get:function(){return this.U}},{key:"G",get:function(){return this.K}},{key:"cursor",set:function(e){this.q=e}},{key:"done",value:function(){this.U=!0}},{key:"j",value:function(e){this.K=e}},{key:"delete",value:function(){return Ke(this.q.delete())}}]),e}(),qe=function(e){g(n,Z);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,J.UNAVAILABLE,"IndexedDB transaction '".concat(e,"' failed: ").concat(r))).name="IndexedDbTransactionError",i}return L(n)}();function Ue(e){return"IndexedDbTransactionError"===e.name}var Be=function(){function e(t){P(this,e),this.store=t}return L(e,[{key:"put",value:function(e,t){var n;return void 0!==t?(G("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(G("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),Ke(n)}},{key:"add",value:function(e){return G("SimpleDb","ADD",this.store.name,e,e),Ke(this.store.add(e))}},{key:"get",value:function(e){var t=this;return Ke(this.store.get(e)).next(function(n){return void 0===n&&(n=null),G("SimpleDb","GET",t.store.name,e,n),n})}},{key:"delete",value:function(e){return G("SimpleDb","DELETE",this.store.name,e),Ke(this.store.delete(e))}},{key:"count",value:function(){return G("SimpleDb","COUNT",this.store.name),Ke(this.store.count())}},{key:"W",value:function(e,t){var n=this.options(e,t);if(n.index||"function"!=typeof this.store.getAll){var r=this.cursor(n),i=[];return this.H(r,function(e,t){i.push(t)}).next(function(){return i})}var a=this.store.getAll(n.range);return new Re(function(e,t){a.onerror=function(e){t(e.target.error)},a.onsuccess=function(t){e(t.target.result)}})}},{key:"J",value:function(e,t){var n=this.store.getAll(e,null===t?void 0:t);return new Re(function(e,t){n.onerror=function(e){t(e.target.error)},n.onsuccess=function(t){e(t.target.result)}})}},{key:"Y",value:function(e,t){G("SimpleDb","DELETE ALL",this.store.name);var n=this.options(e,t);n.Z=!1;var r=this.cursor(n);return this.H(r,function(e,t,n){return n.delete()})}},{key:"X",value:function(e,t){var n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.H(r,t)}},{key:"tt",value:function(e){var t=this.cursor({});return new Re(function(n,r){t.onerror=function(e){var t=Qe(e.target.error);r(t)},t.onsuccess=function(t){var r=t.target.result;r?e(r.primaryKey,r.value).next(function(e){e?r.continue():n()}):n()}})}},{key:"H",value:function(e,t){var n=[];return new Re(function(r,i){e.onerror=function(e){i(e.target.error)},e.onsuccess=function(e){var i=e.target.result;if(i){var a=new Ve(i),u=t(i.primaryKey,i.value,a);if(u instanceof Re){var o=u.catch(function(e){return a.done(),Re.reject(e)});n.push(o)}a.isDone?r():null===a.G?i.continue():i.continue(a.G)}else r()}}).next(function(){return Re.waitFor(n)})}},{key:"options",value:function(e,t){var n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}},{key:"cursor",value:function(e){var t="next";if(e.reverse&&(t="prev"),e.index){var n=this.store.index(e.index);return e.Z?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}]),e}();function Ke(e){return new Re(function(t,n){e.onsuccess=function(e){var n=e.target.result;t(n)},e.onerror=function(e){var t=Qe(e.target.error);n(t)}})}var Ge=!1;function Qe(e){var t=Oe.D((0,a.getUA)());if(t>=12.2&&t<13){var n="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(n)>=0){var r=new Z("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '".concat(n,"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."));return Ge||(Ge=!0,setTimeout(function(){throw r},0)),r}}return e}var je=function(){function e(t,n){P(this,e),this.asyncQueue=t,this.et=n,this.task=null}return L(e,[{key:"start",value:function(){this.nt(15e3)}},{key:"stop",value:function(){this.task&&(this.task.cancel(),this.task=null)}},{key:"started",get:function(){return null!==this.task}},{key:"nt",value:function(e){var t=this;G("IndexBackiller","Scheduled in ".concat(e,"ms")),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return t.task=null,e.prev=1,e.t0=G,e.t1="Documents written: ",e.next=6,m().awrap(t.et.st());case 6:e.t2=e.sent,e.t3=e.t1.concat.call(e.t1,e.t2),(0,e.t0)("IndexBackiller",e.t3),e.next=19;break;case 11:if(e.prev=11,e.t4=e.catch(1),!Ue(e.t4)){e.next=17;break}G("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e.t4),e.next=19;break;case 17:return e.next=19,m().awrap(Le(e.t4));case 19:return e.next=21,m().awrap(t.nt(6e4));case 21:case"end":return e.stop()}},null,null,[[1,11]],Promise)})}}]),e}(),ze=function(){function e(t,n){P(this,e),this.localStore=t,this.persistence=n}return L(e,[{key:"st",value:function(){var e,t=this,n=arguments;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return e=n.length>0&&void 0!==n[0]?n[0]:50,r.abrupt("return",this.persistence.runTransaction("Backfill Indexes","readwrite-primary",function(n){return t.it(n,e)}));case 2:case"end":return r.stop()}},null,this,null,Promise)}},{key:"it",value:function(e,t){var n=this,r=new Set,i=t,a=!0;return Re.doWhile(function(){return!0===a&&i>0},function(){return n.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(function(t){if(null!==t&&!r.has(t))return G("IndexBackiller","Processing collection: ".concat(t)),n.rt(e,t,i).next(function(e){i-=e,r.add(t)});a=!1})}).next(function(){return t-i})}},{key:"rt",value:function(e,t,n){var r=this;return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(function(i){return r.localStore.localDocuments.getNextDocuments(e,t,i,n).next(function(n){var a=n.changes;return r.localStore.indexManager.updateIndexEntries(e,a).next(function(){return r.ot(i,n)}).next(function(n){return G("IndexBackiller","Updating offset: ".concat(n)),r.localStore.indexManager.updateCollectionGroup(e,t,n)}).next(function(){return a.size})})})}},{key:"ot",value:function(e,t){var n=e;return t.changes.forEach(function(e,t){var r=De(t);Ce(r,n)>0&&(n=r)}),new Ne(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}]),e}(),We=function(){function e(t,n){var r=this;P(this,e),this.previousValue=t,n&&(n.sequenceNumberHandler=function(e){return r.ut(e)},this.ct=function(e){return n.writeSequenceNumber(e)})}return L(e,[{key:"ut",value:function(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}},{key:"next",value:function(){var e=++this.previousValue;return this.ct&&this.ct(e),e}}]),e}();We.at=-1;var He=/^[_a-zA-Z][_a-zA-Z0-9]*(?:\.[_a-zA-Z][_a-zA-Z0-9]*)*$/,Xe=function(){function e(t){P(this,e),this.alias=t}return L(e,[{key:"canonicalString",value:function(){var t=this.alias.replace(/\\/g,"\\\\").replace(/`/g,"\\`");return e.ht(t)||(t="`"+t+"`"),t}}],[{key:"ht",value:function(e){return He.test(e)}}]),e}(),Ye=L(function e(t,n,r){P(this,e),this.alias=t,this.lt=n,this.fieldPath=r}),Je=L(function e(t,n,r,i,a,u,o,s){P(this,e),this.databaseId=t,this.appId=n,this.persistenceKey=r,this.host=i,this.ssl=a,this.forceLongPolling=u,this.autoDetectLongPolling=o,this.useFetchStreams=s}),Ze=function(){function e(t,n){P(this,e),this.projectId=t,this.database=n||"(default)"}return L(e,[{key:"isDefaultDatabase",get:function(){return"(default)"===this.database}},{key:"isEqual",value:function(t){return t instanceof e&&t.projectId===this.projectId&&t.database===this.database}}],[{key:"empty",value:function(){return new e("","")}}]),e}();function $e(e){var t=0;for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function et(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function tt(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function nt(e){return null==e}function rt(e){return 0===e&&1/e==-1/0}function it(e){return"number"==typeof e&&Number.isInteger(e)&&!rt(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}exports._DatabaseId=Ze;var at=function(e){g(n,d(Error));var t=w(n);function n(){var e;return P(this,n),(e=t.apply(this,arguments)).name="Base64DecodeError",e}return L(n)}();function ut(){return"undefined"!=typeof atob}var ot=function(e){function t(e){P(this,t),this.binaryString=e}return L(t,[{key:Symbol.iterator,value:function(){var e=this,t=0;return{next:function(){return t<e.binaryString.length?{value:e.binaryString.charCodeAt(t++),done:!1}:{value:void 0,done:!0}}}}},{key:"toBase64",value:function(){return e=this.binaryString,btoa(e);var e}},{key:"toUint8Array",value:function(){return function(e){for(var t=new Uint8Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}},{key:"approximateByteSize",value:function(){return 2*this.binaryString.length}},{key:"compareTo",value:function(e){return fe(this.binaryString,e.binaryString)}},{key:"isEqual",value:function(e){return this.binaryString===e.binaryString}}],[{key:"fromBase64String",value:function(e){return new t(function(e){try{return atob(e)}catch(e){throw e instanceof DOMException?new at("Invalid base64 string: "+e):e}}(e))}},{key:"fromUint8Array",value:function(e){return new t(function(e){for(var t="",n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e))}}]),t}();ot.EMPTY_BYTE_STRING=new ot("");var st=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ct(e){if(H(!!e),"string"==typeof e){var t=0,n=st.exec(e);if(H(!!n),n[1]){var r=n[1];r=(r+"000000000").substr(0,9),t=Number(r)}var i=new Date(e);return{seconds:Math.floor(i.getTime()/1e3),nanos:t}}return{seconds:lt(e.seconds),nanos:lt(e.nanos)}}function lt(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function ft(e){return"string"==typeof e?ot.fromBase64String(e):ot.fromUint8Array(e)}function ht(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function dt(e){var t=e.mapValue.fields.__previous_value__;return ht(t)?dt(t):t}function vt(e){var t=ct(e.mapValue.fields.__local_write_time__.timestampValue);return new ve(t.seconds,t.nanos)}var yt={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},pt={nullValue:"NULL_VALUE"};function mt(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?ht(e)?4:Ct(e)?9007199254740991:10:W()}function gt(e,t){if(e===t)return!0;var n=mt(e);if(n!==mt(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return vt(e).isEqual(vt(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;var n=ct(e.timestampValue),r=ct(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 ft(e.bytesValue).isEqual(ft(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return lt(e.geoPointValue.latitude)===lt(t.geoPointValue.latitude)&<(e.geoPointValue.longitude)===lt(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return lt(e.integerValue)===lt(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=lt(e.doubleValue),r=lt(t.doubleValue);return n===r?rt(n)===rt(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return he(e.arrayValue.values||[],t.arrayValue.values||[],gt);case 10:return function(e,t){var n=e.mapValue.fields||{},r=t.mapValue.fields||{};if($e(n)!==$e(r))return!1;for(var i in n)if(n.hasOwnProperty(i)&&(void 0===r[i]||!gt(n[i],r[i])))return!1;return!0}(e,t);default:return W()}}function kt(e,t){return void 0!==(e.values||[]).find(function(e){return gt(e,t)})}function wt(e,t){if(e===t)return 0;var n=mt(e),r=mt(t);if(n!==r)return fe(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return fe(e.booleanValue,t.booleanValue);case 2:return function(e,t){var n=lt(e.integerValue||e.doubleValue),r=lt(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return xt(e.timestampValue,t.timestampValue);case 4:return xt(vt(e),vt(t));case 5:return fe(e.stringValue,t.stringValue);case 6:return function(e,t){var n=ft(e),r=ft(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){for(var n=e.split("/"),r=t.split("/"),i=0;i<n.length&&i<r.length;i++){var a=fe(n[i],r[i]);if(0!==a)return a}return fe(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){var n=fe(lt(e.latitude),lt(t.latitude));return 0!==n?n:fe(lt(e.longitude),lt(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){for(var n=e.values||[],r=t.values||[],i=0;i<n.length&&i<r.length;++i){var a=wt(n[i],r[i]);if(a)return a}return fe(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===yt.mapValue&&t===yt.mapValue)return 0;if(e===yt.mapValue)return 1;if(t===yt.mapValue)return-1;var n=e.fields||{},r=Object.keys(n),i=t.fields||{},a=Object.keys(i);r.sort(),a.sort();for(var u=0;u<r.length&&u<a.length;++u){var o=fe(r[u],a[u]);if(0!==o)return o;var s=wt(n[r[u]],i[a[u]]);if(0!==s)return s}return fe(r.length,a.length)}(e.mapValue,t.mapValue);default:throw W()}}function xt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return fe(e,t);var n=ct(e),r=ct(t),i=fe(n.seconds,r.seconds);return 0!==i?i:fe(n.nanos,r.nanos)}function bt(e){return It(e)}function It(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){var t=ct(e);return"time(".concat(t.seconds,",").concat(t.nanos,")")}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?ft(e.bytesValue).toBase64():"referenceValue"in e?(n=e.referenceValue,we.fromName(n).toString()):"geoPointValue"in e?"geo(".concat((t=e.geoPointValue).latitude,",").concat(t.longitude,")"):"arrayValue"in e?function(e){var t,n="[",r=!0,i=p(e.values||[]);try{for(i.s();!(t=i.n()).done;){var a=t.value;r?r=!1:n+=",",n+=It(a)}}catch(u){i.e(u)}finally{i.f()}return n+"]"}(e.arrayValue):"mapValue"in e?function(e){var t,n="{",r=!0,i=p(Object.keys(e.fields||{}).sort());try{for(i.s();!(t=i.n()).done;){var a=t.value;r?r=!1:n+=",",n+="".concat(a,":").concat(It(e.fields[a]))}}catch(u){i.e(u)}finally{i.f()}return n+"}"}(e.mapValue):W();var t,n}function Tt(e,t){return{referenceValue:"projects/".concat(e.projectId,"/databases/").concat(e.database,"/documents/").concat(t.path.canonicalString())}}function Et(e){return!!e&&"integerValue"in e}function St(e){return!!e&&"arrayValue"in e}function _t(e){return!!e&&"nullValue"in e}function At(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Dt(e){return!!e&&"mapValue"in e}function Nt(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==C(e.timestampValue))return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){var t={mapValue:{fields:{}}};return et(e.mapValue.fields,function(e,n){return t.mapValue.fields[e]=Nt(n)}),t}if(e.arrayValue){for(var n={arrayValue:{values:[]}},r=0;r<(e.arrayValue.values||[]).length;++r)n.arrayValue.values[r]=Nt(e.arrayValue.values[r]);return n}return Object.assign({},e)}function Ct(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Pt(e){return"nullValue"in e?pt:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?Tt(Ze.empty(),we.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?{mapValue:{}}:W()}function Ft(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?Tt(Ze.empty(),we.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?{mapValue:{}}:"mapValue"in e?yt:W()}function Lt(e,t){var n=wt(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Rt(e,t){var n=wt(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}var Mt=L(function e(t,n){P(this,e),this.position=t,this.inclusive=n});function Ot(e,t,n){for(var r=0,i=0;i<e.position.length;i++){var a=t[i],u=e.position[i];if(r=a.field.isKeyField()?we.comparator(we.fromName(u.referenceValue),n.key):wt(u,n.data.field(a.field)),"desc"===a.dir&&(r*=-1),0!==r)break}return r}function Vt(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(var n=0;n<e.position.length;n++)if(!gt(e.position[n],t.position[n]))return!1;return!0}var qt=L(function e(){P(this,e)}),Ut=function(e){g(n,qt);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this)).field=e,a.op=r,a.value=i,a}return L(n,[{key:"matches",value:function(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(wt(t,this.value)):null!==t&&mt(this.value)===mt(t)&&this.matchesComparison(wt(t,this.value))}},{key:"matchesComparison",value:function(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return W()}}},{key:"isInequality",value:function(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}},{key:"getFlattenedFilters",value:function(){return[this]}},{key:"getFilters",value:function(){return[this]}},{key:"getFirstInequalityField",value:function(){return this.isInequality()?this.field:null}}],[{key:"create",value:function(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new Yt(e,t,r):"array-contains"===t?new en(e,r):"in"===t?new tn(e,r):"not-in"===t?new nn(e,r):"array-contains-any"===t?new rn(e,r):new n(e,t,r)}},{key:"createKeyFieldInFilter",value:function(e,t,n){return"in"===t?new Jt(e,n):new Zt(e,n)}}]),n}(),Bt=function(e){g(n,qt);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).filters=e,i.op=r,i.ft=null,i}return L(n,[{key:"matches",value:function(e){return Kt(this)?void 0===this.filters.find(function(t){return!t.matches(e)}):void 0!==this.filters.find(function(t){return t.matches(e)})}},{key:"getFlattenedFilters",value:function(){return null!==this.ft||(this.ft=this.filters.reduce(function(e,t){return e.concat(t.getFlattenedFilters())},[])),this.ft}},{key:"getFilters",value:function(){return Object.assign([],this.filters)}},{key:"getFirstInequalityField",value:function(){var e=this.dt(function(e){return e.isInequality()});return null!==e?e.field:null}},{key:"dt",value:function(e){var t,n=p(this.getFlattenedFilters());try{for(n.s();!(t=n.n()).done;){var r=t.value;if(e(r))return r}}catch(i){n.e(i)}finally{n.f()}return null}}],[{key:"create",value:function(e,t){return new n(e,t)}}]),n}();function Kt(e){return"and"===e.op}function Gt(e){return"or"===e.op}function Qt(e){return jt(e)&&Kt(e)}function jt(e){var t,n=p(e.filters);try{for(n.s();!(t=n.n()).done;){if(t.value instanceof Bt)return!1}}catch(r){n.e(r)}finally{n.f()}return!0}function zt(e){if(e instanceof Ut)return e.field.canonicalString()+e.op.toString()+bt(e.value);if(Qt(e))return e.filters.map(function(e){return zt(e)}).join(",");var t=e.filters.map(function(e){return zt(e)}).join(",");return"".concat(e.op,"(").concat(t,")")}function Wt(e,t){return e instanceof Ut?function(e,t){return t instanceof Ut&&e.op===t.op&&e.field.isEqual(t.field)&>(e.value,t.value)}(e,t):e instanceof Bt?function(e,t){return t instanceof Bt&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(function(e,n,r){return e&&Wt(n,t.filters[r])},!0)}(e,t):void W()}function Ht(e,t){var n=e.filters.concat(t);return Bt.create(n,e.op)}function Xt(e){return e instanceof Ut?function(e){return"".concat(e.field.canonicalString()," ").concat(e.op," ").concat(bt(e.value))}(e):e instanceof Bt?function(e){return e.op.toString()+" {"+e.getFilters().map(Xt).join(" ,")+"}"}(e):"Filter"}var Yt=function(e){g(n,Ut);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this,e,r,i)).key=we.fromName(i.referenceValue),a}return L(n,[{key:"matches",value:function(e){var t=we.comparator(e.key,this.key);return this.matchesComparison(t)}}]),n}(),Jt=function(e){g(n,Ut);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e,"in",r)).keys=$t("in",r),i}return L(n,[{key:"matches",value:function(e){return this.keys.some(function(t){return t.isEqual(e.key)})}}]),n}(),Zt=function(e){g(n,Ut);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e,"not-in",r)).keys=$t("not-in",r),i}return L(n,[{key:"matches",value:function(e){return!this.keys.some(function(t){return t.isEqual(e.key)})}}]),n}();function $t(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(function(e){return we.fromName(e.referenceValue)})}var en=function(e){g(n,Ut);var t=w(n);function n(e,r){return P(this,n),t.call(this,e,"array-contains",r)}return L(n,[{key:"matches",value:function(e){var t=e.data.field(this.field);return St(t)&&kt(t.arrayValue,this.value)}}]),n}(),tn=function(e){g(n,Ut);var t=w(n);function n(e,r){return P(this,n),t.call(this,e,"in",r)}return L(n,[{key:"matches",value:function(e){var t=e.data.field(this.field);return null!==t&&kt(this.value.arrayValue,t)}}]),n}(),nn=function(e){g(n,Ut);var t=w(n);function n(e,r){return P(this,n),t.call(this,e,"not-in",r)}return L(n,[{key:"matches",value:function(e){if(kt(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!kt(this.value.arrayValue,t)}}]),n}(),rn=function(e){g(n,Ut);var t=w(n);function n(e,r){return P(this,n),t.call(this,e,"array-contains-any",r)}return L(n,[{key:"matches",value:function(e){var t=this,n=e.data.field(this.field);return!(!St(n)||!n.arrayValue.values)&&n.arrayValue.values.some(function(e){return kt(t.value.arrayValue,e)})}}]),n}(),an=L(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"asc";P(this,e),this.field=t,this.dir=n});function un(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}var on=function(){function e(t,n){P(this,e),this.comparator=t,this.root=n||cn.EMPTY}return L(e,[{key:"insert",value:function(t,n){return new e(this.comparator,this.root.insert(t,n,this.comparator).copy(null,null,cn.BLACK,null,null))}},{key:"remove",value:function(t){return new e(this.comparator,this.root.remove(t,this.comparator).copy(null,null,cn.BLACK,null,null))}},{key:"get",value:function(e){for(var t=this.root;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}},{key:"indexOf",value:function(e){for(var t=0,n=this.root;!n.isEmpty();){var 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}},{key:"isEmpty",value:function(){return this.root.isEmpty()}},{key:"size",get:function(){return this.root.size}},{key:"minKey",value:function(){return this.root.minKey()}},{key:"maxKey",value:function(){return this.root.maxKey()}},{key:"inorderTraversal",value:function(e){return this.root.inorderTraversal(e)}},{key:"forEach",value:function(e){this.inorderTraversal(function(t,n){return e(t,n),!1})}},{key:"toString",value:function(){var e=[];return this.inorderTraversal(function(t,n){return e.push("".concat(t,":").concat(n)),!1}),"{".concat(e.join(", "),"}")}},{key:"reverseTraversal",value:function(e){return this.root.reverseTraversal(e)}},{key:"getIterator",value:function(){return new sn(this.root,null,this.comparator,!1)}},{key:"getIteratorFrom",value:function(e){return new sn(this.root,e,this.comparator,!1)}},{key:"getReverseIterator",value:function(){return new sn(this.root,null,this.comparator,!0)}},{key:"getReverseIteratorFrom",value:function(e){return new sn(this.root,e,this.comparator,!0)}}]),e}(),sn=function(){function e(t,n,r,i){P(this,e),this.isReverse=i,this.nodeStack=[];for(var a=1;!t.isEmpty();)if(a=n?r(t.key,n):1,n&&i&&(a*=-1),a<0)t=this.isReverse?t.left:t.right;else{if(0===a){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return L(e,[{key:"getNext",value:function(){var e=this.nodeStack.pop(),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}},{key:"hasNext",value:function(){return this.nodeStack.length>0}},{key:"peek",value:function(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}]),e}(),cn=function(){function e(t,n,r,i,a){P(this,e),this.key=t,this.value=n,this.color=null!=r?r:e.RED,this.left=null!=i?i:e.EMPTY,this.right=null!=a?a:e.EMPTY,this.size=this.left.size+1+this.right.size}return L(e,[{key:"copy",value:function(t,n,r,i,a){return new e(null!=t?t:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=a?a:this.right)}},{key:"isEmpty",value:function(){return!1}},{key:"inorderTraversal",value:function(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}},{key:"reverseTraversal",value:function(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}},{key:"min",value:function(){return this.left.isEmpty()?this:this.left.min()}},{key:"minKey",value:function(){return this.min().key}},{key:"maxKey",value:function(){return this.right.isEmpty()?this.key:this.right.maxKey()}},{key:"insert",value:function(e,t,n){var r=this,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))).fixUp()}},{key:"removeMin",value:function(){if(this.left.isEmpty())return e.EMPTY;var t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),(t=t.copy(null,null,null,t.left.removeMin(),null)).fixUp()}},{key:"remove",value:function(t,n){var r,i=this;if(n(t,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(t,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(t,i.key)){if(i.right.isEmpty())return e.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(t,n))}return i.fixUp()}},{key:"isRed",value:function(){return this.color}},{key:"fixUp",value:function(){var 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}},{key:"moveRedLeft",value:function(){var e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}},{key:"moveRedRight",value:function(){var e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}},{key:"rotateLeft",value:function(){var t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}},{key:"rotateRight",value:function(){var t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}},{key:"colorFlip",value:function(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}},{key:"checkMaxDepth",value:function(){var e=this.check();return Math.pow(2,e)<=this.size+1}},{key:"check",value:function(){if(this.isRed()&&this.left.isRed())throw W();if(this.right.isRed())throw W();var e=this.left.check();if(e!==this.right.check())throw W();return e+(this.isRed()?0:1)}}]),e}();cn.EMPTY=null,cn.RED=!0,cn.BLACK=!1,cn.EMPTY=new(function(){function e(){P(this,e),this.size=0}return L(e,[{key:"key",get:function(){throw W()}},{key:"value",get:function(){throw W()}},{key:"color",get:function(){throw W()}},{key:"left",get:function(){throw W()}},{key:"right",get:function(){throw W()}},{key:"copy",value:function(e,t,n,r,i){return this}},{key:"insert",value:function(e,t,n){return new cn(e,t)}},{key:"remove",value:function(e,t){return this}},{key:"isEmpty",value:function(){return!0}},{key:"inorderTraversal",value:function(e){return!1}},{key:"reverseTraversal",value:function(e){return!1}},{key:"minKey",value:function(){return null}},{key:"maxKey",value:function(){return null}},{key:"isRed",value:function(){return!1}},{key:"checkMaxDepth",value:function(){return!0}},{key:"check",value:function(){return 0}}]),e}());var ln=function(){function e(t){P(this,e),this.comparator=t,this.data=new on(this.comparator)}return L(e,[{key:"has",value:function(e){return null!==this.data.get(e)}},{key:"first",value:function(){return this.data.minKey()}},{key:"last",value:function(){return this.data.maxKey()}},{key:"size",get:function(){return this.data.size}},{key:"indexOf",value:function(e){return this.data.indexOf(e)}},{key:"forEach",value:function(e){this.data.inorderTraversal(function(t,n){return e(t),!1})}},{key:"forEachInRange",value:function(e,t){for(var n=this.data.getIteratorFrom(e[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}},{key:"forEachWhile",value:function(e,t){var n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}},{key:"firstAfterOrEqual",value:function(e){var t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}},{key:"getIterator",value:function(){return new fn(this.data.getIterator())}},{key:"getIteratorFrom",value:function(e){return new fn(this.data.getIteratorFrom(e))}},{key:"add",value:function(e){return this.copy(this.data.remove(e).insert(e,!0))}},{key:"delete",value:function(e){return this.has(e)?this.copy(this.data.remove(e)):this}},{key:"isEmpty",value:function(){return this.data.isEmpty()}},{key:"unionWith",value:function(e){var t=this;return t.size<e.size&&(t=e,e=this),e.forEach(function(e){t=t.add(e)}),t}},{key:"isEqual",value:function(t){if(!(t instanceof e))return!1;if(this.size!==t.size)return!1;for(var n=this.data.getIterator(),r=t.data.getIterator();n.hasNext();){var i=n.getNext().key,a=r.getNext().key;if(0!==this.comparator(i,a))return!1}return!0}},{key:"toArray",value:function(){var e=[];return this.forEach(function(t){e.push(t)}),e}},{key:"toString",value:function(){var e=[];return this.forEach(function(t){return e.push(t)}),"SortedSet("+e.toString()+")"}},{key:"copy",value:function(t){var n=new e(this.comparator);return n.data=t,n}}]),e}(),fn=function(){function e(t){P(this,e),this.iter=t}return L(e,[{key:"getNext",value:function(){return this.iter.getNext().key}},{key:"hasNext",value:function(){return this.iter.hasNext()}}]),e}();function hn(e){return e.hasNext()?e.getNext():void 0}var dn=function(){function e(t){P(this,e),this.fields=t,t.sort(ke.comparator)}return L(e,[{key:"unionWith",value:function(t){var n,r=new ln(ke.comparator),i=p(this.fields);try{for(i.s();!(n=i.n()).done;){var a=n.value;r=r.add(a)}}catch(c){i.e(c)}finally{i.f()}var u,o=p(t);try{for(o.s();!(u=o.n()).done;){var s=u.value;r=r.add(s)}}catch(c){o.e(c)}finally{o.f()}return new e(r.toArray())}},{key:"covers",value:function(e){var t,n=p(this.fields);try{for(n.s();!(t=n.n()).done;){if(t.value.isPrefixOf(e))return!0}}catch(r){n.e(r)}finally{n.f()}return!1}},{key:"isEqual",value:function(e){return he(this.fields,e.fields,function(e,t){return e.isEqual(t)})}}],[{key:"empty",value:function(){return new e([])}}]),e}(),vn=function(){function e(t){P(this,e),this.value=t}return L(e,[{key:"field",value:function(e){if(e.isEmpty())return this.value;for(var t=this.value,n=0;n<e.length-1;++n)if(!Dt(t=(t.mapValue.fields||{})[e.get(n)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}},{key:"set",value:function(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Nt(t)}},{key:"setAll",value:function(e){var t=this,n=ke.emptyPath(),r={},i=[];e.forEach(function(e,a){if(!n.isImmediateParentOf(a)){var u=t.getFieldsMap(n);t.applyChanges(u,r,i),r={},i=[],n=a.popLast()}e?r[a.lastSegment()]=Nt(e):i.push(a.lastSegment())});var a=this.getFieldsMap(n);this.applyChanges(a,r,i)}},{key:"delete",value:function(e){var t=this.field(e.popLast());Dt(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}},{key:"isEqual",value:function(e){return gt(this.value,e.value)}},{key:"getFieldsMap",value:function(e){var t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(var n=0;n<e.length;++n){var r=t.mapValue.fields[e.get(n)];Dt(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}},{key:"applyChanges",value:function(e,t,n){et(t,function(t,n){return e[t]=n});var r,i=p(n);try{for(i.s();!(r=i.n()).done;){var a=r.value;delete e[a]}}catch(u){i.e(u)}finally{i.f()}}},{key:"clone",value:function(){return new e(Nt(this.value))}}],[{key:"empty",value:function(){return new e({mapValue:{}})}}]),e}();function yn(e){var t=[];return et(e.fields,function(e,n){var r=new ke([e]);if(Dt(n)){var i=yn(n.mapValue).fields;if(0===i.length)t.push(r);else{var a,u=p(i);try{for(u.s();!(a=u.n()).done;){var o=a.value;t.push(r.child(o))}}catch(s){u.e(s)}finally{u.f()}}}else t.push(r)}),new dn(t)}var pn=function(){function e(t,n,r,i,a,u,o){P(this,e),this.key=t,this.documentType=n,this.version=r,this.readTime=i,this.createTime=a,this.data=u,this.documentState=o}return L(e,[{key:"convertToFoundDocument",value:function(e,t){return!this.createTime.isEqual(ye.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}},{key:"convertToNoDocument",value:function(e){return this.version=e,this.documentType=2,this.data=vn.empty(),this.documentState=0,this}},{key:"convertToUnknownDocument",value:function(e){return this.version=e,this.documentType=3,this.data=vn.empty(),this.documentState=2,this}},{key:"setHasCommittedMutations",value:function(){return this.documentState=2,this}},{key:"setHasLocalMutations",value:function(){return this.documentState=1,this.version=ye.min(),this}},{key:"setReadTime",value:function(e){return this.readTime=e,this}},{key:"hasLocalMutations",get:function(){return 1===this.documentState}},{key:"hasCommittedMutations",get:function(){return 2===this.documentState}},{key:"hasPendingWrites",get:function(){return this.hasLocalMutations||this.hasCommittedMutations}},{key:"isValidDocument",value:function(){return 0!==this.documentType}},{key:"isFoundDocument",value:function(){return 1===this.documentType}},{key:"isNoDocument",value:function(){return 2===this.documentType}},{key:"isUnknownDocument",value:function(){return 3===this.documentType}},{key:"isEqual",value:function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}},{key:"mutableCopy",value:function(){return new e(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}},{key:"toString",value:function(){return"Document(".concat(this.key,", ").concat(this.version,", ").concat(JSON.stringify(this.data.value),", {createTime: ").concat(this.createTime,"}), {documentType: ").concat(this.documentType,"}), {documentState: ").concat(this.documentState,"})")}}],[{key:"newInvalidDocument",value:function(t){return new e(t,0,ye.min(),ye.min(),ye.min(),vn.empty(),0)}},{key:"newFoundDocument",value:function(t,n,r,i){return new e(t,1,n,ye.min(),r,i,0)}},{key:"newNoDocument",value:function(t,n){return new e(t,2,n,ye.min(),ye.min(),vn.empty(),0)}},{key:"newUnknownDocument",value:function(t,n){return new e(t,3,n,ye.min(),ye.min(),vn.empty(),2)}}]),e}(),mn=L(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;P(this,e),this.path=t,this.collectionGroup=n,this.orderBy=r,this.filters=i,this.limit=a,this.startAt=u,this.endAt=o,this._t=null});function gn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,u=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;return new mn(e,t,n,r,i,a,u)}function kn(e){var t=Y(e);if(null===t._t){var n=t.path.canonicalString();null!==t.collectionGroup&&(n+="|cg:"+t.collectionGroup),n+="|f:",n+=t.filters.map(function(e){return zt(e)}).join(","),n+="|ob:",n+=t.orderBy.map(function(e){return function(e){return e.field.canonicalString()+e.dir}(e)}).join(","),nt(t.limit)||(n+="|l:",n+=t.limit),t.startAt&&(n+="|lb:",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(function(e){return bt(e)}).join(",")),t.endAt&&(n+="|ub:",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(function(e){return bt(e)}).join(",")),t._t=n}return t._t}function wn(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(var n=0;n<e.orderBy.length;n++)if(!un(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(var r=0;r<e.filters.length;r++)if(!Wt(e.filters[r],t.filters[r]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Vt(e.startAt,t.startAt)&&Vt(e.endAt,t.endAt)}function xn(e){return we.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function bn(e,t){return e.filters.filter(function(e){return e instanceof Ut&&e.field.isEqual(t)})}function In(e,t,n){var r,i=pt,a=!0,u=p(bn(e,t));try{for(u.s();!(r=u.n()).done;){var o=r.value,s=pt,c=!0;switch(o.op){case"<":case"<=":s=Pt(o.value);break;case"==":case"in":case">=":s=o.value;break;case">":s=o.value,c=!1;break;case"!=":case"not-in":s=pt}Lt({value:i,inclusive:a},{value:s,inclusive:c})<0&&(i=s,a=c)}}catch(h){u.e(h)}finally{u.f()}if(null!==n)for(var l=0;l<e.orderBy.length;++l)if(e.orderBy[l].field.isEqual(t)){var f=n.position[l];Lt({value:i,inclusive:a},{value:f,inclusive:n.inclusive})<0&&(i=f,a=n.inclusive);break}return{value:i,inclusive:a}}function Tn(e,t,n){var r,i=yt,a=!0,u=p(bn(e,t));try{for(u.s();!(r=u.n()).done;){var o=r.value,s=yt,c=!0;switch(o.op){case">=":case">":s=Ft(o.value),c=!1;break;case"==":case"in":case"<=":s=o.value;break;case"<":s=o.value,c=!1;break;case"!=":case"not-in":s=yt}Rt({value:i,inclusive:a},{value:s,inclusive:c})>0&&(i=s,a=c)}}catch(h){u.e(h)}finally{u.f()}if(null!==n)for(var l=0;l<e.orderBy.length;++l)if(e.orderBy[l].field.isEqual(t)){var f=n.position[l];Rt({value:i,inclusive:a},{value:f,inclusive:n.inclusive})>0&&(i=f,a=n.inclusive);break}return{value:i,inclusive:a}}var En=L(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"F",o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,s=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;P(this,e),this.path=t,this.collectionGroup=n,this.explicitOrderBy=r,this.filters=i,this.limit=a,this.limitType=u,this.startAt=o,this.endAt=s,this.wt=null,this.gt=null,this.startAt,this.endAt});function Sn(e,t,n,r,i,a,u,o){return new En(e,t,n,r,i,a,u,o)}function _n(e){return new En(e)}function An(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function Dn(e){return e.explicitOrderBy.length>0?e.explicitOrderBy[0].field:null}function Nn(e){var t,n=p(e.filters);try{for(n.s();!(t=n.n()).done;){var r=t.value.getFirstInequalityField();if(null!==r)return r}}catch(i){n.e(i)}finally{n.f()}return null}function Cn(e){return null!==e.collectionGroup}function Pn(e){var t=Y(e);if(null===t.wt){t.wt=[];var n=Nn(t),r=Dn(t);if(null!==n&&null===r)n.isKeyField()||t.wt.push(new an(n)),t.wt.push(new an(ke.keyField(),"asc"));else{var i,a=!1,u=p(t.explicitOrderBy);try{for(u.s();!(i=u.n()).done;){var o=i.value;t.wt.push(o),o.field.isKeyField()&&(a=!0)}}catch(c){u.e(c)}finally{u.f()}if(!a){var s=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.wt.push(new an(ke.keyField(),s))}}}return t.wt}function Fn(e){var t=Y(e);if(!t.gt)if("F"===t.limitType)t.gt=gn(t.path,t.collectionGroup,Pn(t),t.filters,t.limit,t.startAt,t.endAt);else{var n,r=[],i=p(Pn(t));try{for(i.s();!(n=i.n()).done;){var a=n.value,u="desc"===a.dir?"asc":"desc";r.push(new an(a.field,u))}}catch(c){i.e(c)}finally{i.f()}var o=t.endAt?new Mt(t.endAt.position,t.endAt.inclusive):null,s=t.startAt?new Mt(t.startAt.position,t.startAt.inclusive):null;t.gt=gn(t.path,t.collectionGroup,r,t.filters,t.limit,o,s)}return t.gt}function Ln(e,t){t.getFirstInequalityField(),Nn(e);var n=e.filters.concat([t]);return new En(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Rn(e,t,n){return new En(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Mn(e,t){return wn(Fn(e),Fn(t))&&e.limitType===t.limitType}function On(e){return"".concat(kn(Fn(e)),"|lt:").concat(e.limitType)}function Vn(e){return"Query(target=".concat(function(e){var t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=", filters: [".concat(e.filters.map(function(e){return Xt(e)}).join(", "),"]")),nt(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=", orderBy: [".concat(e.orderBy.map(function(e){return function(e){return"".concat(e.field.canonicalString()," (").concat(e.dir,")")}(e)}).join(", "),"]")),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(function(e){return bt(e)}).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(function(e){return bt(e)}).join(",")),"Target(".concat(t,")")}(Fn(e)),"; limitType=").concat(e.limitType,")")}function qn(e,t){return t.isFoundDocument()&&function(e,t){var n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):we.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){var n,r=p(Pn(e));try{for(r.s();!(n=r.n()).done;){var i=n.value;if(!i.field.isKeyField()&&null===t.data.field(i.field))return!1}}catch(a){r.e(a)}finally{r.f()}return!0}(e,t)&&function(e,t){var n,r=p(e.filters);try{for(r.s();!(n=r.n()).done;){if(!n.value.matches(t))return!1}}catch(i){r.e(i)}finally{r.f()}return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){var r=Ot(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Pn(e),t))&&!(e.endAt&&!function(e,t,n){var r=Ot(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Pn(e),t))}(e,t)}function Un(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Bn(e){return function(t,n){var r,i=!1,a=p(Pn(e));try{for(a.s();!(r=a.n()).done;){var u=r.value,o=Kn(u,t,n);if(0!==o)return o;i=i||u.field.isKeyField()}}catch(s){a.e(s)}finally{a.f()}return 0}}function Kn(e,t,n){var r=e.field.isKeyField()?we.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?wt(r,i):W()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return W()}}function Gn(e,t){if(e.yt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:rt(t)?"-0":t}}function Qn(e){return{integerValue:""+e}}function jn(e,t){return it(t)?Qn(t):Gn(e,t)}var zn=L(function e(){P(this,e),this._=void 0});function Wn(e,t,n){return e instanceof Yn?function(e,t){var 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 Jn?Zn(e,t):e instanceof $n?er(e,t):function(e,t){var n=Xn(e,t),r=nr(n)+nr(e.It);return Et(n)&&Et(e.It)?Qn(r):Gn(e.Tt,r)}(e,t)}function Hn(e,t,n){return e instanceof Jn?Zn(e,t):e instanceof $n?er(e,t):n}function Xn(e,t){return e instanceof tr?Et(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}var Yn=function(e){g(n,zn);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n)}(),Jn=function(e){g(n,zn);var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this)).elements=e,r}return L(n)}();function Zn(e,t){var n,r=rr(t),i=p(e.elements);try{var a=function(){var e=n.value;r.some(function(t){return gt(t,e)})||r.push(e)};for(i.s();!(n=i.n()).done;)a()}catch(u){i.e(u)}finally{i.f()}return{arrayValue:{values:r}}}var $n=function(e){g(n,zn);var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this)).elements=e,r}return L(n)}();function er(e,t){var n,r=rr(t),i=p(e.elements);try{var a=function(){var e=n.value;r=r.filter(function(t){return!gt(t,e)})};for(i.s();!(n=i.n()).done;)a()}catch(u){i.e(u)}finally{i.f()}return{arrayValue:{values:r}}}var tr=function(e){g(n,zn);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).Tt=e,i.It=r,i}return L(n)}();function nr(e){return lt(e.integerValue||e.doubleValue)}function rr(e){return St(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}var ir=L(function e(t,n){P(this,e),this.field=t,this.transform=n});function ar(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof Jn&&t instanceof Jn||e instanceof $n&&t instanceof $n?he(e.elements,t.elements,gt):e instanceof tr&&t instanceof tr?gt(e.It,t.It):e instanceof Yn&&t instanceof Yn}(e.transform,t.transform)}var ur=L(function e(t,n){P(this,e),this.version=t,this.transformResults=n}),or=function(){function e(t,n){P(this,e),this.updateTime=t,this.exists=n}return L(e,[{key:"isNone",get:function(){return void 0===this.updateTime&&void 0===this.exists}},{key:"isEqual",value:function(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}],[{key:"none",value:function(){return new e}},{key:"exists",value:function(t){return new e(void 0,t)}},{key:"updateTime",value:function(t){return new e(t)}}]),e}();function sr(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}var cr=L(function e(){P(this,e)});function lr(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new br(e.key,or.none()):new yr(e.key,e.data,or.none());var n,r=e.data,i=vn.empty(),a=new ln(ke.comparator),u=p(t.fields);try{for(u.s();!(n=u.n()).done;){var o=n.value;if(!a.has(o)){var s=r.field(o);null===s&&o.length>1&&(o=o.popLast(),s=r.field(o)),null===s?i.delete(o):i.set(o,s),a=a.add(o)}}}catch(c){u.e(c)}finally{u.f()}return new pr(e.key,i,new dn(a.toArray()),or.none())}function fr(e,t,n){e instanceof yr?function(e,t,n){var r=e.value.clone(),i=gr(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof pr?function(e,t,n){if(sr(e.precondition,t)){var r=gr(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(mr(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}else t.convertToUnknownDocument(n.version)}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function hr(e,t,n,r){return e instanceof yr?function(e,t,n,r){if(!sr(e.precondition,t))return n;var i=e.value.clone(),a=kr(e.fieldTransforms,r,t);return i.setAll(a),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof pr?function(e,t,n,r){if(!sr(e.precondition,t))return n;var i=kr(e.fieldTransforms,r,t),a=t.data;return a.setAll(mr(e)),a.setAll(i),t.convertToFoundDocument(t.version,a).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(function(e){return e.field}))}(e,t,n,r):function(e,t,n){return sr(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function dr(e,t){var n,r=null,i=p(e.fieldTransforms);try{for(i.s();!(n=i.n()).done;){var a=n.value,u=t.data.field(a.field),o=Xn(a.transform,u||null);null!=o&&(null===r&&(r=vn.empty()),r.set(a.field,o))}}catch(s){i.e(s)}finally{i.f()}return r||null}function vr(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)&&he(e,t,function(e,t){return ar(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))}var yr=function(e){g(n,cr);var t=w(n);function n(e,r,i){var a,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];return P(this,n),(a=t.call(this)).key=e,a.value=r,a.precondition=i,a.fieldTransforms=u,a.type=0,a}return L(n,[{key:"getFieldMask",value:function(){return null}}]),n}(),pr=function(e){g(n,cr);var t=w(n);function n(e,r,i,a){var u,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[];return P(this,n),(u=t.call(this)).key=e,u.data=r,u.fieldMask=i,u.precondition=a,u.fieldTransforms=o,u.type=1,u}return L(n,[{key:"getFieldMask",value:function(){return this.fieldMask}}]),n}();function mr(e){var t=new Map;return e.fieldMask.fields.forEach(function(n){if(!n.isEmpty()){var r=e.data.field(n);t.set(n,r)}}),t}function gr(e,t,n){var r=new Map;H(e.length===n.length);for(var i=0;i<n.length;i++){var a=e[i],u=a.transform,o=t.data.field(a.field);r.set(a.field,Hn(u,o,n[i]))}return r}function kr(e,t,n){var r,i=new Map,a=p(e);try{for(a.s();!(r=a.n()).done;){var u=r.value,o=u.transform,s=n.data.field(u.field);i.set(u.field,Wn(o,s,t))}}catch(c){a.e(c)}finally{a.f()}return i}var wr,xr,br=function(e){g(n,cr);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).key=e,i.precondition=r,i.type=2,i.fieldTransforms=[],i}return L(n,[{key:"getFieldMask",value:function(){return null}}]),n}(),Ir=function(e){g(n,cr);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).key=e,i.precondition=r,i.type=3,i.fieldTransforms=[],i}return L(n,[{key:"getFieldMask",value:function(){return null}}]),n}(),Tr=L(function e(t){P(this,e),this.count=t});function Er(e){switch(e){default:return W();case J.CANCELLED:case J.UNKNOWN:case J.DEADLINE_EXCEEDED:case J.RESOURCE_EXHAUSTED:case J.INTERNAL:case J.UNAVAILABLE:case J.UNAUTHENTICATED:return!1;case J.INVALID_ARGUMENT:case J.NOT_FOUND:case J.ALREADY_EXISTS:case J.PERMISSION_DENIED:case J.FAILED_PRECONDITION:case J.ABORTED:case J.OUT_OF_RANGE:case J.UNIMPLEMENTED:case J.DATA_LOSS:return!0}}function Sr(e){if(void 0===e)return Q("GRPC error has no .code"),J.UNKNOWN;switch(e){case wr.OK:return J.OK;case wr.CANCELLED:return J.CANCELLED;case wr.UNKNOWN:return J.UNKNOWN;case wr.DEADLINE_EXCEEDED:return J.DEADLINE_EXCEEDED;case wr.RESOURCE_EXHAUSTED:return J.RESOURCE_EXHAUSTED;case wr.INTERNAL:return J.INTERNAL;case wr.UNAVAILABLE:return J.UNAVAILABLE;case wr.UNAUTHENTICATED:return J.UNAUTHENTICATED;case wr.INVALID_ARGUMENT:return J.INVALID_ARGUMENT;case wr.NOT_FOUND:return J.NOT_FOUND;case wr.ALREADY_EXISTS:return J.ALREADY_EXISTS;case wr.PERMISSION_DENIED:return J.PERMISSION_DENIED;case wr.FAILED_PRECONDITION:return J.FAILED_PRECONDITION;case wr.ABORTED:return J.ABORTED;case wr.OUT_OF_RANGE:return J.OUT_OF_RANGE;case wr.UNIMPLEMENTED:return J.UNIMPLEMENTED;case wr.DATA_LOSS:return J.DATA_LOSS;default:return W()}}(xr=wr||(wr={}))[xr.OK=0]="OK",xr[xr.CANCELLED=1]="CANCELLED",xr[xr.UNKNOWN=2]="UNKNOWN",xr[xr.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",xr[xr.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",xr[xr.NOT_FOUND=5]="NOT_FOUND",xr[xr.ALREADY_EXISTS=6]="ALREADY_EXISTS",xr[xr.PERMISSION_DENIED=7]="PERMISSION_DENIED",xr[xr.UNAUTHENTICATED=16]="UNAUTHENTICATED",xr[xr.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",xr[xr.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",xr[xr.ABORTED=10]="ABORTED",xr[xr.OUT_OF_RANGE=11]="OUT_OF_RANGE",xr[xr.UNIMPLEMENTED=12]="UNIMPLEMENTED",xr[xr.INTERNAL=13]="INTERNAL",xr[xr.UNAVAILABLE=14]="UNAVAILABLE",xr[xr.DATA_LOSS=15]="DATA_LOSS";var _r=function(){function e(t,n){P(this,e),this.mapKeyFn=t,this.equalsFn=n,this.inner={},this.innerSize=0}return L(e,[{key:"get",value:function(e){var t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n){var r,i=p(n);try{for(i.s();!(r=i.n()).done;){var a=c(r.value,2),u=a[0],o=a[1];if(this.equalsFn(u,e))return o}}catch(s){i.e(s)}finally{i.f()}}}},{key:"has",value:function(e){return void 0!==this.get(e)}},{key:"set",value:function(e,t){var n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(var i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}},{key:"delete",value:function(e){var t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(var r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}},{key:"forEach",value:function(e){et(this.inner,function(t,n){var r,i=p(n);try{for(i.s();!(r=i.n()).done;){var a=c(r.value,2),u=a[0],o=a[1];e(u,o)}}catch(s){i.e(s)}finally{i.f()}})}},{key:"isEmpty",value:function(){return tt(this.inner)}},{key:"size",value:function(){return this.innerSize}}]),e}(),Ar=new on(we.comparator);function Dr(){return Ar}var Nr=new on(we.comparator);function Cr(){for(var e=Nr,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0,a=n;i<a.length;i++){var u=a[i];e=e.insert(u.key,u)}return e}function Pr(e){var t=Nr;return e.forEach(function(e,n){return t=t.insert(e,n.overlayedDocument)}),t}function Fr(){return Rr()}function Lr(){return Rr()}function Rr(){return new _r(function(e){return e.toString()},function(e,t){return e.isEqual(t)})}var Mr=new on(we.comparator),Or=new ln(we.comparator);function Vr(){for(var e=Or,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0,a=n;i<a.length;i++){var u=a[i];e=e.add(u)}return e}var qr=new ln(fe);function Ur(){return qr}var Br=function(){function e(t,n,r,i,a){P(this,e),this.snapshotVersion=t,this.targetChanges=n,this.targetMismatches=r,this.documentUpdates=i,this.resolvedLimboDocuments=a}return L(e,null,[{key:"createSynthesizedRemoteEventForCurrentChange",value:function(t,n,r){var i=new Map;return i.set(t,Kr.createSynthesizedTargetChangeForCurrentChange(t,n,r)),new e(ye.min(),i,Ur(),Dr(),Vr())}}]),e}(),Kr=function(){function e(t,n,r,i,a){P(this,e),this.resumeToken=t,this.current=n,this.addedDocuments=r,this.modifiedDocuments=i,this.removedDocuments=a}return L(e,null,[{key:"createSynthesizedTargetChangeForCurrentChange",value:function(t,n,r){return new e(r,n,Vr(),Vr(),Vr())}}]),e}(),Gr=L(function e(t,n,r,i){P(this,e),this.Et=t,this.removedTargetIds=n,this.key=r,this.At=i}),Qr=L(function e(t,n){P(this,e),this.targetId=t,this.Rt=n}),jr=L(function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ot.EMPTY_BYTE_STRING,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;P(this,e),this.state=t,this.targetIds=n,this.resumeToken=r,this.cause=i}),zr=function(){function e(){P(this,e),this.Pt=0,this.vt=Xr(),this.bt=ot.EMPTY_BYTE_STRING,this.Vt=!1,this.St=!0}return L(e,[{key:"current",get:function(){return this.Vt}},{key:"resumeToken",get:function(){return this.bt}},{key:"Dt",get:function(){return 0!==this.Pt}},{key:"Ct",get:function(){return this.St}},{key:"xt",value:function(e){e.approximateByteSize()>0&&(this.St=!0,this.bt=e)}},{key:"Nt",value:function(){var e=Vr(),t=Vr(),n=Vr();return this.vt.forEach(function(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:W()}}),new Kr(this.bt,this.Vt,e,t,n)}},{key:"kt",value:function(){this.St=!1,this.vt=Xr()}},{key:"$t",value:function(e,t){this.St=!0,this.vt=this.vt.insert(e,t)}},{key:"Mt",value:function(e){this.St=!0,this.vt=this.vt.remove(e)}},{key:"Ot",value:function(){this.Pt+=1}},{key:"Ft",value:function(){this.Pt-=1}},{key:"Bt",value:function(){this.St=!0,this.Vt=!0}}]),e}(),Wr=function(){function e(t){P(this,e),this.Lt=t,this.qt=new Map,this.Ut=Dr(),this.Kt=Hr(),this.Gt=new ln(fe)}return L(e,[{key:"Qt",value:function(e){var t,n=p(e.Et);try{for(n.s();!(t=n.n()).done;){var r=t.value;e.At&&e.At.isFoundDocument()?this.jt(r,e.At):this.zt(r,e.key,e.At)}}catch(o){n.e(o)}finally{n.f()}var i,a=p(e.removedTargetIds);try{for(a.s();!(i=a.n()).done;){var u=i.value;this.zt(u,e.key,e.At)}}catch(o){a.e(o)}finally{a.f()}}},{key:"Wt",value:function(e){var t=this;this.forEachTarget(e,function(n){var r=t.Ht(n);switch(e.state){case 0:t.Jt(n)&&r.xt(e.resumeToken);break;case 1:r.Ft(),r.Dt||r.kt(),r.xt(e.resumeToken);break;case 2:r.Ft(),r.Dt||t.removeTarget(n);break;case 3:t.Jt(n)&&(r.Bt(),r.xt(e.resumeToken));break;case 4:t.Jt(n)&&(t.Yt(n),r.xt(e.resumeToken));break;default:W()}})}},{key:"forEachTarget",value:function(e,t){var n=this;e.targetIds.length>0?e.targetIds.forEach(t):this.qt.forEach(function(e,r){n.Jt(r)&&t(r)})}},{key:"Zt",value:function(e){var t=e.targetId,n=e.Rt.count,r=this.Xt(t);if(r){var i=r.target;if(xn(i))if(0===n){var a=new we(i.path);this.zt(t,a,pn.newNoDocument(a,ye.min()))}else H(1===n);else this.te(t)!==n&&(this.Yt(t),this.Gt=this.Gt.add(t))}}},{key:"ee",value:function(e){var t=this,n=new Map;this.qt.forEach(function(r,i){var a=t.Xt(i);if(a){if(r.current&&xn(a.target)){var u=new we(a.target.path);null!==t.Ut.get(u)||t.ne(i,u)||t.zt(i,u,pn.newNoDocument(u,e))}r.Ct&&(n.set(i,r.Nt()),r.kt())}});var r=Vr();this.Kt.forEach(function(e,n){var i=!0;n.forEachWhile(function(e){var n=t.Xt(e);return!n||2===n.purpose||(i=!1,!1)}),i&&(r=r.add(e))}),this.Ut.forEach(function(t,n){return n.setReadTime(e)});var i=new Br(e,n,this.Gt,this.Ut,r);return this.Ut=Dr(),this.Kt=Hr(),this.Gt=new ln(fe),i}},{key:"jt",value:function(e,t){if(this.Jt(e)){var n=this.ne(e,t.key)?2:0;this.Ht(e).$t(t.key,n),this.Ut=this.Ut.insert(t.key,t),this.Kt=this.Kt.insert(t.key,this.se(t.key).add(e))}}},{key:"zt",value:function(e,t,n){if(this.Jt(e)){var r=this.Ht(e);this.ne(e,t)?r.$t(t,1):r.Mt(t),this.Kt=this.Kt.insert(t,this.se(t).delete(e)),n&&(this.Ut=this.Ut.insert(t,n))}}},{key:"removeTarget",value:function(e){this.qt.delete(e)}},{key:"te",value:function(e){var t=this.Ht(e).Nt();return this.Lt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}},{key:"Ot",value:function(e){this.Ht(e).Ot()}},{key:"Ht",value:function(e){var t=this.qt.get(e);return t||(t=new zr,this.qt.set(e,t)),t}},{key:"se",value:function(e){var t=this.Kt.get(e);return t||(t=new ln(fe),this.Kt=this.Kt.insert(e,t)),t}},{key:"Jt",value:function(e){var t=null!==this.Xt(e);return t||G("WatchChangeAggregator","Detected inactive target",e),t}},{key:"Xt",value:function(e){var t=this.qt.get(e);return t&&t.Dt?null:this.Lt.ie(e)}},{key:"Yt",value:function(e){var t=this;this.qt.set(e,new zr),this.Lt.getRemoteKeysForTarget(e).forEach(function(n){t.zt(e,n,null)})}},{key:"ne",value:function(e,t){return this.Lt.getRemoteKeysForTarget(e).has(t)}}]),e}();function Hr(){return new on(we.comparator)}function Xr(){return new on(we.comparator)}var Yr={asc:"ASCENDING",desc:"DESCENDING"},Jr={"<":"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"},Zr={and:"AND",or:"OR"},$r=L(function e(t,n){P(this,e),this.databaseId=t,this.yt=n});function ei(e,t){return e.yt?"".concat(new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z",""),".").concat(("000000000"+t.nanoseconds).slice(-9),"Z"):{seconds:""+t.seconds,nanos:t.nanoseconds}}function ti(e,t){return e.yt?t.toBase64():t.toUint8Array()}function ni(e,t){return ei(e,t.toTimestamp())}function ri(e){return H(!!e),ye.fromTimestamp(function(e){var t=ct(e);return new ve(t.seconds,t.nanos)}(e))}function ii(e,t){return function(e){return new me(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function ai(e){var t=me.fromString(e);return H(Ci(t)),t}function ui(e,t){return ii(e.databaseId,t.path)}function oi(e,t){var n=ai(t);if(n.get(1)!==e.databaseId.projectId)throw new Z(J.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 Z(J.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new we(fi(n))}function si(e,t){return ii(e.databaseId,t)}function ci(e){var t=ai(e);return 4===t.length?me.emptyPath():fi(t)}function li(e){return new me(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function fi(e){return H(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function hi(e,t,n){return{name:ui(e,t),fields:n.value.mapValue.fields}}function di(e,t,n){var r=oi(e,t.name),i=ri(t.updateTime),a=t.createTime?ri(t.createTime):ye.min(),u=new vn({mapValue:{fields:t.fields}}),o=pn.newFoundDocument(r,i,a,u);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function vi(e,t){return"found"in t?function(e,t){H(!!t.found),t.found.name,t.found.updateTime;var n=oi(e,t.found.name),r=ri(t.found.updateTime),i=t.found.createTime?ri(t.found.createTime):ye.min(),a=new vn({mapValue:{fields:t.found.fields}});return pn.newFoundDocument(n,r,i,a)}(e,t):"missing"in t?function(e,t){H(!!t.missing),H(!!t.readTime);var n=oi(e,t.missing),r=ri(t.readTime);return pn.newNoDocument(n,r)}(e,t):W()}function yi(e,t){var n;if("targetChange"in t){t.targetChange;var r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:W()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],a=function(e,t){return e.yt?(H(void 0===t||"string"==typeof t),ot.fromBase64String(t||"")):(H(void 0===t||t instanceof Uint8Array),ot.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),u=t.targetChange.cause,o=u&&function(e){var t=void 0===e.code?J.UNKNOWN:Sr(e.code);return new Z(t,e.message||"")}(u);n=new jr(r,i,a,o||null)}else if("documentChange"in t){t.documentChange;var s=t.documentChange;s.document,s.document.name,s.document.updateTime;var c=oi(e,s.document.name),l=ri(s.document.updateTime),f=s.document.createTime?ri(s.document.createTime):ye.min(),h=new vn({mapValue:{fields:s.document.fields}}),d=pn.newFoundDocument(c,l,f,h),v=s.targetIds||[],y=s.removedTargetIds||[];n=new Gr(v,y,d.key,d)}else if("documentDelete"in t){t.documentDelete;var p=t.documentDelete;p.document;var m=oi(e,p.document),g=p.readTime?ri(p.readTime):ye.min(),k=pn.newNoDocument(m,g),w=p.removedTargetIds||[];n=new Gr([],w,k.key,k)}else if("documentRemove"in t){t.documentRemove;var x=t.documentRemove;x.document;var b=oi(e,x.document),I=x.removedTargetIds||[];n=new Gr([],I,b,null)}else{if(!("filter"in t))return W();t.filter;var T=t.filter;T.targetId;var E=T.count||0,S=new Tr(E),_=T.targetId;n=new Qr(_,S)}return n}function pi(e,t){var n;if(t instanceof yr)n={update:hi(e,t.key,t.value)};else if(t instanceof br)n={delete:ui(e,t.key)};else if(t instanceof pr)n={update:hi(e,t.key,t.data),updateMask:Ni(t.fieldMask)};else{if(!(t instanceof Ir))return W();n={verify:ui(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map(function(e){return function(e,t){var n=t.transform;if(n instanceof Yn)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Jn)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof $n)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof tr)return{fieldPath:t.field.canonicalString(),increment:n.It};throw W()}(0,e)})),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:ni(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:W()}(e,t.precondition)),n}function mi(e,t){var n=t.currentDocument?function(e){return void 0!==e.updateTime?or.updateTime(ri(e.updateTime)):void 0!==e.exists?or.exists(e.exists):or.none()}(t.currentDocument):or.none(),r=t.updateTransforms?t.updateTransforms.map(function(t){return function(e,t){var n=null;if("setToServerValue"in t)H("REQUEST_TIME"===t.setToServerValue),n=new Yn;else if("appendMissingElements"in t){var r=t.appendMissingElements.values||[];n=new Jn(r)}else if("removeAllFromArray"in t){var i=t.removeAllFromArray.values||[];n=new $n(i)}else"increment"in t?n=new tr(e,t.increment):W();var a=ke.fromServerFormat(t.fieldPath);return new ir(a,n)}(e,t)}):[];if(t.update){t.update.name;var i=oi(e,t.update.name),a=new vn({mapValue:{fields:t.update.fields}});if(t.updateMask){var u=function(e){var t=e.fieldPaths||[];return new dn(t.map(function(e){return ke.fromServerFormat(e)}))}(t.updateMask);return new pr(i,a,u,n,r)}return new yr(i,a,n,r)}if(t.delete){var o=oi(e,t.delete);return new br(o,n)}if(t.verify){var s=oi(e,t.verify);return new Ir(s,n)}return W()}function gi(e,t){return e&&e.length>0?(H(void 0!==t),e.map(function(e){return function(e,t){var n=e.updateTime?ri(e.updateTime):ri(t);return n.isEqual(ye.min())&&(n=ri(t)),new ur(n,e.transformResults||[])}(e,t)})):[]}function ki(e,t){return{documents:[si(e,t.path)]}}function wi(e,t){var n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=si(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=si(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return Di(Bt.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);var a=function(e){if(0!==e.length)return e.map(function(e){return function(e){return{field:_i(e.field),direction:Ti(e.dir)}}(e)})}(t.orderBy);a&&(n.structuredQuery.orderBy=a);var u,o=function(e,t){return e.yt||nt(t)?t:{value:t}}(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt={before:(u=t.startAt).inclusive,values:u.position}),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function xi(e){var t=ci(e.parent),n=e.structuredQuery,r=n.from?n.from.length:0,i=null;if(r>0){H(1===r);var a=n.from[0];a.allDescendants?i=a.collectionId:t=t.child(a.collectionId)}var u=[];n.where&&(u=function(e){var t=Ii(n.where);return t instanceof Bt&&Qt(t)?t.getFilters():[t]}());var o=[];n.orderBy&&(o=n.orderBy.map(function(e){return function(e){return new an(Ai(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)}));var s=null;n.limit&&(s=function(e){var t;return nt(t="object"==C(e)?e.value:e)?null:t}(n.limit));var c=null;n.startAt&&(c=function(e){var t=!!e.before,n=e.values||[];return new Mt(n,t)}(n.startAt));var l=null;return n.endAt&&(l=function(e){var t=!e.before,n=e.values||[];return new Mt(n,t)}(n.endAt)),Sn(t,i,o,u,s,"F",c,l)}function bi(e,t){var n=function(e,t){switch(t){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return W()}}(0,t.purpose);return null==n?null:{"goog-listen-tags":n}}function Ii(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":var t=Ai(e.unaryFilter.field);return Ut.create(t,"==",{doubleValue:NaN});case"IS_NULL":var n=Ai(e.unaryFilter.field);return Ut.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var r=Ai(e.unaryFilter.field);return Ut.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":var i=Ai(e.unaryFilter.field);return Ut.create(i,"!=",{nullValue:"NULL_VALUE"});default:return W()}}(e):void 0!==e.fieldFilter?function(e){return Ut.create(Ai(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 W()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return Bt.create(e.compositeFilter.filters.map(function(e){return Ii(e)}),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return W()}}(e.compositeFilter.op))}(e):W()}function Ti(e){return Yr[e]}function Ei(e){return Jr[e]}function Si(e){return Zr[e]}function _i(e){return{fieldPath:e.canonicalString()}}function Ai(e){return ke.fromServerFormat(e.fieldPath)}function Di(e){return e instanceof Ut?function(e){if("=="===e.op){if(At(e.value))return{unaryFilter:{field:_i(e.field),op:"IS_NAN"}};if(_t(e.value))return{unaryFilter:{field:_i(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(At(e.value))return{unaryFilter:{field:_i(e.field),op:"IS_NOT_NAN"}};if(_t(e.value))return{unaryFilter:{field:_i(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:_i(e.field),op:Ei(e.op),value:e.value}}}(e):e instanceof Bt?function(e){var t=e.getFilters().map(function(e){return Di(e)});return 1===t.length?t[0]:{compositeFilter:{op:Si(e.op),filters:t}}}(e):W()}function Ni(e){var t=[];return e.fields.forEach(function(e){return t.push(e.canonicalString())}),{fieldPaths:t}}function Ci(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function Pi(e){for(var t="",n=0;n<e.length;n++)t.length>0&&(t=Li(t)),t=Fi(e.get(n),t);return Li(t)}function Fi(e,t){for(var n=t,r=e.length,i=0;i<r;i++){var a=e.charAt(i);switch(a){case"\0":n+="";break;case"":n+="";break;default:n+=a}}return n}function Li(e){return e+""}function Ri(e){var t=e.length;if(H(t>=2),2===t)return H(""===e.charAt(0)&&""===e.charAt(1)),me.emptyPath();for(var n=t-2,r=[],i="",a=0;a<t;){var u=e.indexOf("",a);switch((u<0||u>n)&&W(),e.charAt(u+1)){case"":var o=e.substring(a,u),s=void 0;0===i.length?s=o:(s=i+=o,i=""),r.push(s);break;case"":i+=e.substring(a,u),i+="\0";break;case"":i+=e.substring(a,u+1);break;default:W()}a=u+2}return new me(r)}var Mi=["userId","batchId"];function Oi(e,t){return[e,Pi(t)]}function Vi(e,t,n){return[e,Pi(t),n]}var qi={},Ui=["prefixPath","collectionGroup","readTime","documentId"],Bi=["prefixPath","collectionGroup","documentId"],Ki=["collectionGroup","readTime","prefixPath","documentId"],Gi=["canonicalId","targetId"],Qi=["targetId","path"],ji=["path","targetId"],zi=["collectionId","parent"],Wi=["indexId","uid"],Hi=["uid","sequenceNumber"],Xi=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Yi=["indexId","uid","orderedDocumentKey"],Ji=["userId","collectionPath","documentId"],Zi=["userId","collectionPath","largestBatchId"],$i=["userId","collectionGroup","largestBatchId"],ea=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments"].concat(["clientMetadata"]).concat(["remoteDocumentGlobal"]).concat(["collectionParents"]).concat(["bundles","namedQueries"]),ta=[].concat(E(ea),["documentOverlays"]),na=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ra=na,ia=[].concat(ra,["indexConfiguration","indexState","indexEntries"]),aa=function(e){g(n,Fe);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).re=e,i.currentSequenceNumber=r,i}return L(n)}();function ua(e,t){var n=Y(e);return Oe.M(n.re,t)}var oa=function(){function e(t,n,r,i){P(this,e),this.batchId=t,this.localWriteTime=n,this.baseMutations=r,this.mutations=i}return L(e,[{key:"applyToRemoteDocument",value:function(e,t){for(var n=t.mutationResults,r=0;r<this.mutations.length;r++){var i=this.mutations[r];i.key.isEqual(e.key)&&fr(i,e,n[r])}}},{key:"applyToLocalView",value:function(e,t){var n,r=p(this.baseMutations);try{for(r.s();!(n=r.n()).done;){var i=n.value;i.key.isEqual(e.key)&&(t=hr(i,e,t,this.localWriteTime))}}catch(s){r.e(s)}finally{r.f()}var a,u=p(this.mutations);try{for(u.s();!(a=u.n()).done;){var o=a.value;o.key.isEqual(e.key)&&(t=hr(o,e,t,this.localWriteTime))}}catch(s){u.e(s)}finally{u.f()}return t}},{key:"applyToLocalDocumentSet",value:function(e,t){var n=this,r=Lr();return this.mutations.forEach(function(i){var a=e.get(i.key),u=a.overlayedDocument,o=n.applyToLocalView(u,a.mutatedFields),s=lr(u,o=t.has(i.key)?null:o);null!==s&&r.set(i.key,s),u.isValidDocument()||u.convertToNoDocument(ye.min())}),r}},{key:"keys",value:function(){return this.mutations.reduce(function(e,t){return e.add(t.key)},Vr())}},{key:"isEqual",value:function(e){return this.batchId===e.batchId&&he(this.mutations,e.mutations,function(e,t){return vr(e,t)})&&he(this.baseMutations,e.baseMutations,function(e,t){return vr(e,t)})}}]),e}(),sa=function(){function e(t,n,r,i){P(this,e),this.batch=t,this.commitVersion=n,this.mutationResults=r,this.docVersions=i}return L(e,null,[{key:"from",value:function(t,n,r){H(t.mutations.length===r.length);for(var i=Mr,a=t.mutations,u=0;u<a.length;u++)i=i.insert(a[u].key,r[u].version);return new e(t,n,r,i)}}]),e}(),ca=function(){function e(t,n){P(this,e),this.largestBatchId=t,this.mutation=n}return L(e,[{key:"getKey",value:function(){return this.mutation.key}},{key:"isEqual",value:function(e){return null!==e&&this.mutation===e.mutation}},{key:"toString",value:function(){return"Overlay{\n largestBatchId: ".concat(this.largestBatchId,",\n mutation: ").concat(this.mutation.toString(),"\n }")}}]),e}(),la=function(){function e(t,n,r,i){var a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:ye.min(),u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:ye.min(),o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ot.EMPTY_BYTE_STRING;P(this,e),this.target=t,this.targetId=n,this.purpose=r,this.sequenceNumber=i,this.snapshotVersion=a,this.lastLimboFreeSnapshotVersion=u,this.resumeToken=o}return L(e,[{key:"withSequenceNumber",value:function(t){return new e(this.target,this.targetId,this.purpose,t,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}},{key:"withResumeToken",value:function(t,n){return new e(this.target,this.targetId,this.purpose,this.sequenceNumber,n,this.lastLimboFreeSnapshotVersion,t)}},{key:"withLastLimboFreeSnapshotVersion",value:function(t){return new e(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,t,this.resumeToken)}}]),e}(),fa=L(function e(t){P(this,e),this.oe=t});function ha(e,t){var n;if(t.document)n=di(e.oe,t.document,!!t.hasCommittedMutations);else if(t.noDocument){var r=we.fromSegments(t.noDocument.path),i=pa(t.noDocument.readTime);n=pn.newNoDocument(r,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return W();var a=we.fromSegments(t.unknownDocument.path),u=pa(t.unknownDocument.version);n=pn.newUnknownDocument(a,u)}return t.readTime&&n.setReadTime(function(e){var t=new ve(e[0],e[1]);return ye.fromTimestamp(t)}(t.readTime)),n}function da(e,t){var n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:va(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:ui(e,t.key),fields:t.data.value.mapValue.fields,updateTime:ei(e,t.version.toTimestamp()),createTime:ei(e,t.createTime.toTimestamp())}}(e.oe,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:ya(t.version)};else{if(!t.isUnknownDocument())return W();r.unknownDocument={path:n.path.toArray(),version:ya(t.version)}}return r}function va(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function ya(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function pa(e){var t=new ve(e.seconds,e.nanoseconds);return ye.fromTimestamp(t)}function ma(e,t){for(var n=(t.baseMutations||[]).map(function(t){return mi(e.oe,t)}),r=0;r<t.mutations.length-1;++r){var i=t.mutations[r];if(r+1<t.mutations.length&&void 0!==t.mutations[r+1].transform){var a=t.mutations[r+1];i.updateTransforms=a.transform.fieldTransforms,t.mutations.splice(r+1,1),++r}}var u=t.mutations.map(function(t){return mi(e.oe,t)}),o=ve.fromMillis(t.localWriteTimeMs);return new oa(t.batchId,o,n,u)}function ga(e){var t,n,r=pa(e.readTime),i=void 0!==e.lastLimboFreeSnapshotVersion?pa(e.lastLimboFreeSnapshotVersion):ye.min();return void 0!==e.query.documents?(H(1===(n=e.query).documents.length),t=Fn(_n(ci(n.documents[0])))):t=function(e){return Fn(xi(e))}(e.query),new la(t,e.targetId,0,e.lastListenSequenceNumber,r,i,ot.fromBase64String(e.resumeToken))}function ka(e,t){var n,r=ya(t.snapshotVersion),i=ya(t.lastLimboFreeSnapshotVersion);n=xn(t.target)?ki(e.oe,t.target):wi(e.oe,t.target);var a=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:kn(t.target),readTime:r,resumeToken:a,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function wa(e){var t=xi({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Rn(t,t.limit,"L"):t}function xa(e,t){return new ca(t.largestBatchId,mi(e.oe,t.overlayMutation))}function ba(e,t){var n=t.path.lastSegment();return[e,Pi(t.path.popLast()),n]}function Ia(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:ya(r.readTime),documentKey:Pi(r.documentKey.path),largestBatchId:r.largestBatchId}}var Ta=function(){function e(){P(this,e)}return L(e,[{key:"getBundleMetadata",value:function(e,t){return Ea(e).get(t).next(function(e){if(e)return{id:(t=e).bundleId,createTime:pa(t.createTime),version:t.version};var t})}},{key:"saveBundleMetadata",value:function(e,t){return Ea(e).put({bundleId:(n=t).id,createTime:ya(ri(n.createTime)),version:n.version});var n}},{key:"getNamedQuery",value:function(e,t){return Sa(e).get(t).next(function(e){if(e)return{name:(t=e).name,query:wa(t.bundledQuery),readTime:pa(t.readTime)};var t})}},{key:"saveNamedQuery",value:function(e,t){return Sa(e).put(function(e){return{name:e.name,readTime:ya(ri(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}]),e}();function Ea(e){return ua(e,"bundles")}function Sa(e){return ua(e,"namedQueries")}var _a=function(){function e(t,n){P(this,e),this.Tt=t,this.userId=n}return L(e,[{key:"getOverlay",value:function(e,t){var n=this;return Aa(e).get(ba(this.userId,t)).next(function(e){return e?xa(n.Tt,e):null})}},{key:"getOverlays",value:function(e,t){var n=this,r=Fr();return Re.forEach(t,function(t){return n.getOverlay(e,t).next(function(e){null!==e&&r.set(t,e)})}).next(function(){return r})}},{key:"saveOverlays",value:function(e,t,n){var r=this,i=[];return n.forEach(function(n,a){var u=new ca(t,a);i.push(r.ce(e,u))}),Re.waitFor(i)}},{key:"removeOverlaysForBatchId",value:function(e,t,n){var r=this,i=new Set;t.forEach(function(e){return i.add(Pi(e.getCollectionPath()))});var a=[];return i.forEach(function(t){var i=IDBKeyRange.bound([r.userId,t,n],[r.userId,t,n+1],!1,!0);a.push(Aa(e).Y("collectionPathOverlayIndex",i))}),Re.waitFor(a)}},{key:"getOverlaysForCollection",value:function(e,t,n){var r=this,i=Fr(),a=Pi(t),u=IDBKeyRange.bound([this.userId,a,n],[this.userId,a,Number.POSITIVE_INFINITY],!0);return Aa(e).W("collectionPathOverlayIndex",u).next(function(e){var t,n=p(e);try{for(n.s();!(t=n.n()).done;){var a=t.value,u=xa(r.Tt,a);i.set(u.getKey(),u)}}catch(o){n.e(o)}finally{n.f()}return i})}},{key:"getOverlaysForCollectionGroup",value:function(e,t,n,r){var i,a=this,u=Fr(),o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Aa(e).X({index:"collectionGroupOverlayIndex",range:o},function(e,t,n){var o=xa(a.Tt,t);u.size()<r||o.largestBatchId===i?(u.set(o.getKey(),o),i=o.largestBatchId):n.done()}).next(function(){return u})}},{key:"ce",value:function(e,t){return Aa(e).put(function(e,t,n){var r=c(ba(t,n.mutation.key),3);r[0];return{userId:t,collectionPath:r[1],documentId:r[2],collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:pi(e.oe,n.mutation)}}(this.Tt,this.userId,t))}}],[{key:"ue",value:function(t,n){return new e(t,n.uid||"")}}]),e}();function Aa(e){return ua(e,"documentOverlays")}var Da=function(){function e(){P(this,e)}return L(e,[{key:"ae",value:function(e,t){this.he(e,t),t.le()}},{key:"he",value:function(e,t){if("nullValue"in e)this.fe(t,5);else if("booleanValue"in e)this.fe(t,10),t.de(e.booleanValue?1:0);else if("integerValue"in e)this.fe(t,15),t.de(lt(e.integerValue));else if("doubleValue"in e){var n=lt(e.doubleValue);isNaN(n)?this.fe(t,13):(this.fe(t,15),rt(n)?t.de(0):t.de(n))}else if("timestampValue"in e){var r=e.timestampValue;this.fe(t,20),"string"==typeof r?t._e(r):(t._e("".concat(r.seconds||"")),t.de(r.nanos||0))}else if("stringValue"in e)this.we(e.stringValue,t),this.me(t);else if("bytesValue"in e)this.fe(t,30),t.ge(ft(e.bytesValue)),this.me(t);else if("referenceValue"in e)this.ye(e.referenceValue,t);else if("geoPointValue"in e){var i=e.geoPointValue;this.fe(t,45),t.de(i.latitude||0),t.de(i.longitude||0)}else"mapValue"in e?Ct(e)?this.fe(t,Number.MAX_SAFE_INTEGER):(this.pe(e.mapValue,t),this.me(t)):"arrayValue"in e?(this.Ie(e.arrayValue,t),this.me(t)):W()}},{key:"we",value:function(e,t){this.fe(t,25),this.Te(e,t)}},{key:"Te",value:function(e,t){t._e(e)}},{key:"pe",value:function(e,t){var n=e.fields||{};this.fe(t,55);for(var r=0,i=Object.keys(n);r<i.length;r++){var a=i[r];this.we(a,t),this.he(n[a],t)}}},{key:"Ie",value:function(e,t){var n=e.values||[];this.fe(t,50);var r,i=p(n);try{for(i.s();!(r=i.n()).done;){var a=r.value;this.he(a,t)}}catch(u){i.e(u)}finally{i.f()}}},{key:"ye",value:function(e,t){var n=this;this.fe(t,37),we.fromName(e).path.forEach(function(e){n.fe(t,60),n.Te(e,t)})}},{key:"fe",value:function(e,t){e.de(t)}},{key:"me",value:function(e){e.de(2)}}]),e}();function Na(e){if(0===e)return 8;var t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}function Ca(e){var t=64-function(e){for(var t=0,n=0;n<8;++n){var r=Na(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}Da.Ee=new Da;var Pa=function(){function e(){P(this,e),this.buffer=new Uint8Array(1024),this.position=0}return L(e,[{key:"Ae",value:function(e){for(var t=e[Symbol.iterator](),n=t.next();!n.done;)this.Re(n.value),n=t.next();this.Pe()}},{key:"ve",value:function(e){for(var t=e[Symbol.iterator](),n=t.next();!n.done;)this.be(n.value),n=t.next();this.Ve()}},{key:"Se",value:function(e){var t,n=p(e);try{for(n.s();!(t=n.n()).done;){var r=t.value,i=r.charCodeAt(0);if(i<128)this.Re(i);else if(i<2048)this.Re(960|i>>>6),this.Re(128|63&i);else if(r<"\ud800"||"\udbff"<r)this.Re(480|i>>>12),this.Re(128|63&i>>>6),this.Re(128|63&i);else{var a=r.codePointAt(0);this.Re(240|a>>>18),this.Re(128|63&a>>>12),this.Re(128|63&a>>>6),this.Re(128|63&a)}}}catch(u){n.e(u)}finally{n.f()}this.Pe()}},{key:"De",value:function(e){var t,n=p(e);try{for(n.s();!(t=n.n()).done;){var r=t.value,i=r.charCodeAt(0);if(i<128)this.be(i);else if(i<2048)this.be(960|i>>>6),this.be(128|63&i);else if(r<"\ud800"||"\udbff"<r)this.be(480|i>>>12),this.be(128|63&i>>>6),this.be(128|63&i);else{var a=r.codePointAt(0);this.be(240|a>>>18),this.be(128|63&a>>>12),this.be(128|63&a>>>6),this.be(128|63&a)}}}catch(u){n.e(u)}finally{n.f()}this.Ve()}},{key:"Ce",value:function(e){var t=this.xe(e),n=Ca(t);this.Ne(1+n),this.buffer[this.position++]=255&n;for(var r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}},{key:"ke",value:function(e){var t=this.xe(e),n=Ca(t);this.Ne(1+n),this.buffer[this.position++]=~(255&n);for(var r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}},{key:"$e",value:function(){this.Me(255),this.Me(255)}},{key:"Oe",value:function(){this.Fe(255),this.Fe(255)}},{key:"reset",value:function(){this.position=0}},{key:"seed",value:function(e){this.Ne(e.length),this.buffer.set(e,this.position),this.position+=e.length}},{key:"Be",value:function(){return this.buffer.slice(0,this.position)}},{key:"xe",value:function(e){var t=function(e){var t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(var r=1;r<t.length;++r)t[r]^=n?255:0;return t}},{key:"Re",value:function(e){var t=255&e;0===t?(this.Me(0),this.Me(255)):255===t?(this.Me(255),this.Me(0)):this.Me(t)}},{key:"be",value:function(e){var t=255&e;0===t?(this.Fe(0),this.Fe(255)):255===t?(this.Fe(255),this.Fe(0)):this.Fe(e)}},{key:"Pe",value:function(){this.Me(0),this.Me(1)}},{key:"Ve",value:function(){this.Fe(0),this.Fe(1)}},{key:"Me",value:function(e){this.Ne(1),this.buffer[this.position++]=e}},{key:"Fe",value:function(e){this.Ne(1),this.buffer[this.position++]=~e}},{key:"Ne",value:function(e){var t=e+this.position;if(!(t<=this.buffer.length)){var n=2*this.buffer.length;n<t&&(n=t);var r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}}]),e}(),Fa=function(){function e(t){P(this,e),this.Le=t}return L(e,[{key:"ge",value:function(e){this.Le.Ae(e)}},{key:"_e",value:function(e){this.Le.Se(e)}},{key:"de",value:function(e){this.Le.Ce(e)}},{key:"le",value:function(){this.Le.$e()}}]),e}(),La=function(){function e(t){P(this,e),this.Le=t}return L(e,[{key:"ge",value:function(e){this.Le.ve(e)}},{key:"_e",value:function(e){this.Le.De(e)}},{key:"de",value:function(e){this.Le.ke(e)}},{key:"le",value:function(){this.Le.Oe()}}]),e}(),Ra=function(){function e(){P(this,e),this.Le=new Pa,this.qe=new Fa(this.Le),this.Ue=new La(this.Le)}return L(e,[{key:"seed",value:function(e){this.Le.seed(e)}},{key:"Ke",value:function(e){return 0===e?this.qe:this.Ue}},{key:"Be",value:function(){return this.Le.Be()}},{key:"reset",value:function(){this.Le.reset()}}]),e}(),Ma=function(){function e(t,n,r,i){P(this,e),this.indexId=t,this.documentKey=n,this.arrayValue=r,this.directionalValue=i}return L(e,[{key:"Ge",value:function(){var t=this.directionalValue.length,n=0===t||255===this.directionalValue[t-1]?t+1:t,r=new Uint8Array(n);return r.set(this.directionalValue,0),n!==t?r.set([0],this.directionalValue.length):++r[r.length-1],new e(this.indexId,this.documentKey,this.arrayValue,r)}}]),e}();function Oa(e,t){var n=e.indexId-t.indexId;return 0!==n?n:0!==(n=Va(e.arrayValue,t.arrayValue))?n:0!==(n=Va(e.directionalValue,t.directionalValue))?n:we.comparator(e.documentKey,t.documentKey)}function Va(e,t){for(var n=0;n<e.length&&n<t.length;++n){var r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}var qa=function(){function e(t){P(this,e),this.collectionId=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment(),this.Qe=t.orderBy,this.je=[];var n,r=p(t.filters);try{for(r.s();!(n=r.n()).done;){var i=n.value;i.isInequality()?this.ze=i:this.je.push(i)}}catch(a){r.e(a)}finally{r.f()}}return L(e,[{key:"We",value:function(e){H(e.collectionGroup===this.collectionId);var t=be(e);if(void 0!==t&&!this.He(t))return!1;for(var n=Ie(e),r=0,i=0;r<n.length&&this.He(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.ze){var a=n[r];if(!this.Je(this.ze,a)||!this.Ye(this.Qe[i++],a))return!1;++r}for(;r<n.length;++r){var u=n[r];if(i>=this.Qe.length||!this.Ye(this.Qe[i++],u))return!1}return!0}},{key:"He",value:function(e){var t,n=p(this.je);try{for(n.s();!(t=n.n()).done;){var r=t.value;if(this.Je(r,e))return!0}}catch(i){n.e(i)}finally{n.f()}return!1}},{key:"Je",value:function(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}},{key:"Ye",value:function(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}]),e}();function Ua(e){var t,n;if(H(e instanceof Ut||e instanceof Bt),e instanceof Ut){if(e instanceof tn){var r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map(function(t){return Ut.create(e.field,"==",t)}))||[];return Bt.create(r,"or")}return e}var i=e.filters.map(function(e){return Ua(e)});return Bt.create(i,e.op)}function Ba(e){if(0===e.getFilters().length)return[];var t=ja(Ua(e));return H(Qa(t)),Ka(t)||Ga(t)?[t]:t.getFilters()}function Ka(e){return e instanceof Ut}function Ga(e){return e instanceof Bt&&Qt(e)}function Qa(e){return Ka(e)||Ga(e)||function(e){if(e instanceof Bt&&Gt(e)){var t,n=p(e.getFilters());try{for(n.s();!(t=n.n()).done;){var r=t.value;if(!Ka(r)&&!Ga(r))return!1}}catch(i){n.e(i)}finally{n.f()}return!0}return!1}(e)}function ja(e){if(H(e instanceof Ut||e instanceof Bt),e instanceof Ut)return e;if(1===e.filters.length)return ja(e.filters[0]);var t=e.filters.map(function(e){return ja(e)}),n=Bt.create(t,e.op);return Qa(n=Ha(n))?n:(H(n instanceof Bt),H(Kt(n)),H(n.filters.length>1),n.filters.reduce(function(e,t){return za(e,t)}))}function za(e,t){return H(e instanceof Ut||e instanceof Bt),H(t instanceof Ut||t instanceof Bt),Ha(e instanceof Ut?t instanceof Ut?function(e,t){return Bt.create([e,t],"and")}(e,t):Wa(e,t):t instanceof Ut?Wa(t,e):function(e,t){if(H(e.filters.length>0&&t.filters.length>0),Kt(e)&&Kt(t))return Ht(e,t.getFilters());var n=Gt(e)?e:t,r=Gt(e)?t:e,i=n.filters.map(function(e){return za(e,r)});return Bt.create(i,"or")}(e,t))}function Wa(e,t){if(Kt(t))return Ht(t,e.getFilters());var n=t.filters.map(function(t){return za(e,t)});return Bt.create(n,"or")}function Ha(e){if(H(e instanceof Ut||e instanceof Bt),e instanceof Ut)return e;var t=e.getFilters();if(1===t.length)return Ha(t[0]);if(jt(e))return e;var n=t.map(function(e){return Ha(e)}),r=[];return n.forEach(function(t){t instanceof Ut?r.push(t):t instanceof Bt&&(t.op===e.op?r.push.apply(r,E(t.filters)):r.push(t))}),1===r.length?r[0]:Bt.create(r,e.op)}var Xa=function(){function e(){P(this,e),this.Ze=new Ya}return L(e,[{key:"addToCollectionParentIndex",value:function(e,t){return this.Ze.add(t),Re.resolve()}},{key:"getCollectionParents",value:function(e,t){return Re.resolve(this.Ze.getEntries(t))}},{key:"addFieldIndex",value:function(e,t){return Re.resolve()}},{key:"deleteFieldIndex",value:function(e,t){return Re.resolve()}},{key:"getDocumentsMatchingTarget",value:function(e,t){return Re.resolve(null)}},{key:"getIndexType",value:function(e,t){return Re.resolve(0)}},{key:"getFieldIndexes",value:function(e,t){return Re.resolve([])}},{key:"getNextCollectionGroupToUpdate",value:function(e){return Re.resolve(null)}},{key:"getMinOffset",value:function(e,t){return Re.resolve(Ne.min())}},{key:"getMinOffsetFromCollectionGroup",value:function(e,t){return Re.resolve(Ne.min())}},{key:"updateCollectionGroup",value:function(e,t,n){return Re.resolve()}},{key:"updateIndexEntries",value:function(e,t){return Re.resolve()}}]),e}(),Ya=function(){function e(){P(this,e),this.index={}}return L(e,[{key:"add",value:function(e){var t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ln(me.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}},{key:"has",value:function(e){var t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}},{key:"getEntries",value:function(e){return(this.index[e]||new ln(me.comparator)).toArray()}}]),e}(),Ja=new Uint8Array(0),Za=function(){function e(t,n){P(this,e),this.user=t,this.databaseId=n,this.Xe=new Ya,this.tn=new _r(function(e){return kn(e)},function(e,t){return wn(e,t)}),this.uid=t.uid||""}return L(e,[{key:"addToCollectionParentIndex",value:function(e,t){var n=this;if(!this.Xe.has(t)){var r=t.lastSegment(),i=t.popLast();e.addOnCommittedListener(function(){n.Xe.add(t)});var a={collectionId:r,parent:Pi(i)};return $a(e).put(a)}return Re.resolve()}},{key:"getCollectionParents",value:function(e,t){var n=[],r=IDBKeyRange.bound([t,""],[de(t),""],!1,!0);return $a(e).W(r).next(function(e){var r,i=p(e);try{for(i.s();!(r=i.n()).done;){var a=r.value;if(a.collectionId!==t)break;n.push(Ri(a.parent))}}catch(u){i.e(u)}finally{i.f()}return n})}},{key:"addFieldIndex",value:function(e,t){var n=this,r=tu(e),i=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map(function(e){return[e.fieldPath.canonicalString(),e.kind]})}}(t);delete i.indexId;var a=r.add(i);if(t.indexState){var u=nu(e);return a.next(function(e){u.put(Ia(e,n.user,t.indexState.sequenceNumber,t.indexState.offset))})}return a.next()}},{key:"deleteFieldIndex",value:function(e,t){var n=tu(e),r=nu(e),i=eu(e);return n.delete(t.indexId).next(function(){return r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))}).next(function(){return i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))})}},{key:"getDocumentsMatchingTarget",value:function(e,t){var n=this,r=eu(e),i=!0,a=new Map;return Re.forEach(this.en(t),function(t){return n.nn(e,t).next(function(e){i&&(i=!!e),a.set(t,e)})}).next(function(){if(i){var e=Vr(),u=[];return Re.forEach(a,function(i,a){var o;G("IndexedDbIndexManager","Using index ".concat((o=i,"id=".concat(o.indexId,"|cg=").concat(o.collectionGroup,"|f=").concat(o.fields.map(function(e){return"".concat(e.fieldPath,":").concat(e.kind)}).join(",")))," to execute ").concat(kn(t)));var s=function(e,t){var n=be(i);if(void 0===n)return null;var r,a=p(bn(e,n.fieldPath));try{for(a.s();!(r=a.n()).done;){var u=r.value;switch(u.op){case"array-contains-any":return u.value.arrayValue.values||[];case"array-contains":return[u.value]}}}catch(o){a.e(o)}finally{a.f()}return null}(a),c=function(e,t){var n,r=new Map,i=p(Ie(t));try{for(i.s();!(n=i.n()).done;){var a,u=n.value,o=p(bn(e,u.fieldPath));try{for(o.s();!(a=o.n()).done;){var s=a.value;switch(s.op){case"==":case"in":r.set(u.fieldPath.canonicalString(),s.value);break;case"not-in":case"!=":return r.set(u.fieldPath.canonicalString(),s.value),Array.from(r.values())}}}catch(c){o.e(c)}finally{o.f()}}}catch(c){i.e(c)}finally{i.f()}return null}(a,i),l=function(e,t){var n,r=[],a=!0,u=p(Ie(i));try{for(u.s();!(n=u.n()).done;){var o=n.value,s=0===o.kind?In(e,o.fieldPath,e.startAt):Tn(e,o.fieldPath,e.startAt);r.push(s.value),a&&(a=s.inclusive)}}catch(c){u.e(c)}finally{u.f()}return new Mt(r,a)}(a),f=function(e,t){var n,r=[],a=!0,u=p(Ie(i));try{for(u.s();!(n=u.n()).done;){var o=n.value,s=0===o.kind?Tn(e,o.fieldPath,e.endAt):In(e,o.fieldPath,e.endAt);r.push(s.value),a&&(a=s.inclusive)}}catch(c){u.e(c)}finally{u.f()}return new Mt(r,a)}(a),h=n.sn(i,a,l),d=n.sn(i,a,f),v=n.rn(i,a,c),y=n.on(i.indexId,s,h,l.inclusive,d,f.inclusive,v);return Re.forEach(y,function(n){return r.J(n,t.limit).next(function(t){t.forEach(function(t){var n=we.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),u.push(n))})})})}).next(function(){return u})}return Re.resolve(null)})}},{key:"en",value:function(e){var t=this.tn.get(e);return t||(t=0===e.filters.length?[e]:Ba(Bt.create(e.filters,"and")).map(function(t){return gn(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)}),this.tn.set(e,t),t)}},{key:"on",value:function(e,t,n,r,i,a,u){for(var o=this,s=(null!=t?t.length:1)*Math.max(n.length,i.length),c=s/(null!=t?t.length:1),l=[],f=function(){var s=t?o.un(t[h/c]):Ja,f=o.cn(e,s,n[h%c],r),d=o.an(e,s,i[h%c],a),v=u.map(function(t){return o.cn(e,s,t,!0)});l.push.apply(l,E(o.createRange(f,d,v)))},h=0;h<s;++h)f();return l}},{key:"cn",value:function(e,t,n,r){var i=new Ma(e,we.empty(),t,n);return r?i:i.Ge()}},{key:"an",value:function(e,t,n,r){var i=new Ma(e,we.empty(),t,n);return r?i.Ge():i}},{key:"nn",value:function(e,t){var n=new qa(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(function(e){var t,r=null,i=p(e);try{for(i.s();!(t=i.n()).done;){var a=t.value;n.We(a)&&(!r||a.fields.length>r.fields.length)&&(r=a)}}catch(u){i.e(u)}finally{i.f()}return r})}},{key:"getIndexType",value:function(e,t){var n=this,r=2,i=this.en(t);return Re.forEach(i,function(t){return n.nn(e,t).next(function(e){e?0!==r&&e.fields.length<function(e){var t,n=new ln(ke.comparator),r=!1,i=p(e.filters);try{for(i.s();!(t=i.n()).done;){var a,u=p(t.value.getFlattenedFilters());try{for(u.s();!(a=u.n()).done;){var o=a.value;o.field.isKeyField()||("array-contains"===o.op||"array-contains-any"===o.op?r=!0:n=n.add(o.field))}}catch(f){u.e(f)}finally{u.f()}}}catch(f){i.e(f)}finally{i.f()}var s,c=p(e.orderBy);try{for(c.s();!(s=c.n()).done;){var l=s.value;l.field.isKeyField()||(n=n.add(l.field))}}catch(f){c.e(f)}finally{c.f()}return n.size+(r?1:0)}(t)&&(r=1):r=0})}).next(function(){return null!==t.limit&&i.length>1&&2===r?1:r})}},{key:"hn",value:function(e,t){var n,r=new Ra,i=p(Ie(e));try{for(i.s();!(n=i.n()).done;){var a=n.value,u=t.data.field(a.fieldPath);if(null==u)return null;var o=r.Ke(a.kind);Da.Ee.ae(u,o)}}catch(s){i.e(s)}finally{i.f()}return r.Be()}},{key:"un",value:function(e){var t=new Ra;return Da.Ee.ae(e,t.Ke(0)),t.Be()}},{key:"ln",value:function(e,t){var n=new Ra;return Da.Ee.ae(Tt(this.databaseId,t),n.Ke(function(e){var t=Ie(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Be()}},{key:"rn",value:function(e,t,n){if(null===n)return[];var r=[];r.push(new Ra);var i,a=0,u=p(Ie(e));try{for(u.s();!(i=u.n()).done;){var o,s=i.value,c=n[a++],l=p(r);try{for(l.s();!(o=l.n()).done;){var f=o.value;if(this.fn(t,s.fieldPath)&&St(c))r=this.dn(r,s,c);else{var h=f.Ke(s.kind);Da.Ee.ae(c,h)}}}catch(d){l.e(d)}finally{l.f()}}}catch(d){u.e(d)}finally{u.f()}return this._n(r)}},{key:"sn",value:function(e,t,n){return this.rn(e,t,n.position)}},{key:"_n",value:function(e){for(var t=[],n=0;n<e.length;++n)t[n]=e[n].Be();return t}},{key:"dn",value:function(e,t,n){var r,i=E(e),a=[],u=p(n.arrayValue.values||[]);try{for(u.s();!(r=u.n()).done;){var o,s=r.value,c=p(i);try{for(c.s();!(o=c.n()).done;){var l=o.value,f=new Ra;f.seed(l.Be()),Da.Ee.ae(s,f.Ke(t.kind)),a.push(f)}}catch(h){c.e(h)}finally{c.f()}}}catch(h){u.e(h)}finally{u.f()}return a}},{key:"fn",value:function(e,t){return!!e.filters.find(function(e){return e instanceof Ut&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op)})}},{key:"getFieldIndexes",value:function(e,t){var n=this,r=tu(e),i=nu(e);return(t?r.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):r.W()).next(function(e){var t=[];return Re.forEach(e,function(e){return i.get([e.indexId,n.uid]).next(function(n){t.push(function(e,t){var n=t?new _e(t.sequenceNumber,new Ne(pa(t.readTime),new we(Ri(t.documentKey)),t.largestBatchId)):_e.empty(),r=e.fields.map(function(e){var t=c(e,2),n=t[0],r=t[1];return new Ee(ke.fromServerFormat(n),r)});return new xe(e.indexId,e.collectionGroup,r,n)}(e,n))})}).next(function(){return t})})}},{key:"getNextCollectionGroupToUpdate",value:function(e){return this.getFieldIndexes(e).next(function(e){return 0===e.length?null:(e.sort(function(e,t){var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:fe(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup)})}},{key:"updateCollectionGroup",value:function(e,t,n){var r=this,i=tu(e),a=nu(e);return this.wn(e).next(function(e){return i.W("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(function(t){return Re.forEach(t,function(t){return a.put(Ia(t.indexId,r.user,e,n))})})})}},{key:"updateIndexEntries",value:function(e,t){var n=this,r=new Map;return Re.forEach(t,function(t,i){var a=r.get(t.collectionGroup);return(a?Re.resolve(a):n.getFieldIndexes(e,t.collectionGroup)).next(function(a){return r.set(t.collectionGroup,a),Re.forEach(a,function(r){return n.mn(e,t,r).next(function(t){var a=n.gn(i,r);return t.isEqual(a)?Re.resolve():n.yn(e,i,r,t,a)})})})})}},{key:"pn",value:function(e,t,n,r){return eu(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.ln(n,t.key),documentKey:t.key.path.toArray()})}},{key:"In",value:function(e,t,n,r){return eu(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.ln(n,t.key),t.key.path.toArray()])}},{key:"mn",value:function(e,t,n){var r=eu(e),i=new ln(Oa);return r.X({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.ln(n,t)])},function(e,r){i=i.add(new Ma(n.indexId,t,r.arrayValue,r.directionalValue))}).next(function(){return i})}},{key:"gn",value:function(e,t){var n=new ln(Oa),r=this.hn(t,e);if(null==r)return n;var i=be(t);if(null!=i){var a=e.data.field(i.fieldPath);if(St(a)){var u,o=p(a.arrayValue.values||[]);try{for(o.s();!(u=o.n()).done;){var s=u.value;n=n.add(new Ma(t.indexId,e.key,this.un(s),r))}}catch(c){o.e(c)}finally{o.f()}}}else n=n.add(new Ma(t.indexId,e.key,Ja,r));return n}},{key:"yn",value:function(e,t,n,r,i){var a=this;G("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);var u=[];return function(e,t,n,r,i){for(var a=e.getIterator(),u=t.getIterator(),o=hn(a),s=hn(u);o||s;){var c=!1,l=!1;if(o&&s){var f=n(o,s);f<0?l=!0:f>0&&(c=!0)}else null!=o?l=!0:c=!0;c?(r(s),s=hn(u)):l?(i(o),o=hn(a)):(o=hn(a),s=hn(u))}}(r,i,Oa,function(r){u.push(a.pn(e,t,n,r))},function(r){u.push(a.In(e,t,n,r))}),Re.waitFor(u)}},{key:"wn",value:function(e){var t=1;return nu(e).X({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},function(e,n,r){r.done(),t=n.sequenceNumber+1}).next(function(){return t})}},{key:"createRange",value:function(e,t,n){n=n.sort(function(e,t){return Oa(e,t)}).filter(function(e,t,n){return!t||0!==Oa(e,n[t-1])});var r=[];r.push(e);var i,a=p(n);try{for(a.s();!(i=a.n()).done;){var u=i.value,o=Oa(u,e),s=Oa(u,t);if(0===o)r[0]=e.Ge();else if(o>0&&s<0)r.push(u),r.push(u.Ge());else if(s>0)break}}catch(d){a.e(d)}finally{a.f()}r.push(t);for(var c=[],l=0;l<r.length;l+=2){if(this.Tn(r[l],r[l+1]))return[];var f=[r[l].indexId,this.uid,r[l].arrayValue,r[l].directionalValue,Ja,[]],h=[r[l+1].indexId,this.uid,r[l+1].arrayValue,r[l+1].directionalValue,Ja,[]];c.push(IDBKeyRange.bound(f,h))}return c}},{key:"Tn",value:function(e,t){return Oa(e,t)>0}},{key:"getMinOffsetFromCollectionGroup",value:function(e,t){return this.getFieldIndexes(e,t).next(ru)}},{key:"getMinOffset",value:function(e,t){var n=this;return Re.mapArray(this.en(t),function(t){return n.nn(e,t).next(function(e){return e||W()})}).next(ru)}}]),e}();function $a(e){return ua(e,"collectionParents")}function eu(e){return ua(e,"indexEntries")}function tu(e){return ua(e,"indexConfiguration")}function nu(e){return ua(e,"indexState")}function ru(e){H(0!==e.length);for(var t=e[0].indexState.offset,n=t.largestBatchId,r=1;r<e.length;r++){var i=e[r].indexState.offset;Ce(i,t)<0&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new Ne(t.readTime,t.documentKey,n)}var iu={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},au=function(){function e(t,n,r){P(this,e),this.cacheSizeCollectionThreshold=t,this.percentileToCollect=n,this.maximumSequenceNumbersToCollect=r}return L(e,null,[{key:"withCacheSize",value:function(t){return new e(t,e.DEFAULT_COLLECTION_PERCENTILE,e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}]),e}();function uu(e,t,n){var r=e.store("mutations"),i=e.store("documentMutations"),a=[],u=IDBKeyRange.only(n.batchId),o=0,s=r.X({range:u},function(e,t,n){return o++,n.delete()});a.push(s.next(function(){H(1===o)}));var c,l=[],f=p(n.mutations);try{for(f.s();!(c=f.n()).done;){var h=c.value,d=Vi(t,h.key.path,n.batchId);a.push(i.delete(d)),l.push(h.key)}}catch(v){f.e(v)}finally{f.f()}return Re.waitFor(a).next(function(){return l})}function ou(e){if(!e)return 0;var t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw W();t=e.noDocument}return JSON.stringify(t).length}au.DEFAULT_COLLECTION_PERCENTILE=10,au.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,au.DEFAULT=new au(41943040,au.DEFAULT_COLLECTION_PERCENTILE,au.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),au.DISABLED=new au(-1,0,0);var su=function(){function e(t,n,r,i){P(this,e),this.userId=t,this.Tt=n,this.indexManager=r,this.referenceDelegate=i,this.En={}}return L(e,[{key:"checkEmpty",value:function(e){var t=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return lu(e).X({index:"userMutationsIndex",range:n},function(e,n,r){t=!1,r.done()}).next(function(){return t})}},{key:"addMutationBatch",value:function(e,t,n,r){var i=this,a=fu(e),u=lu(e);return u.add({}).next(function(o){H("number"==typeof o);var s,c=new oa(o,t,n,r),l=function(e,t,n){var r=n.baseMutations.map(function(t){return pi(e.oe,t)}),i=n.mutations.map(function(t){return pi(e.oe,t)});return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(i.Tt,i.userId,c),f=[],h=new ln(function(e,t){return fe(e.canonicalString(),t.canonicalString())}),d=p(r);try{for(d.s();!(s=d.n()).done;){var v=s.value,y=Vi(i.userId,v.key.path,o);h=h.add(v.key.path.popLast()),f.push(u.put(l)),f.push(a.put(y,qi))}}catch(m){d.e(m)}finally{d.f()}return h.forEach(function(t){f.push(i.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(function(){i.En[o]=c.keys()}),Re.waitFor(f).next(function(){return c})})}},{key:"lookupMutationBatch",value:function(e,t){var n=this;return lu(e).get(t).next(function(e){return e?(H(e.userId===n.userId),ma(n.Tt,e)):null})}},{key:"An",value:function(e,t){var n=this;return this.En[t]?Re.resolve(this.En[t]):this.lookupMutationBatch(e,t).next(function(e){if(e){var r=e.keys();return n.En[t]=r,r}return null})}},{key:"getNextMutationBatchAfterBatchId",value:function(e,t){var n=this,r=t+1,i=IDBKeyRange.lowerBound([this.userId,r]),a=null;return lu(e).X({index:"userMutationsIndex",range:i},function(e,t,i){t.userId===n.userId&&(H(t.batchId>=r),a=ma(n.Tt,t)),i.done()}).next(function(){return a})}},{key:"getHighestUnacknowledgedBatchId",value:function(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=-1;return lu(e).X({index:"userMutationsIndex",range:t,reverse:!0},function(e,t,r){n=t.batchId,r.done()}).next(function(){return n})}},{key:"getAllMutationBatches",value:function(e){var t=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return lu(e).W("userMutationsIndex",n).next(function(e){return e.map(function(e){return ma(t.Tt,e)})})}},{key:"getAllMutationBatchesAffectingDocumentKey",value:function(e,t){var n=this,r=Oi(this.userId,t.path),i=IDBKeyRange.lowerBound(r),a=[];return fu(e).X({range:i},function(r,i,u){var o=c(r,3),s=o[0],l=o[1],f=o[2],h=Ri(l);if(s===n.userId&&t.path.isEqual(h))return lu(e).get(f).next(function(e){if(!e)throw W();H(e.userId===n.userId),a.push(ma(n.Tt,e))});u.done()}).next(function(){return a})}},{key:"getAllMutationBatchesAffectingDocumentKeys",value:function(e,t){var n=this,r=new ln(fe),i=[];return t.forEach(function(t){var a=Oi(n.userId,t.path),u=IDBKeyRange.lowerBound(a),o=fu(e).X({range:u},function(e,i,a){var u=c(e,3),o=u[0],s=u[1],l=u[2],f=Ri(s);o===n.userId&&t.path.isEqual(f)?r=r.add(l):a.done()});i.push(o)}),Re.waitFor(i).next(function(){return n.Rn(e,r)})}},{key:"getAllMutationBatchesAffectingQuery",value:function(e,t){var n=this,r=t.path,i=r.length+1,a=Oi(this.userId,r),u=IDBKeyRange.lowerBound(a),o=new ln(fe);return fu(e).X({range:u},function(e,t,a){var u=c(e,3),s=u[0],l=u[1],f=u[2],h=Ri(l);s===n.userId&&r.isPrefixOf(h)?h.length===i&&(o=o.add(f)):a.done()}).next(function(){return n.Rn(e,o)})}},{key:"Rn",value:function(e,t){var n=this,r=[],i=[];return t.forEach(function(t){i.push(lu(e).get(t).next(function(e){if(null===e)throw W();H(e.userId===n.userId),r.push(ma(n.Tt,e))}))}),Re.waitFor(i).next(function(){return r})}},{key:"removeMutationBatch",value:function(e,t){var n=this;return uu(e.re,this.userId,t).next(function(r){return e.addOnCommittedListener(function(){n.Pn(t.batchId)}),Re.forEach(r,function(t){return n.referenceDelegate.markPotentiallyOrphaned(e,t)})})}},{key:"Pn",value:function(e){delete this.En[e]}},{key:"performConsistencyCheck",value:function(e){var t=this;return this.checkEmpty(e).next(function(n){if(!n)return Re.resolve();var r=IDBKeyRange.lowerBound([t.userId]),i=[];return fu(e).X({range:r},function(e,n,r){if(e[0]===t.userId){var a=Ri(e[1]);i.push(a)}else r.done()}).next(function(){H(0===i.length)})})}},{key:"containsKey",value:function(e,t){return cu(e,this.userId,t)}},{key:"vn",value:function(e){var t=this;return hu(e).get(this.userId).next(function(e){return e||{userId:t.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}})}}],[{key:"ue",value:function(t,n,r,i){return H(""!==t.uid),new e(t.isAuthenticated()?t.uid:"",n,r,i)}}]),e}();function cu(e,t,n){var r=Oi(t,n.path),i=r[1],a=IDBKeyRange.lowerBound(r),u=!1;return fu(e).X({range:a,Z:!0},function(e,n,r){var a=c(e,3),o=a[0],s=a[1];a[2];o===t&&s===i&&(u=!0),r.done()}).next(function(){return u})}function lu(e){return ua(e,"mutations")}function fu(e){return ua(e,"documentMutations")}function hu(e){return ua(e,"mutationQueues")}var du=function(){function e(t){P(this,e),this.bn=t}return L(e,[{key:"next",value:function(){return this.bn+=2,this.bn}}],[{key:"Vn",value:function(){return new e(0)}},{key:"Sn",value:function(){return new e(-1)}}]),e}(),vu=function(){function e(t,n){P(this,e),this.referenceDelegate=t,this.Tt=n}return L(e,[{key:"allocateTargetId",value:function(e){var t=this;return this.Dn(e).next(function(n){var r=new du(n.highestTargetId);return n.highestTargetId=r.next(),t.Cn(e,n).next(function(){return n.highestTargetId})})}},{key:"getLastRemoteSnapshotVersion",value:function(e){return this.Dn(e).next(function(e){return ye.fromTimestamp(new ve(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))})}},{key:"getHighestSequenceNumber",value:function(e){return this.Dn(e).next(function(e){return e.highestListenSequenceNumber})}},{key:"setTargetsMetadata",value:function(e,t,n){var r=this;return this.Dn(e).next(function(i){return i.highestListenSequenceNumber=t,n&&(i.lastRemoteSnapshotVersion=n.toTimestamp()),t>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=t),r.Cn(e,i)})}},{key:"addTargetData",value:function(e,t){var n=this;return this.xn(e,t).next(function(){return n.Dn(e).next(function(r){return r.targetCount+=1,n.Nn(t,r),n.Cn(e,r)})})}},{key:"updateTargetData",value:function(e,t){return this.xn(e,t)}},{key:"removeTargetData",value:function(e,t){var n=this;return this.removeMatchingKeysForTargetId(e,t.targetId).next(function(){return yu(e).delete(t.targetId)}).next(function(){return n.Dn(e)}).next(function(t){return H(t.targetCount>0),t.targetCount-=1,n.Cn(e,t)})}},{key:"removeTargets",value:function(e,t,n){var r=this,i=0,a=[];return yu(e).X(function(u,o){var s=ga(o);s.sequenceNumber<=t&&null===n.get(s.targetId)&&(i++,a.push(r.removeTargetData(e,s)))}).next(function(){return Re.waitFor(a)}).next(function(){return i})}},{key:"forEachTarget",value:function(e,t){return yu(e).X(function(e,n){var r=ga(n);t(r)})}},{key:"Dn",value:function(e){return pu(e).get("targetGlobalKey").next(function(e){return H(null!==e),e})}},{key:"Cn",value:function(e,t){return pu(e).put("targetGlobalKey",t)}},{key:"xn",value:function(e,t){return yu(e).put(ka(this.Tt,t))}},{key:"Nn",value:function(e,t){var n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}},{key:"getTargetCount",value:function(e){return this.Dn(e).next(function(e){return e.targetCount})}},{key:"getTargetData",value:function(e,t){var n=kn(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]),i=null;return yu(e).X({range:r,index:"queryTargetsIndex"},function(e,n,r){var a=ga(n);wn(t,a.target)&&(i=a,r.done())}).next(function(){return i})}},{key:"addMatchingKeys",value:function(e,t,n){var r=this,i=[],a=mu(e);return t.forEach(function(t){var u=Pi(t.path);i.push(a.put({targetId:n,path:u})),i.push(r.referenceDelegate.addReference(e,n,t))}),Re.waitFor(i)}},{key:"removeMatchingKeys",value:function(e,t,n){var r=this,i=mu(e);return Re.forEach(t,function(t){var a=Pi(t.path);return Re.waitFor([i.delete([n,a]),r.referenceDelegate.removeReference(e,n,t)])})}},{key:"removeMatchingKeysForTargetId",value:function(e,t){var n=mu(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}},{key:"getMatchingKeysForTargetId",value:function(e,t){var n=IDBKeyRange.bound([t],[t+1],!1,!0),r=mu(e),i=Vr();return r.X({range:n,Z:!0},function(e,t,n){var r=Ri(e[1]),a=new we(r);i=i.add(a)}).next(function(){return i})}},{key:"containsKey",value:function(e,t){var n=Pi(t.path),r=IDBKeyRange.bound([n],[de(n)],!1,!0),i=0;return mu(e).X({index:"documentTargetsIndex",Z:!0,range:r},function(e,t,n){var r=c(e,2),a=r[0];r[1];0!==a&&(i++,n.done())}).next(function(){return i>0})}},{key:"ie",value:function(e,t){return yu(e).get(t).next(function(e){return e?ga(e):null})}}]),e}();function yu(e){return ua(e,"targets")}function pu(e){return ua(e,"targetGlobal")}function mu(e){return ua(e,"targetDocuments")}function gu(e,t){var n=c(e,2),r=n[0],i=n[1],a=c(t,2),u=a[0],o=a[1],s=fe(r,u);return 0===s?fe(i,o):s}var ku=function(){function e(t){P(this,e),this.kn=t,this.buffer=new ln(gu),this.$n=0}return L(e,[{key:"Mn",value:function(){return++this.$n}},{key:"On",value:function(e){var t=[e,this.Mn()];if(this.buffer.size<this.kn)this.buffer=this.buffer.add(t);else{var n=this.buffer.last();gu(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}},{key:"maxValue",get:function(){return this.buffer.last()[0]}}]),e}(),wu=function(){function e(t,n,r){P(this,e),this.garbageCollector=t,this.asyncQueue=n,this.localStore=r,this.Fn=null}return L(e,[{key:"start",value:function(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Bn(6e4)}},{key:"stop",value:function(){this.Fn&&(this.Fn.cancel(),this.Fn=null)}},{key:"started",get:function(){return null!==this.Fn}},{key:"Bn",value:function(e){var t=this;G("LruGarbageCollector","Garbage collection scheduled in ".concat(e,"ms")),this.Fn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return t.Fn=null,e.prev=1,e.next=4,m().awrap(t.localStore.collectGarbage(t.garbageCollector));case 4:e.next=14;break;case 6:if(e.prev=6,e.t0=e.catch(1),!Ue(e.t0)){e.next=12;break}G("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e.t0),e.next=14;break;case 12:return e.next=14,m().awrap(Le(e.t0));case 14:return e.next=16,m().awrap(t.Bn(3e5));case 16:case"end":return e.stop()}},null,null,[[1,6]],Promise)})}}]),e}(),xu=function(){function e(t,n){P(this,e),this.Ln=t,this.params=n}return L(e,[{key:"calculateTargetCount",value:function(e,t){return this.Ln.qn(e).next(function(e){return Math.floor(t/100*e)})}},{key:"nthSequenceNumber",value:function(e,t){var n=this;if(0===t)return Re.resolve(We.at);var r=new ku(t);return this.Ln.forEachTarget(e,function(e){return r.On(e.sequenceNumber)}).next(function(){return n.Ln.Un(e,function(e){return r.On(e)})}).next(function(){return r.maxValue})}},{key:"removeTargets",value:function(e,t,n){return this.Ln.removeTargets(e,t,n)}},{key:"removeOrphanedDocuments",value:function(e,t){return this.Ln.removeOrphanedDocuments(e,t)}},{key:"collect",value:function(e,t){var n=this;return-1===this.params.cacheSizeCollectionThreshold?(G("LruGarbageCollector","Garbage collection skipped; disabled"),Re.resolve(iu)):this.getCacheSize(e).next(function(r){return r<n.params.cacheSizeCollectionThreshold?(G("LruGarbageCollector","Garbage collection skipped; Cache size ".concat(r," is lower than threshold ").concat(n.params.cacheSizeCollectionThreshold)),iu):n.Kn(e,t)})}},{key:"getCacheSize",value:function(e){return this.Ln.getCacheSize(e)}},{key:"Kn",value:function(e,t){var n,r,a,u,o,s,c,l=this,f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(function(t){return t>l.params.maximumSequenceNumbersToCollect?(G("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of ".concat(l.params.maximumSequenceNumbersToCollect," from ").concat(t)),r=l.params.maximumSequenceNumbersToCollect):r=t,u=Date.now(),l.nthSequenceNumber(e,r)}).next(function(r){return n=r,o=Date.now(),l.removeTargets(e,n,t)}).next(function(t){return a=t,s=Date.now(),l.removeOrphanedDocuments(e,n)}).next(function(e){return c=Date.now(),B()<=i.LogLevel.DEBUG&&G("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in ".concat(u-f,"ms\n\tDetermined least recently used ").concat(r," in ")+(o-u)+"ms\n"+"\tRemoved ".concat(a," targets in ")+(s-o)+"ms\n"+"\tRemoved ".concat(e," documents in ")+(c-s)+"ms\n"+"Total Duration: ".concat(c-f,"ms")),Re.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:a,documentsRemoved:e})})}}]),e}(),bu=function(){function e(t,n){P(this,e),this.db=t,this.garbageCollector=function(e,t){return new xu(e,t)}(this,n)}return L(e,[{key:"qn",value:function(e){var t=this.Gn(e);return this.db.getTargetCache().getTargetCount(e).next(function(e){return t.next(function(t){return e+t})})}},{key:"Gn",value:function(e){var t=0;return this.Un(e,function(e){t++}).next(function(){return t})}},{key:"forEachTarget",value:function(e,t){return this.db.getTargetCache().forEachTarget(e,t)}},{key:"Un",value:function(e,t){return this.Qn(e,function(e,n){return t(n)})}},{key:"addReference",value:function(e,t,n){return Iu(e,n)}},{key:"removeReference",value:function(e,t,n){return Iu(e,n)}},{key:"removeTargets",value:function(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}},{key:"markPotentiallyOrphaned",value:function(e,t){return Iu(e,t)}},{key:"jn",value:function(e,t){return function(e,t){var n=!1;return hu(e).tt(function(r){return cu(e,r,t).next(function(e){return e&&(n=!0),Re.resolve(!e)})}).next(function(){return n})}(e,t)}},{key:"removeOrphanedDocuments",value:function(e,t){var n=this,r=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[],a=0;return this.Qn(e,function(u,o){if(o<=t){var s=n.jn(e,u).next(function(t){if(!t)return a++,r.getEntry(e,u).next(function(){return r.removeEntry(u,ye.min()),mu(e).delete([0,Pi(u.path)])})});i.push(s)}}).next(function(){return Re.waitFor(i)}).next(function(){return r.apply(e)}).next(function(){return a})}},{key:"removeTarget",value:function(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}},{key:"updateLimboDocument",value:function(e,t){return Iu(e,t)}},{key:"Qn",value:function(e,t){var n,r=mu(e),i=We.at;return r.X({index:"documentTargetsIndex"},function(e,r){var a=c(e,2),u=a[0],o=(a[1],r.path),s=r.sequenceNumber;0===u?(i!==We.at&&t(new we(Ri(n)),i),i=s,n=o):i=We.at}).next(function(){i!==We.at&&t(new we(Ri(n)),i)})}},{key:"getCacheSize",value:function(e){return this.db.getRemoteDocumentCache().getSize(e)}}]),e}();function Iu(e,t){return mu(e).put(function(e,t){return{targetId:0,path:Pi(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}var Tu=function(){function e(){P(this,e),this.changes=new _r(function(e){return e.toString()},function(e,t){return e.isEqual(t)}),this.changesApplied=!1}return L(e,[{key:"addEntry",value:function(e){this.assertNotApplied(),this.changes.set(e.key,e)}},{key:"removeEntry",value:function(e,t){this.assertNotApplied(),this.changes.set(e,pn.newInvalidDocument(e).setReadTime(t))}},{key:"getEntry",value:function(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?Re.resolve(n):this.getFromCache(e,t)}},{key:"getEntries",value:function(e,t){return this.getAllFromCache(e,t)}},{key:"apply",value:function(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}},{key:"assertNotApplied",value:function(){}}]),e}(),Eu=function(){function e(t){P(this,e),this.Tt=t}return L(e,[{key:"setIndexManager",value:function(e){this.indexManager=e}},{key:"addEntry",value:function(e,t,n){return Du(e).put(n)}},{key:"removeEntry",value:function(e,t,n){return Du(e).delete(function(e,t){var n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],va(t),n[n.length-1]]}(t,n))}},{key:"updateMetadata",value:function(e,t){var n=this;return this.getMetadata(e).next(function(r){return r.byteSize+=t,n.zn(e,r)})}},{key:"getEntry",value:function(e,t){var n=this,r=pn.newInvalidDocument(t);return Du(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(Nu(t))},function(e,i){r=n.Wn(t,i)}).next(function(){return r})}},{key:"Hn",value:function(e,t){var n=this,r={size:0,document:pn.newInvalidDocument(t)};return Du(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(Nu(t))},function(e,i){r={document:n.Wn(t,i),size:ou(i)}}).next(function(){return r})}},{key:"getEntries",value:function(e,t){var n=this,r=Dr();return this.Jn(e,t,function(e,t){var i=n.Wn(e,t);r=r.insert(e,i)}).next(function(){return r})}},{key:"Yn",value:function(e,t){var n=this,r=Dr(),i=new on(we.comparator);return this.Jn(e,t,function(e,t){var a=n.Wn(e,t);r=r.insert(e,a),i=i.insert(e,ou(t))}).next(function(){return{documents:r,Zn:i}})}},{key:"Jn",value:function(e,t,n){if(t.isEmpty())return Re.resolve();var r=new ln(Pu);t.forEach(function(e){return r=r.add(e)});var i=IDBKeyRange.bound(Nu(r.first()),Nu(r.last())),a=r.getIterator(),u=a.getNext();return Du(e).X({index:"documentKeyIndex",range:i},function(e,t,r){for(var i=we.fromSegments([].concat(E(t.prefixPath),[t.collectionGroup,t.documentId]));u&&Pu(u,i)<0;)n(u,null),u=a.getNext();u&&u.isEqual(i)&&(n(u,t),u=a.hasNext()?a.getNext():null),u?r.j(Nu(u)):r.done()}).next(function(){for(;u;)n(u,null),u=a.hasNext()?a.getNext():null})}},{key:"getDocumentsMatchingQuery",value:function(e,t,n,r){var i=this,a=t.path,u=[a.popLast().toArray(),a.lastSegment(),va(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[a.popLast().toArray(),a.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Du(e).W(IDBKeyRange.bound(u,o,!0)).next(function(e){var n,a=Dr(),u=p(e);try{for(u.s();!(n=u.n()).done;){var o=n.value,s=i.Wn(we.fromSegments(o.prefixPath.concat(o.collectionGroup,o.documentId)),o);s.isFoundDocument()&&(qn(t,s)||r.has(s.key))&&(a=a.insert(s.key,s))}}catch(c){u.e(c)}finally{u.f()}return a})}},{key:"getAllFromCollectionGroup",value:function(e,t,n,r){var i=this,a=Dr(),u=Cu(t,n),o=Cu(t,Ne.max());return Du(e).X({index:"collectionGroupIndex",range:IDBKeyRange.bound(u,o,!0)},function(e,t,n){var u=i.Wn(we.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(a=a.insert(u.key,u)).size===r&&n.done()}).next(function(){return a})}},{key:"newChangeBuffer",value:function(e){return new _u(this,!!e&&e.trackRemovals)}},{key:"getSize",value:function(e){return this.getMetadata(e).next(function(e){return e.byteSize})}},{key:"getMetadata",value:function(e){return Au(e).get("remoteDocumentGlobalKey").next(function(e){return H(!!e),e})}},{key:"zn",value:function(e,t){return Au(e).put("remoteDocumentGlobalKey",t)}},{key:"Wn",value:function(e,t){if(t){var n=ha(this.Tt,t);if(!n.isNoDocument()||!n.version.isEqual(ye.min()))return n}return pn.newInvalidDocument(e)}}]),e}();function Su(e){return new Eu(e)}var _u=function(e){g(n,Tu);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).Xn=e,i.trackRemovals=r,i.ts=new _r(function(e){return e.toString()},function(e,t){return e.isEqual(t)}),i}return L(n,[{key:"applyChanges",value:function(e){var t=this,n=[],r=0,i=new ln(function(e,t){return fe(e.canonicalString(),t.canonicalString())});return this.changes.forEach(function(a,u){var o=t.ts.get(a);if(n.push(t.Xn.removeEntry(e,a,o.readTime)),u.isValidDocument()){var s=da(t.Xn.Tt,u);i=i.add(a.path.popLast());var c=ou(s);r+=c-o.size,n.push(t.Xn.addEntry(e,a,s))}else if(r-=o.size,t.trackRemovals){var l=da(t.Xn.Tt,u.convertToNoDocument(ye.min()));n.push(t.Xn.addEntry(e,a,l))}}),i.forEach(function(r){n.push(t.Xn.indexManager.addToCollectionParentIndex(e,r))}),n.push(this.Xn.updateMetadata(e,r)),Re.waitFor(n)}},{key:"getFromCache",value:function(e,t){var n=this;return this.Xn.Hn(e,t).next(function(e){return n.ts.set(t,{size:e.size,readTime:e.document.readTime}),e.document})}},{key:"getAllFromCache",value:function(e,t){var n=this;return this.Xn.Yn(e,t).next(function(e){var t=e.documents;return e.Zn.forEach(function(e,r){n.ts.set(e,{size:r,readTime:t.get(e).readTime})}),t})}}]),n}();function Au(e){return ua(e,"remoteDocumentGlobal")}function Du(e){return ua(e,"remoteDocumentsV14")}function Nu(e){var t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Cu(e,t){var n=t.documentKey.path.toArray();return[e,va(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function Pu(e,t){for(var n=e.path.toArray(),r=t.path.toArray(),i=0,a=0;a<n.length-2&&a<r.length-2;++a)if(i=fe(n[a],r[a]))return i;return(i=fe(n.length,r.length))||((i=fe(n[n.length-2],r[r.length-2]))||fe(n[n.length-1],r[r.length-1]))}var Fu=L(function e(t,n){P(this,e),this.overlayedDocument=t,this.mutatedFields=n}),Lu=function(){function e(t,n,r,i){P(this,e),this.remoteDocumentCache=t,this.mutationQueue=n,this.documentOverlayCache=r,this.indexManager=i}return L(e,[{key:"getDocument",value:function(e,t){var n=this,r=null;return this.documentOverlayCache.getOverlay(e,t).next(function(i){return r=i,n.remoteDocumentCache.getEntry(e,t)}).next(function(e){return null!==r&&hr(r.mutation,e,dn.empty(),ve.now()),e})}},{key:"getDocuments",value:function(e,t){var n=this;return this.remoteDocumentCache.getEntries(e,t).next(function(t){return n.getLocalViewOfDocuments(e,t,Vr()).next(function(){return t})})}},{key:"getLocalViewOfDocuments",value:function(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Vr(),i=Fr();return this.populateOverlays(e,i,t).next(function(){return n.computeViews(e,t,i,r).next(function(e){var t=Cr();return e.forEach(function(e,n){t=t.insert(e,n.overlayedDocument)}),t})})}},{key:"getOverlayedDocuments",value:function(e,t){var n=this,r=Fr();return this.populateOverlays(e,r,t).next(function(){return n.computeViews(e,t,r,Vr())})}},{key:"populateOverlays",value:function(e,t,n){var r=[];return n.forEach(function(e){t.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(function(e){e.forEach(function(e,n){t.set(e,n)})})}},{key:"computeViews",value:function(e,t,n,r){var i=Dr(),a=Rr(),u=Rr();return t.forEach(function(e,t){var u=n.get(t.key);r.has(t.key)&&(void 0===u||u.mutation instanceof pr)?i=i.insert(t.key,t):void 0!==u?(a.set(t.key,u.mutation.getFieldMask()),hr(u.mutation,t,u.mutation.getFieldMask(),ve.now())):a.set(t.key,dn.empty())}),this.recalculateAndSaveOverlays(e,i).next(function(e){return e.forEach(function(e,t){return a.set(e,t)}),t.forEach(function(e,t){var n;return u.set(e,new Fu(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),u})}},{key:"recalculateAndSaveOverlays",value:function(e,t){var n=this,r=Rr(),i=new on(function(e,t){return e-t}),a=Vr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(function(e){var n,a=p(e);try{var u=function(){var e=n.value;e.keys().forEach(function(n){var a=t.get(n);if(null!==a){var u=r.get(n)||dn.empty();u=e.applyToLocalView(a,u),r.set(n,u);var o=(i.get(e.batchId)||Vr()).add(n);i=i.insert(e.batchId,o)}})};for(a.s();!(n=a.n()).done;)u()}catch(o){a.e(o)}finally{a.f()}}).next(function(){for(var u=[],o=i.getReverseIterator(),s=function(){var i=o.getNext(),s=i.key,c=i.value,l=Lr();c.forEach(function(e){if(!a.has(e)){var n=lr(t.get(e),r.get(e));null!==n&&l.set(e,n),a=a.add(e)}}),u.push(n.documentOverlayCache.saveOverlays(e,s,l))};o.hasNext();)s();return Re.waitFor(u)}).next(function(){return r})}},{key:"recalculateAndSaveOverlaysForDocumentKeys",value:function(e,t){var n=this;return this.remoteDocumentCache.getEntries(e,t).next(function(t){return n.recalculateAndSaveOverlays(e,t)})}},{key:"getDocumentsMatchingQuery",value:function(e,t,n){return function(e){return we.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Cn(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n)}},{key:"getNextDocuments",value:function(e,t,n,r){var i=this;return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(function(a){var u=r-a.size>0?i.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-a.size):Re.resolve(Fr()),o=-1,s=a;return u.next(function(t){return Re.forEach(t,function(t,n){return o<n.largestBatchId&&(o=n.largestBatchId),a.get(t)?Re.resolve():i.remoteDocumentCache.getEntry(e,t).next(function(e){s=s.insert(t,e)})}).next(function(){return i.populateOverlays(e,t,a)}).next(function(){return i.computeViews(e,s,t,Vr())}).next(function(e){return{batchId:o,changes:Pr(e)}})})})}},{key:"getDocumentsMatchingDocumentQuery",value:function(e,t){return this.getDocument(e,new we(t)).next(function(e){var t=Cr();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}},{key:"getDocumentsMatchingCollectionGroupQuery",value:function(e,t,n){var r=this,i=t.collectionGroup,a=Cr();return this.indexManager.getCollectionParents(e,i).next(function(u){return Re.forEach(u,function(u){var o=function(e,t){return new En(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,u.child(i));return r.getDocumentsMatchingCollectionQuery(e,o,n).next(function(e){e.forEach(function(e,t){a=a.insert(e,t)})})}).next(function(){return a})})}},{key:"getDocumentsMatchingCollectionQuery",value:function(e,t,n){var r,i=this;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(function(a){return r=a,i.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,r)}).next(function(e){r.forEach(function(t,n){var r=n.getKey();null===e.get(r)&&(e=e.insert(r,pn.newInvalidDocument(r)))});var n=Cr();return e.forEach(function(e,i){var a=r.get(e);void 0!==a&&hr(a.mutation,i,dn.empty(),ve.now()),qn(t,i)&&(n=n.insert(e,i))}),n})}}]),e}(),Ru=function(){function e(t){P(this,e),this.Tt=t,this.es=new Map,this.ns=new Map}return L(e,[{key:"getBundleMetadata",value:function(e,t){return Re.resolve(this.es.get(t))}},{key:"saveBundleMetadata",value:function(e,t){var n;return this.es.set(t.id,{id:(n=t).id,version:n.version,createTime:ri(n.createTime)}),Re.resolve()}},{key:"getNamedQuery",value:function(e,t){return Re.resolve(this.ns.get(t))}},{key:"saveNamedQuery",value:function(e,t){return this.ns.set(t.name,function(e){return{name:e.name,query:wa(e.bundledQuery),readTime:ri(e.readTime)}}(t)),Re.resolve()}}]),e}(),Mu=function(){function e(){P(this,e),this.overlays=new on(we.comparator),this.ss=new Map}return L(e,[{key:"getOverlay",value:function(e,t){return Re.resolve(this.overlays.get(t))}},{key:"getOverlays",value:function(e,t){var n=this,r=Fr();return Re.forEach(t,function(t){return n.getOverlay(e,t).next(function(e){null!==e&&r.set(t,e)})}).next(function(){return r})}},{key:"saveOverlays",value:function(e,t,n){var r=this;return n.forEach(function(n,i){r.ce(e,t,i)}),Re.resolve()}},{key:"removeOverlaysForBatchId",value:function(e,t,n){var r=this,i=this.ss.get(n);return void 0!==i&&(i.forEach(function(e){return r.overlays=r.overlays.remove(e)}),this.ss.delete(n)),Re.resolve()}},{key:"getOverlaysForCollection",value:function(e,t,n){for(var r=Fr(),i=t.length+1,a=new we(t.child("")),u=this.overlays.getIteratorFrom(a);u.hasNext();){var o=u.getNext().value,s=o.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&o.largestBatchId>n&&r.set(o.getKey(),o)}return Re.resolve(r)}},{key:"getOverlaysForCollectionGroup",value:function(e,t,n,r){for(var i=new on(function(e,t){return e-t}),a=this.overlays.getIterator();a.hasNext();){var u=a.getNext().value;if(u.getKey().getCollectionGroup()===t&&u.largestBatchId>n){var o=i.get(u.largestBatchId);null===o&&(o=Fr(),i=i.insert(u.largestBatchId,o)),o.set(u.getKey(),u)}}for(var s=Fr(),c=i.getIterator();c.hasNext()&&(c.getNext().value.forEach(function(e,t){return s.set(e,t)}),!(s.size()>=r)););return Re.resolve(s)}},{key:"ce",value:function(e,t,n){var r=this.overlays.get(n.key);if(null!==r){var i=this.ss.get(r.largestBatchId).delete(n.key);this.ss.set(r.largestBatchId,i)}this.overlays=this.overlays.insert(n.key,new ca(t,n));var a=this.ss.get(t);void 0===a&&(a=Vr(),this.ss.set(t,a)),this.ss.set(t,a.add(n.key))}}]),e}(),Ou=function(){function e(){P(this,e),this.rs=new ln(Vu.os),this.us=new ln(Vu.cs)}return L(e,[{key:"isEmpty",value:function(){return this.rs.isEmpty()}},{key:"addReference",value:function(e,t){var n=new Vu(e,t);this.rs=this.rs.add(n),this.us=this.us.add(n)}},{key:"hs",value:function(e,t){var n=this;e.forEach(function(e){return n.addReference(e,t)})}},{key:"removeReference",value:function(e,t){this.ls(new Vu(e,t))}},{key:"fs",value:function(e,t){var n=this;e.forEach(function(e){return n.removeReference(e,t)})}},{key:"ds",value:function(e){var t=this,n=new we(new me([])),r=new Vu(n,e),i=new Vu(n,e+1),a=[];return this.us.forEachInRange([r,i],function(e){t.ls(e),a.push(e.key)}),a}},{key:"_s",value:function(){var e=this;this.rs.forEach(function(t){return e.ls(t)})}},{key:"ls",value:function(e){this.rs=this.rs.delete(e),this.us=this.us.delete(e)}},{key:"ws",value:function(e){var t=new we(new me([])),n=new Vu(t,e),r=new Vu(t,e+1),i=Vr();return this.us.forEachInRange([n,r],function(e){i=i.add(e.key)}),i}},{key:"containsKey",value:function(e){var t=new Vu(e,0),n=this.rs.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}]),e}(),Vu=function(){function e(t,n){P(this,e),this.key=t,this.gs=n}return L(e,null,[{key:"os",value:function(e,t){return we.comparator(e.key,t.key)||fe(e.gs,t.gs)}},{key:"cs",value:function(e,t){return fe(e.gs,t.gs)||we.comparator(e.key,t.key)}}]),e}(),qu=function(){function e(t,n){P(this,e),this.indexManager=t,this.referenceDelegate=n,this.mutationQueue=[],this.ys=1,this.ps=new ln(Vu.os)}return L(e,[{key:"checkEmpty",value:function(e){return Re.resolve(0===this.mutationQueue.length)}},{key:"addMutationBatch",value:function(e,t,n,r){var i=this.ys;this.ys++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];var a=new oa(i,t,n,r);this.mutationQueue.push(a);var u,o=p(r);try{for(o.s();!(u=o.n()).done;){var s=u.value;this.ps=this.ps.add(new Vu(s.key,i)),this.indexManager.addToCollectionParentIndex(e,s.key.path.popLast())}}catch(c){o.e(c)}finally{o.f()}return Re.resolve(a)}},{key:"lookupMutationBatch",value:function(e,t){return Re.resolve(this.Is(t))}},{key:"getNextMutationBatchAfterBatchId",value:function(e,t){var n=t+1,r=this.Ts(n),i=r<0?0:r;return Re.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}},{key:"getHighestUnacknowledgedBatchId",value:function(){return Re.resolve(0===this.mutationQueue.length?-1:this.ys-1)}},{key:"getAllMutationBatches",value:function(e){return Re.resolve(this.mutationQueue.slice())}},{key:"getAllMutationBatchesAffectingDocumentKey",value:function(e,t){var n=this,r=new Vu(t,0),i=new Vu(t,Number.POSITIVE_INFINITY),a=[];return this.ps.forEachInRange([r,i],function(e){var t=n.Is(e.gs);a.push(t)}),Re.resolve(a)}},{key:"getAllMutationBatchesAffectingDocumentKeys",value:function(e,t){var n=this,r=new ln(fe);return t.forEach(function(e){var t=new Vu(e,0),i=new Vu(e,Number.POSITIVE_INFINITY);n.ps.forEachInRange([t,i],function(e){r=r.add(e.gs)})}),Re.resolve(this.Es(r))}},{key:"getAllMutationBatchesAffectingQuery",value:function(e,t){var n=t.path,r=n.length+1,i=n;we.isDocumentKey(i)||(i=i.child(""));var a=new Vu(new we(i),0),u=new ln(fe);return this.ps.forEachWhile(function(e){var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(u=u.add(e.gs)),!0)},a),Re.resolve(this.Es(u))}},{key:"Es",value:function(e){var t=this,n=[];return e.forEach(function(e){var r=t.Is(e);null!==r&&n.push(r)}),n}},{key:"removeMutationBatch",value:function(e,t){var n=this;H(0===this.As(t.batchId,"removed")),this.mutationQueue.shift();var r=this.ps;return Re.forEach(t.mutations,function(i){var a=new Vu(i.key,t.batchId);return r=r.delete(a),n.referenceDelegate.markPotentiallyOrphaned(e,i.key)}).next(function(){n.ps=r})}},{key:"Pn",value:function(e){}},{key:"containsKey",value:function(e,t){var n=new Vu(t,0),r=this.ps.firstAfterOrEqual(n);return Re.resolve(t.isEqual(r&&r.key))}},{key:"performConsistencyCheck",value:function(e){return this.mutationQueue.length,Re.resolve()}},{key:"As",value:function(e,t){return this.Ts(e)}},{key:"Ts",value:function(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}},{key:"Is",value:function(e){var t=this.Ts(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}]),e}(),Uu=function(){function e(t){P(this,e),this.Rs=t,this.docs=new on(we.comparator),this.size=0}return L(e,[{key:"setIndexManager",value:function(e){this.indexManager=e}},{key:"addEntry",value:function(e,t){var n=t.key,r=this.docs.get(n),i=r?r.size:0,a=this.Rs(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}},{key:"removeEntry",value:function(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}},{key:"getEntry",value:function(e,t){var n=this.docs.get(t);return Re.resolve(n?n.document.mutableCopy():pn.newInvalidDocument(t))}},{key:"getEntries",value:function(e,t){var n=this,r=Dr();return t.forEach(function(e){var t=n.docs.get(e);r=r.insert(e,t?t.document.mutableCopy():pn.newInvalidDocument(e))}),Re.resolve(r)}},{key:"getDocumentsMatchingQuery",value:function(e,t,n,r){for(var i=Dr(),a=t.path,u=new we(a.child("")),o=this.docs.getIteratorFrom(u);o.hasNext();){var s=o.getNext(),c=s.key,l=s.value.document;if(!a.isPrefixOf(c.path))break;c.path.length>a.length+1||Ce(De(l),n)<=0||(r.has(l.key)||qn(t,l))&&(i=i.insert(l.key,l.mutableCopy()))}return Re.resolve(i)}},{key:"getAllFromCollectionGroup",value:function(e,t,n,r){W()}},{key:"Ps",value:function(e,t){return Re.forEach(this.docs,function(e){return t(e)})}},{key:"newChangeBuffer",value:function(e){return new Bu(this)}},{key:"getSize",value:function(e){return Re.resolve(this.size)}}]),e}(),Bu=function(e){g(n,Tu);var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this)).Xn=e,r}return L(n,[{key:"applyChanges",value:function(e){var t=this,n=[];return this.changes.forEach(function(r,i){i.isValidDocument()?n.push(t.Xn.addEntry(e,i)):t.Xn.removeEntry(r)}),Re.waitFor(n)}},{key:"getFromCache",value:function(e,t){return this.Xn.getEntry(e,t)}},{key:"getAllFromCache",value:function(e,t){return this.Xn.getEntries(e,t)}}]),n}(),Ku=function(){function e(t){P(this,e),this.persistence=t,this.vs=new _r(function(e){return kn(e)},wn),this.lastRemoteSnapshotVersion=ye.min(),this.highestTargetId=0,this.bs=0,this.Vs=new Ou,this.targetCount=0,this.Ss=du.Vn()}return L(e,[{key:"forEachTarget",value:function(e,t){return this.vs.forEach(function(e,n){return t(n)}),Re.resolve()}},{key:"getLastRemoteSnapshotVersion",value:function(e){return Re.resolve(this.lastRemoteSnapshotVersion)}},{key:"getHighestSequenceNumber",value:function(e){return Re.resolve(this.bs)}},{key:"allocateTargetId",value:function(e){return this.highestTargetId=this.Ss.next(),Re.resolve(this.highestTargetId)}},{key:"setTargetsMetadata",value:function(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),Re.resolve()}},{key:"xn",value:function(e){this.vs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Ss=new du(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}},{key:"addTargetData",value:function(e,t){return this.xn(t),this.targetCount+=1,Re.resolve()}},{key:"updateTargetData",value:function(e,t){return this.xn(t),Re.resolve()}},{key:"removeTargetData",value:function(e,t){return this.vs.delete(t.target),this.Vs.ds(t.targetId),this.targetCount-=1,Re.resolve()}},{key:"removeTargets",value:function(e,t,n){var r=this,i=0,a=[];return this.vs.forEach(function(u,o){o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r.vs.delete(u),a.push(r.removeMatchingKeysForTargetId(e,o.targetId)),i++)}),Re.waitFor(a).next(function(){return i})}},{key:"getTargetCount",value:function(e){return Re.resolve(this.targetCount)}},{key:"getTargetData",value:function(e,t){var n=this.vs.get(t)||null;return Re.resolve(n)}},{key:"addMatchingKeys",value:function(e,t,n){return this.Vs.hs(t,n),Re.resolve()}},{key:"removeMatchingKeys",value:function(e,t,n){this.Vs.fs(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(function(t){i.push(r.markPotentiallyOrphaned(e,t))}),Re.waitFor(i)}},{key:"removeMatchingKeysForTargetId",value:function(e,t){return this.Vs.ds(t),Re.resolve()}},{key:"getMatchingKeysForTargetId",value:function(e,t){var n=this.Vs.ws(t);return Re.resolve(n)}},{key:"containsKey",value:function(e,t){return Re.resolve(this.Vs.containsKey(t))}}]),e}(),Gu=function(){function e(t,n){var r=this;P(this,e),this.Ds={},this.overlays={},this.Cs=new We(0),this.xs=!1,this.xs=!0,this.referenceDelegate=t(this),this.Ns=new Ku(this),this.indexManager=new Xa,this.remoteDocumentCache=new Uu(function(e){return r.referenceDelegate.ks(e)}),this.Tt=new fa(n),this.$s=new Ru(this.Tt)}return L(e,[{key:"start",value:function(){return Promise.resolve()}},{key:"shutdown",value:function(){return this.xs=!1,Promise.resolve()}},{key:"started",get:function(){return this.xs}},{key:"setDatabaseDeletedListener",value:function(){}},{key:"setNetworkEnabled",value:function(){}},{key:"getIndexManager",value:function(e){return this.indexManager}},{key:"getDocumentOverlayCache",value:function(e){var t=this.overlays[e.toKey()];return t||(t=new Mu,this.overlays[e.toKey()]=t),t}},{key:"getMutationQueue",value:function(e,t){var n=this.Ds[e.toKey()];return n||(n=new qu(t,this.referenceDelegate),this.Ds[e.toKey()]=n),n}},{key:"getTargetCache",value:function(){return this.Ns}},{key:"getRemoteDocumentCache",value:function(){return this.remoteDocumentCache}},{key:"getBundleCache",value:function(){return this.$s}},{key:"runTransaction",value:function(e,t,n){var r=this;G("MemoryPersistence","Starting transaction:",e);var i=new Qu(this.Cs.next());return this.referenceDelegate.Ms(),n(i).next(function(e){return r.referenceDelegate.Os(i).next(function(){return e})}).toPromise().then(function(e){return i.raiseOnCommittedEvent(),e})}},{key:"Fs",value:function(e,t){return Re.or(Object.values(this.Ds).map(function(n){return function(){return n.containsKey(e,t)}}))}}]),e}(),Qu=function(e){g(n,Fe);var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this)).currentSequenceNumber=e,r}return L(n)}(),ju=function(){function e(t){P(this,e),this.persistence=t,this.Bs=new Ou,this.Ls=null}return L(e,[{key:"Us",get:function(){if(this.Ls)return this.Ls;throw W()}},{key:"addReference",value:function(e,t,n){return this.Bs.addReference(n,t),this.Us.delete(n.toString()),Re.resolve()}},{key:"removeReference",value:function(e,t,n){return this.Bs.removeReference(n,t),this.Us.add(n.toString()),Re.resolve()}},{key:"markPotentiallyOrphaned",value:function(e,t){return this.Us.add(t.toString()),Re.resolve()}},{key:"removeTarget",value:function(e,t){var n=this;this.Bs.ds(t.targetId).forEach(function(e){return n.Us.add(e.toString())});var r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(function(e){e.forEach(function(e){return n.Us.add(e.toString())})}).next(function(){return r.removeTargetData(e,t)})}},{key:"Ms",value:function(){this.Ls=new Set}},{key:"Os",value:function(e){var t=this,n=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Re.forEach(this.Us,function(r){var i=we.fromPath(r);return t.Ks(e,i).next(function(e){e||n.removeEntry(i,ye.min())})}).next(function(){return t.Ls=null,n.apply(e)})}},{key:"updateLimboDocument",value:function(e,t){var n=this;return this.Ks(e,t).next(function(e){e?n.Us.delete(t.toString()):n.Us.add(t.toString())})}},{key:"ks",value:function(e){return 0}},{key:"Ks",value:function(e,t){var n=this;return Re.or([function(){return Re.resolve(n.Bs.containsKey(t))},function(){return n.persistence.getTargetCache().containsKey(e,t)},function(){return n.persistence.Fs(e,t)}])}}],[{key:"qs",value:function(t){return new e(t)}}]),e}(),zu=function(){function e(t){P(this,e),this.Tt=t}return L(e,[{key:"F",value:function(e,t,n,r){var i=this,a=new Me("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Mi,{unique:!0}),e.createObjectStore("documentMutations")}(e),Wu(e),function(e){e.createObjectStore("remoteDocuments")}(e));var u=Re.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),Wu(e)),u=u.next(function(){return e=a.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ye.min().toTimestamp(),targetCount:0},e.put("targetGlobalKey",t);var e,t})),n<4&&r>=4&&(0!==n&&(u=u.next(function(){return function(e,t){return t.store("mutations").W().next(function(n){e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Mi,{unique:!0});var r=t.store("mutations"),i=n.map(function(e){return r.put(e)});return Re.waitFor(i)})}(e,a)})),u=u.next(function(){!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)})),n<5&&r>=5&&(u=u.next(function(){return i.Gs(a)})),n<6&&r>=6&&(u=u.next(function(){return function(e){e.createObjectStore("remoteDocumentGlobal")}(e),i.Qs(a)})),n<7&&r>=7&&(u=u.next(function(){return i.js(a)})),n<8&&r>=8&&(u=u.next(function(){return i.zs(e,a)})),n<9&&r>=9&&(u=u.next(function(){!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)})),n<10&&r>=10&&(u=u.next(function(){return i.Ws(a)})),n<11&&r>=11&&(u=u.next(function(){!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)})),n<12&&r>=12&&(u=u.next(function(){!function(e){var t=e.createObjectStore("documentOverlays",{keyPath:Ji});t.createIndex("collectionPathOverlayIndex",Zi,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",$i,{unique:!1})}(e)})),n<13&&r>=13&&(u=u.next(function(){return function(e){var t=e.createObjectStore("remoteDocumentsV14",{keyPath:Ui});t.createIndex("documentKeyIndex",Bi),t.createIndex("collectionGroupIndex",Ki)}(e)}).next(function(){return i.Hs(e,a)}).next(function(){return e.deleteObjectStore("remoteDocuments")})),n<14&&r>=14&&(u=u.next(function(){return i.Js(e,a)})),n<15&&r>=15&&(u=u.next(function(){return function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Wi}).createIndex("sequenceNumberIndex",Hi,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Xi}).createIndex("documentKeyIndex",Yi,{unique:!1})}(e)})),u}},{key:"Qs",value:function(e){var t=0;return e.store("remoteDocuments").X(function(e,n){t+=ou(n)}).next(function(){var n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)})}},{key:"Gs",value:function(e){var t=this,n=e.store("mutationQueues"),r=e.store("mutations");return n.W().next(function(n){return Re.forEach(n,function(n){var i=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return r.W("userMutationsIndex",i).next(function(r){return Re.forEach(r,function(r){H(r.userId===n.userId);var i=ma(t.Tt,r);return uu(e,n.userId,i).next(function(){})})})})})}},{key:"js",value:function(e){var t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(function(e){var r=[];return n.X(function(n,i){var a=new me(n),u=[0,Pi(a)];r.push(t.get(u).next(function(n){return n?Re.resolve():function(n){return t.put({targetId:0,path:Pi(n),sequenceNumber:e.highestListenSequenceNumber})}(a)}))}).next(function(){return Re.waitFor(r)})})}},{key:"zs",value:function(e,t){e.createObjectStore("collectionParents",{keyPath:zi});var n=t.store("collectionParents"),r=new Ya,i=function(e){if(r.add(e)){var t=e.lastSegment(),i=e.popLast();return n.put({collectionId:t,parent:Pi(i)})}};return t.store("remoteDocuments").X({Z:!0},function(e,t){var n=new me(e);return i(n.popLast())}).next(function(){return t.store("documentMutations").X({Z:!0},function(e,t){var n=c(e,3),r=(n[0],n[1]),a=(n[2],Ri(r));return i(a.popLast())})})}},{key:"Ws",value:function(e){var t=this,n=e.store("targets");return n.X(function(e,r){var i=ga(r),a=ka(t.Tt,i);return n.put(a)})}},{key:"Hs",value:function(e,t){var n=t.store("remoteDocuments"),r=[];return n.X(function(e,n){var i,a=t.store("remoteDocumentsV14"),u=(i=n,i.document?new we(me.fromString(i.document.name).popFirst(5)):i.noDocument?we.fromSegments(i.noDocument.path):i.unknownDocument?we.fromSegments(i.unknownDocument.path):W()).path.toArray(),o={prefixPath:u.slice(0,u.length-2),collectionGroup:u[u.length-2],documentId:u[u.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(a.put(o))}).next(function(){return Re.waitFor(r)})}},{key:"Js",value:function(e,t){var n=this,r=t.store("mutations"),i=Su(this.Tt),a=new Gu(ju.qs,this.Tt.oe);return r.W().next(function(e){var r=new Map;return e.forEach(function(e){var t,i=null!==(t=r.get(e.userId))&&void 0!==t?t:Vr();ma(n.Tt,e).keys().forEach(function(e){return i=i.add(e)}),r.set(e.userId,i)}),Re.forEach(r,function(e,r){var u=new V(r),o=_a.ue(n.Tt,u),s=a.getIndexManager(u),c=su.ue(u,n.Tt,s,a.referenceDelegate);return new Lu(i,c,o,s).recalculateAndSaveOverlaysForDocumentKeys(new aa(t,We.at),e).next()})})}}]),e}();function Wu(e){e.createObjectStore("targetDocuments",{keyPath:Qi}).createIndex("documentTargetsIndex",ji,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Gi,{unique:!0}),e.createObjectStore("targetGlobal")}var Hu="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.",Xu=function(){function e(t,n,r,i,a,u,o,s,c,l){var f=arguments.length>10&&void 0!==arguments[10]?arguments[10]:15;if(P(this,e),this.allowTabSynchronization=t,this.persistenceKey=n,this.clientId=r,this.Ys=a,this.window=u,this.document=o,this.Zs=c,this.Xs=l,this.ti=f,this.Cs=null,this.xs=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ei=null,this.inForeground=!1,this.ni=null,this.si=null,this.ii=Number.NEGATIVE_INFINITY,this.ri=function(e){return Promise.resolve()},!e.C())throw new Z(J.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new bu(this,i),this.oi=n+"main",this.Tt=new fa(s),this.ui=new Oe(this.oi,this.ti,new zu(this.Tt)),this.Ns=new vu(this.referenceDelegate,this.Tt),this.remoteDocumentCache=Su(this.Tt),this.$s=new Ta,this.window&&this.window.localStorage?this.ci=this.window.localStorage:(this.ci=null,!1===l&&Q("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}return L(e,[{key:"start",value:function(){var e=this;return this.ai().then(function(){if(!e.isPrimary&&!e.allowTabSynchronization)throw new Z(J.FAILED_PRECONDITION,Hu);return e.hi(),e.li(),e.fi(),e.runTransaction("getHighestListenSequenceNumber","readonly",function(t){return e.Ns.getHighestSequenceNumber(t)})}).then(function(t){e.Cs=new We(t,e.Zs)}).then(function(){e.xs=!0}).catch(function(t){return e.ui&&e.ui.close(),Promise.reject(t)})}},{key:"di",value:function(e){var t=this;return this.ri=function(n){return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(!t.started){r.next=2;break}return r.abrupt("return",e(n));case 2:case"end":return r.stop()}},null,null,null,Promise)},e(this.isPrimary)}},{key:"setDatabaseDeletedListener",value:function(e){this.ui.L(function(t){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=null===t.newVersion,!n.t0){n.next=4;break}return n.next=4,m().awrap(e());case 4:case"end":return n.stop()}},null,null,null,Promise)})}},{key:"setNetworkEnabled",value:function(e){var t=this;this.networkEnabled!==e&&(this.networkEnabled=e,this.Ys.enqueueAndForget(function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=t.started,!e.t0){e.next=4;break}return e.next=4,m().awrap(t.ai());case 4:case"end":return e.stop()}},null,null,null,Promise)}))}},{key:"ai",value:function(){var e=this;return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",function(t){return Ju(t).put({clientId:e.clientId,updateTimeMs:Date.now(),networkEnabled:e.networkEnabled,inForeground:e.inForeground}).next(function(){if(e.isPrimary)return e._i(t).next(function(t){t||(e.isPrimary=!1,e.Ys.enqueueRetryable(function(){return e.ri(!1)}))})}).next(function(){return e.wi(t)}).next(function(n){return e.isPrimary&&!n?e.mi(t).next(function(){return!1}):!!n&&e.gi(t).next(function(){return!0})})}).catch(function(t){if(Ue(t))return G("IndexedDbPersistence","Failed to extend owner lease: ",t),e.isPrimary;if(!e.allowTabSynchronization)throw t;return G("IndexedDbPersistence","Releasing owner lease after error during lease refresh",t),!1}).then(function(t){e.isPrimary!==t&&e.Ys.enqueueRetryable(function(){return e.ri(t)}),e.isPrimary=t})}},{key:"_i",value:function(e){var t=this;return Yu(e).get("owner").next(function(e){return Re.resolve(t.yi(e))})}},{key:"pi",value:function(e){return Ju(e).delete(this.clientId)}},{key:"Ii",value:function(){var e,t,n,r,i=this;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:if(!this.isPrimary||this.Ti(this.ii,18e5)){a.next=6;break}return this.ii=Date.now(),a.next=4,m().awrap(this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(e){var t=ua(e,"clientMetadata");return t.W().next(function(e){var n=i.Ei(e,18e5),r=e.filter(function(e){return-1===n.indexOf(e)});return Re.forEach(r,function(e){return t.delete(e.clientId)}).next(function(){return r})})}).catch(function(){return[]}));case 4:if(e=a.sent,this.ci){t=p(e);try{for(t.s();!(n=t.n()).done;)r=n.value,this.ci.removeItem(this.Ai(r.clientId))}catch(u){t.e(u)}finally{t.f()}}case 6:case"end":return a.stop()}},null,this,null,Promise)}},{key:"fi",value:function(){var e=this;this.si=this.Ys.enqueueAfterDelay("client_metadata_refresh",4e3,function(){return e.ai().then(function(){return e.Ii()}).then(function(){return e.fi()})})}},{key:"yi",value:function(e){return!!e&&e.ownerId===this.clientId}},{key:"wi",value:function(e){var t=this;return this.Xs?Re.resolve(!0):Yu(e).get("owner").next(function(n){if(null!==n&&t.Ti(n.leaseTimestampMs,5e3)&&!t.Ri(n.ownerId)){if(t.yi(n)&&t.networkEnabled)return!0;if(!t.yi(n)){if(!n.allowTabSynchronization)throw new Z(J.FAILED_PRECONDITION,Hu);return!1}}return!(!t.networkEnabled||!t.inForeground)||Ju(e).W().next(function(e){return void 0===t.Ei(e,5e3).find(function(e){if(t.clientId!==e.clientId){var n=!t.networkEnabled&&e.networkEnabled,r=!t.inForeground&&e.inForeground,i=t.networkEnabled===e.networkEnabled;if(n||r&&i)return!0}return!1})})}).next(function(e){return t.isPrimary!==e&&G("IndexedDbPersistence","Client ".concat(e?"is":"is not"," eligible for a primary lease.")),e})}},{key:"shutdown",value:function(){var e=this;return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return this.xs=!1,this.Pi(),this.si&&(this.si.cancel(),this.si=null),this.vi(),this.bi(),t.next=7,m().awrap(this.ui.runTransaction("shutdown","readwrite",["owner","clientMetadata"],function(t){var n=new aa(t,We.at);return e.mi(n).next(function(){return e.pi(n)})}));case 7:this.ui.close(),this.Vi();case 9:case"end":return t.stop()}},null,this,null,Promise)}},{key:"Ei",value:function(e,t){var n=this;return e.filter(function(e){return n.Ti(e.updateTimeMs,t)&&!n.Ri(e.clientId)})}},{key:"Si",value:function(){var e=this;return this.runTransaction("getActiveClients","readonly",function(t){return Ju(t).W().next(function(t){return e.Ei(t,18e5).map(function(e){return e.clientId})})})}},{key:"started",get:function(){return this.xs}},{key:"getMutationQueue",value:function(e,t){return su.ue(e,this.Tt,t,this.referenceDelegate)}},{key:"getTargetCache",value:function(){return this.Ns}},{key:"getRemoteDocumentCache",value:function(){return this.remoteDocumentCache}},{key:"getIndexManager",value:function(e){return new Za(e,this.Tt.oe.databaseId)}},{key:"getDocumentOverlayCache",value:function(e){return _a.ue(this.Tt,e)}},{key:"getBundleCache",value:function(){return this.$s}},{key:"runTransaction",value:function(e,t,n){var r=this;G("IndexedDbPersistence","Starting transaction:",e);var i,a,u="readonly"===t?"readonly":"readwrite",o=15===(i=this.ti)?ia:14===i?ra:13===i?na:12===i?ta:11===i?ea:void W();return this.ui.runTransaction(e,u,o,function(i){return a=new aa(i,r.Cs?r.Cs.next():We.at),"readwrite-primary"===t?r._i(a).next(function(e){return!!e||r.wi(a)}).next(function(t){if(!t)throw Q("Failed to obtain primary lease for action '".concat(e,"'.")),r.isPrimary=!1,r.Ys.enqueueRetryable(function(){return r.ri(!1)}),new Z(J.FAILED_PRECONDITION,Pe);return n(a)}).next(function(e){return r.gi(a).next(function(){return e})}):r.Di(a).next(function(){return n(a)})}).then(function(e){return a.raiseOnCommittedEvent(),e})}},{key:"Di",value:function(e){var t=this;return Yu(e).get("owner").next(function(e){if(null!==e&&t.Ti(e.leaseTimestampMs,5e3)&&!t.Ri(e.ownerId)&&!t.yi(e)&&!(t.Xs||t.allowTabSynchronization&&e.allowTabSynchronization))throw new Z(J.FAILED_PRECONDITION,Hu)})}},{key:"gi",value:function(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Yu(e).put("owner",t)}},{key:"mi",value:function(e){var t=this,n=Yu(e);return n.get("owner").next(function(e){return t.yi(e)?(G("IndexedDbPersistence","Releasing primary lease."),n.delete("owner")):Re.resolve()})}},{key:"Ti",value:function(e,t){var n=Date.now();return!(e<n-t||e>n&&(Q("Detected an update time that is in the future: ".concat(e," > ").concat(n)),1))}},{key:"hi",value:function(){var e=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ni=function(){e.Ys.enqueueAndForget(function(){return e.inForeground="visible"===e.document.visibilityState,e.ai()})},this.document.addEventListener("visibilitychange",this.ni),this.inForeground="visible"===this.document.visibilityState)}},{key:"vi",value:function(){this.ni&&(this.document.removeEventListener("visibilitychange",this.ni),this.ni=null)}},{key:"li",value:function(){var e,t=this;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ei=function(){t.Pi();var e=/(?:Version|Mobile)\/1[456]/;(0,a.isSafari)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&t.Ys.enterRestrictedMode(!0),t.Ys.enqueueAndForget(function(){return t.shutdown()})},this.window.addEventListener("pagehide",this.ei))}},{key:"bi",value:function(){this.ei&&(this.window.removeEventListener("pagehide",this.ei),this.ei=null)}},{key:"Ri",value:function(e){var t;try{var n=null!==(null===(t=this.ci)||void 0===t?void 0:t.getItem(this.Ai(e)));return G("IndexedDbPersistence","Client '".concat(e,"' ").concat(n?"is":"is not"," zombied in LocalStorage")),n}catch(e){return Q("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}},{key:"Pi",value:function(){if(this.ci)try{this.ci.setItem(this.Ai(this.clientId),String(Date.now()))}catch(e){Q("Failed to set zombie client id.",e)}}},{key:"Vi",value:function(){if(this.ci)try{this.ci.removeItem(this.Ai(this.clientId))}catch(e){}}},{key:"Ai",value:function(e){return"firestore_zombie_".concat(this.persistenceKey,"_").concat(e)}}],[{key:"C",value:function(){return Oe.C()}}]),e}();function Yu(e){return ua(e,"owner")}function Ju(e){return ua(e,"clientMetadata")}function Zu(e,t){var n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}var $u=function(){function e(t,n,r,i){P(this,e),this.targetId=t,this.fromCache=n,this.Ci=r,this.xi=i}return L(e,null,[{key:"Ni",value:function(t,n){var r,i=Vr(),a=Vr(),u=p(n.docChanges);try{for(u.s();!(r=u.n()).done;){var o=r.value;switch(o.type){case 0:i=i.add(o.doc.key);break;case 1:a=a.add(o.doc.key)}}}catch(s){u.e(s)}finally{u.f()}return new e(t,n.fromCache,i,a)}}]),e}(),eo=function(){function e(){P(this,e),this.ki=!1}return L(e,[{key:"initialize",value:function(e,t){this.$i=e,this.indexManager=t,this.ki=!0}},{key:"getDocumentsMatchingQuery",value:function(e,t,n,r){var i=this;return this.Mi(e,t).next(function(a){return a||i.Oi(e,t,r,n)}).next(function(n){return n||i.Fi(e,t)})}},{key:"Mi",value:function(e,t){var n=this;if(An(t))return Re.resolve(null);var r=Fn(t);return this.indexManager.getIndexType(e,r).next(function(i){return 0===i?null:(null!==t.limit&&1===i&&(t=Rn(t,null,"F"),r=Fn(t)),n.indexManager.getDocumentsMatchingTarget(e,r).next(function(i){var a=Vr.apply(void 0,E(i));return n.$i.getDocuments(e,a).next(function(i){return n.indexManager.getMinOffset(e,r).next(function(r){var u=n.Bi(t,i);return n.Li(t,u,a,r.readTime)?n.Mi(e,Rn(t,null,"F")):n.qi(e,u,t,r)})})}))})}},{key:"Oi",value:function(e,t,n,r){var a=this;return An(t)||r.isEqual(ye.min())?this.Fi(e,t):this.$i.getDocuments(e,n).next(function(u){var o=a.Bi(t,u);return a.Li(t,o,n,r)?a.Fi(e,t):(B()<=i.LogLevel.DEBUG&&G("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Vn(t)),a.qi(e,o,t,Ae(r,-1)))})}},{key:"Bi",value:function(e,t){var n=new ln(Bn(e));return t.forEach(function(t,r){qn(e,r)&&(n=n.add(r))}),n}},{key:"Li",value:function(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;var i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}},{key:"Fi",value:function(e,t){return B()<=i.LogLevel.DEBUG&&G("QueryEngine","Using full collection scan to execute query:",Vn(t)),this.$i.getDocumentsMatchingQuery(e,t,Ne.min())}},{key:"qi",value:function(e,t,n,r){return this.$i.getDocumentsMatchingQuery(e,n,r).next(function(e){return t.forEach(function(t){e=e.insert(t.key,t)}),e})}}]),e}(),to=function(){function e(t,n,r,i){P(this,e),this.persistence=t,this.Ui=n,this.Tt=i,this.Ki=new on(fe),this.Gi=new _r(function(e){return kn(e)},wn),this.Qi=new Map,this.ji=t.getRemoteDocumentCache(),this.Ns=t.getTargetCache(),this.$s=t.getBundleCache(),this.zi(r)}return L(e,[{key:"zi",value:function(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Lu(this.ji,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ji.setIndexManager(this.indexManager),this.Ui.initialize(this.localDocuments,this.indexManager)}},{key:"collectGarbage",value:function(e){var t=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",function(n){return e.collect(n,t.Ki)})}}]),e}();function no(e,t,n,r){return new to(e,t,n,r)}function ro(e,t){var n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return n=Y(e),r.next=3,m().awrap(n.persistence.runTransaction("Handle user change","readonly",function(e){var r;return n.mutationQueue.getAllMutationBatches(e).next(function(i){return r=i,n.zi(t),n.mutationQueue.getAllMutationBatches(e)}).next(function(t){var i,a=[],u=[],o=Vr(),s=p(r);try{for(s.s();!(i=s.n()).done;){var c=i.value;a.push(c.batchId);var l,f=p(c.mutations);try{for(f.s();!(l=f.n()).done;){var h=l.value;o=o.add(h.key)}}catch(w){f.e(w)}finally{f.f()}}}catch(w){s.e(w)}finally{s.f()}var d,v=p(t);try{for(v.s();!(d=v.n()).done;){var y=d.value;u.push(y.batchId);var m,g=p(y.mutations);try{for(g.s();!(m=g.n()).done;){var k=m.value;o=o.add(k.key)}}catch(w){g.e(w)}finally{g.f()}}}catch(w){v.e(w)}finally{v.f()}return n.localDocuments.getDocuments(e,o).next(function(e){return{Wi:e,removedBatchIds:a,addedBatchIds:u}})})}));case 3:return r.abrupt("return",r.sent);case 4:case"end":return r.stop()}},null,null,null,Promise)}function io(e,t){var n=Y(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",function(e){var r=t.batch.keys(),i=n.ji.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){var i=n.batch,a=i.keys(),u=Re.resolve();return a.forEach(function(e){u=u.next(function(){return r.getEntry(t,e)}).next(function(t){var a=n.docVersions.get(e);H(null!==a),t.version.compareTo(a)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),u.next(function(){return e.mutationQueue.removeMutationBatch(t,i)})}(n,e,t,i).next(function(){return i.apply(e)}).next(function(){return n.mutationQueue.performConsistencyCheck(e)}).next(function(){return n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)}).next(function(){return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){for(var t=Vr(),n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))}).next(function(){return n.localDocuments.getDocuments(e,r)})})}function ao(e){var t=Y(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",function(e){return t.Ns.getLastRemoteSnapshotVersion(e)})}function uo(e,t){var n=Y(e),r=t.snapshotVersion,i=n.Ki;return n.persistence.runTransaction("Apply remote event","readwrite-primary",function(e){var a=n.ji.newChangeBuffer({trackRemovals:!0});i=n.Ki;var u=[];t.targetChanges.forEach(function(a,o){var s=i.get(o);if(s){u.push(n.Ns.removeMatchingKeys(e,a.removedDocuments,o).next(function(){return n.Ns.addMatchingKeys(e,a.addedDocuments,o)}));var c=s.withSequenceNumber(e.currentSequenceNumber);t.targetMismatches.has(o)?c=c.withResumeToken(ot.EMPTY_BYTE_STRING,ye.min()).withLastLimboFreeSnapshotVersion(ye.min()):a.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(a.resumeToken,r)),i=i.insert(o,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||(t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0)}(s,c,a)&&u.push(n.Ns.updateTargetData(e,c))}});var o=Dr(),s=Vr();if(t.documentUpdates.forEach(function(r){t.resolvedLimboDocuments.has(r)&&u.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))}),u.push(oo(e,a,t.documentUpdates).next(function(e){o=e.Hi,s=e.Ji})),!r.isEqual(ye.min())){var c=n.Ns.getLastRemoteSnapshotVersion(e).next(function(t){return n.Ns.setTargetsMetadata(e,e.currentSequenceNumber,r)});u.push(c)}return Re.waitFor(u).next(function(){return a.apply(e)}).next(function(){return n.localDocuments.getLocalViewOfDocuments(e,o,s)}).next(function(){return o})}).then(function(e){return n.Ki=i,e})}function oo(e,t,n){var r=Vr(),i=Vr();return n.forEach(function(e){return r=r.add(e)}),t.getEntries(e,r).next(function(e){var r=Dr();return n.forEach(function(n,a){var u=e.get(n);a.isFoundDocument()!==u.isFoundDocument()&&(i=i.add(n)),a.isNoDocument()&&a.version.isEqual(ye.min())?(t.removeEntry(n,a.readTime),r=r.insert(n,a)):!u.isValidDocument()||a.version.compareTo(u.version)>0||0===a.version.compareTo(u.version)&&u.hasPendingWrites?(t.addEntry(a),r=r.insert(n,a)):G("LocalStore","Ignoring outdated watch update for ",n,". Current version:",u.version," Watch version:",a.version)}),{Hi:r,Ji:i}})}function so(e,t){var n=Y(e);return n.persistence.runTransaction("Get next mutation batch","readonly",function(e){return void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)})}function co(e,t){var n=Y(e);return n.persistence.runTransaction("Allocate target","readwrite",function(e){var r;return n.Ns.getTargetData(e,t).next(function(i){return i?(r=i,Re.resolve(r)):n.Ns.allocateTargetId(e).next(function(i){return r=new la(t,i,0,e.currentSequenceNumber),n.Ns.addTargetData(e,r).next(function(){return r})})})}).then(function(e){var r=n.Ki.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.Ki=n.Ki.insert(e.targetId,e),n.Gi.set(t,e.targetId)),e})}function lo(e,t,n){var r,i,a;return m().async(function(u){for(;;)switch(u.prev=u.next){case 0:if(r=Y(e),i=r.Ki.get(t),a=n?"readwrite":"readwrite-primary",u.prev=1,u.t0=n,u.t0){u.next=6;break}return u.next=6,m().awrap(r.persistence.runTransaction("Release target",a,function(e){return r.persistence.referenceDelegate.removeTarget(e,i)}));case 6:u.next=13;break;case 8:if(u.prev=8,u.t1=u.catch(1),Ue(u.t1)){u.next=12;break}throw u.t1;case 12:G("LocalStore","Failed to update sequence numbers for target ".concat(t,": ").concat(u.t1));case 13:r.Ki=r.Ki.remove(t),r.Gi.delete(i.target);case 14:case"end":return u.stop()}},null,null,[[1,8]],Promise)}function fo(e,t,n){var r=Y(e),i=ye.min(),a=Vr();return r.persistence.runTransaction("Execute query","readonly",function(e){return function(e,t,n){var r=Y(e),i=r.Gi.get(n);return void 0!==i?Re.resolve(r.Ki.get(i)):r.Ns.getTargetData(t,n)}(r,e,Fn(t)).next(function(t){if(t)return i=t.lastLimboFreeSnapshotVersion,r.Ns.getMatchingKeysForTargetId(e,t.targetId).next(function(e){a=e})}).next(function(){return r.Ui.getDocumentsMatchingQuery(e,t,n?i:ye.min(),n?a:Vr())}).next(function(e){return yo(r,Un(t),e),{documents:e,Yi:a}})})}function ho(e,t){var n=Y(e),r=Y(n.Ns),i=n.Ki.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",function(e){return r.ie(e,t).next(function(e){return e?e.target:null})})}function vo(e,t){var n=Y(e),r=n.Qi.get(t)||ye.min();return n.persistence.runTransaction("Get new document changes","readonly",function(e){return n.ji.getAllFromCollectionGroup(e,t,Ae(r,-1),Number.MAX_SAFE_INTEGER)}).then(function(e){return yo(n,t,e),e})}function yo(e,t,n){var r=e.Qi.get(t)||ye.min();n.forEach(function(e,t){t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.Qi.set(t,r)}function po(e,t,n,r){var i,a,u,o,s,c,l,f,h,d;return m().async(function(v){for(;;)switch(v.prev=v.next){case 0:i=Y(e),a=Vr(),u=Dr(),o=p(n);try{for(o.s();!(s=o.n()).done;)c=s.value,l=t.Zi(c.metadata.name),c.document&&(a=a.add(l)),(f=t.Xi(c)).setReadTime(t.tr(c.metadata.readTime)),u=u.insert(l,f)}catch(y){o.e(y)}finally{o.f()}return h=i.ji.newChangeBuffer({trackRemovals:!0}),v.next=7,m().awrap(co(i,function(e){return Fn(_n(me.fromString("__bundle__/docs/".concat(e))))}(r)));case 7:return d=v.sent,v.abrupt("return",i.persistence.runTransaction("Apply bundle documents","readwrite",function(e){return oo(e,h,u).next(function(t){return h.apply(e),t}).next(function(t){return i.Ns.removeMatchingKeysForTargetId(e,d.targetId).next(function(){return i.Ns.addMatchingKeys(e,a,d.targetId)}).next(function(){return i.localDocuments.getLocalViewOfDocuments(e,t.Hi,t.Ji)}).next(function(){return t.Hi})})}));case 9:case"end":return v.stop()}},null,null,null,Promise)}function mo(e,t){var n,r,i,a=arguments;return m().async(function(u){for(;;)switch(u.prev=u.next){case 0:return n=a.length>2&&void 0!==a[2]?a[2]:Vr(),u.next=3,m().awrap(co(e,Fn(wa(t.bundledQuery))));case 3:return r=u.sent,i=Y(e),u.abrupt("return",i.persistence.runTransaction("Save named query","readwrite",function(e){var a=ri(t.readTime);if(r.snapshotVersion.compareTo(a)>=0)return i.$s.saveNamedQuery(e,t);var u=r.withResumeToken(ot.EMPTY_BYTE_STRING,a);return i.Ki=i.Ki.insert(u.targetId,u),i.Ns.updateTargetData(e,u).next(function(){return i.Ns.removeMatchingKeysForTargetId(e,r.targetId)}).next(function(){return i.Ns.addMatchingKeys(e,n,r.targetId)}).next(function(){return i.$s.saveNamedQuery(e,t)})}));case 6:case"end":return u.stop()}},null,null,null,Promise)}function go(e,t){return"firestore_clients_".concat(e,"_").concat(t)}function ko(e,t,n){var r="firestore_mutations_".concat(e,"_").concat(n);return t.isAuthenticated()&&(r+="_".concat(t.uid)),r}function wo(e,t){return"firestore_targets_".concat(e,"_").concat(t)}var xo=function(){function e(t,n,r,i){P(this,e),this.user=t,this.batchId=n,this.state=r,this.error=i}return L(e,[{key:"nr",value:function(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}],[{key:"er",value:function(t,n,r){var i,a=JSON.parse(r),u="object"==C(a)&&-1!==["pending","acknowledged","rejected"].indexOf(a.state)&&(void 0===a.error||"object"==C(a.error));return u&&a.error&&((u="string"==typeof a.error.message&&"string"==typeof a.error.code)&&(i=new Z(a.error.code,a.error.message))),u?new e(t,n,a.state,i):(Q("SharedClientState","Failed to parse mutation state for ID '".concat(n,"': ").concat(r)),null)}}]),e}(),bo=function(){function e(t,n,r){P(this,e),this.targetId=t,this.state=n,this.error=r}return L(e,[{key:"nr",value:function(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}],[{key:"er",value:function(t,n){var r,i=JSON.parse(n),a="object"==C(i)&&-1!==["not-current","current","rejected"].indexOf(i.state)&&(void 0===i.error||"object"==C(i.error));return a&&i.error&&((a="string"==typeof i.error.message&&"string"==typeof i.error.code)&&(r=new Z(i.error.code,i.error.message))),a?new e(t,i.state,r):(Q("SharedClientState","Failed to parse target state for ID '".concat(t,"': ").concat(n)),null)}}]),e}(),Io=function(){function e(t,n){P(this,e),this.clientId=t,this.activeTargetIds=n}return L(e,null,[{key:"er",value:function(t,n){for(var r=JSON.parse(n),i="object"==C(r)&&r.activeTargetIds instanceof Array,a=Ur(),u=0;i&&u<r.activeTargetIds.length;++u)i=it(r.activeTargetIds[u]),a=a.add(r.activeTargetIds[u]);return i?new e(t,a):(Q("SharedClientState","Failed to parse client data for instance '".concat(t,"': ").concat(n)),null)}}]),e}(),To=function(){function e(t,n){P(this,e),this.clientId=t,this.onlineState=n}return L(e,null,[{key:"er",value:function(t){var n=JSON.parse(t);return"object"==C(n)&&-1!==["Unknown","Online","Offline"].indexOf(n.onlineState)&&"string"==typeof n.clientId?new e(n.clientId,n.onlineState):(Q("SharedClientState","Failed to parse online state: ".concat(t)),null)}}]),e}(),Eo=function(){function e(){P(this,e),this.activeTargetIds=Ur()}return L(e,[{key:"sr",value:function(e){this.activeTargetIds=this.activeTargetIds.add(e)}},{key:"ir",value:function(e){this.activeTargetIds=this.activeTargetIds.delete(e)}},{key:"nr",value:function(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}]),e}(),So=function(){function e(t,n,r,i,a){P(this,e),this.window=t,this.Ys=n,this.persistenceKey=r,this.rr=i,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ur=this.cr.bind(this),this.ar=new on(fe),this.started=!1,this.hr=[];var u=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=a,this.lr=go(this.persistenceKey,this.rr),this.dr=function(e){return"firestore_sequence_number_".concat(e)}(this.persistenceKey),this.ar=this.ar.insert(this.rr,new Eo),this._r=new RegExp("^firestore_clients_".concat(u,"_([^_]*)$")),this.wr=new RegExp("^firestore_mutations_".concat(u,"_(\\d+)(?:_(.*))?$")),this.mr=new RegExp("^firestore_targets_".concat(u,"_(\\d+)$")),this.gr=function(e){return"firestore_online_state_".concat(e)}(this.persistenceKey),this.yr=function(e){return"firestore_bundle_loaded_v2_".concat(e)}(this.persistenceKey),this.window.addEventListener("storage",this.ur)}return L(e,[{key:"start",value:function(){var e,t,n,r,i,a,u,o,s,c,l,f=this;return m().async(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,m().awrap(this.syncEngine.Si());case 2:e=h.sent,t=p(e),h.prev=4,t.s();case 6:if((n=t.n()).done){h.next=14;break}if((r=n.value)!==this.rr){h.next=10;break}return h.abrupt("continue",12);case 10:(i=this.getItem(go(this.persistenceKey,r)))&&(a=Io.er(r,i))&&(this.ar=this.ar.insert(a.clientId,a));case 12:h.next=6;break;case 14:h.next=19;break;case 16:h.prev=16,h.t0=h.catch(4),t.e(h.t0);case 19:return h.prev=19,t.f(),h.finish(19);case 22:this.pr(),(u=this.storage.getItem(this.gr))&&(o=this.Ir(u))&&this.Tr(o),s=p(this.hr);try{for(s.s();!(c=s.n()).done;)l=c.value,this.cr(l)}catch(d){s.e(d)}finally{s.f()}this.hr=[],this.window.addEventListener("pagehide",function(){return f.shutdown()}),this.started=!0;case 28:case"end":return h.stop()}},null,this,[[4,16,19,22]],Promise)}},{key:"writeSequenceNumber",value:function(e){this.setItem(this.dr,JSON.stringify(e))}},{key:"getAllActiveQueryTargets",value:function(){return this.Er(this.ar)}},{key:"isActiveQueryTarget",value:function(e){var t=!1;return this.ar.forEach(function(n,r){r.activeTargetIds.has(e)&&(t=!0)}),t}},{key:"addPendingMutation",value:function(e){this.Ar(e,"pending")}},{key:"updateMutationState",value:function(e,t,n){this.Ar(e,t,n),this.Rr(e)}},{key:"addLocalQueryTarget",value:function(e){var t="not-current";if(this.isActiveQueryTarget(e)){var n=this.storage.getItem(wo(this.persistenceKey,e));if(n){var r=bo.er(e,n);r&&(t=r.state)}}return this.Pr.sr(e),this.pr(),t}},{key:"removeLocalQueryTarget",value:function(e){this.Pr.ir(e),this.pr()}},{key:"isLocalQueryTarget",value:function(e){return this.Pr.activeTargetIds.has(e)}},{key:"clearQueryState",value:function(e){this.removeItem(wo(this.persistenceKey,e))}},{key:"updateQueryState",value:function(e,t,n){this.vr(e,t,n)}},{key:"handleUserChange",value:function(e,t,n){var r=this;t.forEach(function(e){r.Rr(e)}),this.currentUser=e,n.forEach(function(e){r.addPendingMutation(e)})}},{key:"setOnlineState",value:function(e){this.br(e)}},{key:"notifyBundleLoaded",value:function(e){this.Vr(e)}},{key:"shutdown",value:function(){this.started&&(this.window.removeEventListener("storage",this.ur),this.removeItem(this.lr),this.started=!1)}},{key:"getItem",value:function(e){var t=this.storage.getItem(e);return G("SharedClientState","READ",e,t),t}},{key:"setItem",value:function(e,t){G("SharedClientState","SET",e,t),this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){G("SharedClientState","REMOVE",e),this.storage.removeItem(e)}},{key:"cr",value:function(e){var t=this,n=e;if(n.storageArea===this.storage){if(G("SharedClientState","EVENT",n.key,n.newValue),n.key===this.lr)return void Q("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Ys.enqueueRetryable(function(){var e,r,i,a,u,o,s;return m().async(function(c){for(;;)switch(c.prev=c.next){case 0:if(!t.started){c.next=43;break}if(null===n.key){c.next=41;break}if(!t._r.test(n.key)){c.next=11;break}if(null!=n.newValue){c.next=6;break}return e=t.Sr(n.key),c.abrupt("return",t.Dr(e,null));case 6:if(!(r=t.Cr(n.key,n.newValue))){c.next=9;break}return c.abrupt("return",t.Dr(r.clientId,r));case 9:c.next=41;break;case 11:if(!t.wr.test(n.key)){c.next=18;break}if(null===n.newValue){c.next=16;break}if(!(i=t.Nr(n.key,n.newValue))){c.next=16;break}return c.abrupt("return",t.kr(i));case 16:c.next=41;break;case 18:if(!t.mr.test(n.key)){c.next=25;break}if(null===n.newValue){c.next=23;break}if(!(a=t.$r(n.key,n.newValue))){c.next=23;break}return c.abrupt("return",t.Mr(a));case 23:c.next=41;break;case 25:if(n.key!==t.gr){c.next=32;break}if(null===n.newValue){c.next=30;break}if(!(u=t.Ir(n.newValue))){c.next=30;break}return c.abrupt("return",t.Tr(u));case 30:c.next=41;break;case 32:if(n.key!==t.dr){c.next=37;break}(o=function(e){var t=We.at;if(null!=e)try{var n=JSON.parse(e);H("number"==typeof n),t=n}catch(e){Q("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(n.newValue))!==We.at&&t.sequenceNumberHandler(o),c.next=41;break;case 37:if(n.key!==t.yr){c.next=41;break}return s=t.Or(n.newValue),c.next=41,m().awrap(Promise.all(s.map(function(e){return t.syncEngine.Fr(e)})));case 41:c.next=44;break;case 43:t.hr.push(n);case 44:case"end":return c.stop()}},null,null,null,Promise)})}}},{key:"Pr",get:function(){return this.ar.get(this.rr)}},{key:"pr",value:function(){this.setItem(this.lr,this.Pr.nr())}},{key:"Ar",value:function(e,t,n){var r=new xo(this.currentUser,e,t,n),i=ko(this.persistenceKey,this.currentUser,e);this.setItem(i,r.nr())}},{key:"Rr",value:function(e){var t=ko(this.persistenceKey,this.currentUser,e);this.removeItem(t)}},{key:"br",value:function(e){var t={clientId:this.rr,onlineState:e};this.storage.setItem(this.gr,JSON.stringify(t))}},{key:"vr",value:function(e,t,n){var r=wo(this.persistenceKey,e),i=new bo(e,t,n);this.setItem(r,i.nr())}},{key:"Vr",value:function(e){var t=JSON.stringify(Array.from(e));this.setItem(this.yr,t)}},{key:"Sr",value:function(e){var t=this._r.exec(e);return t?t[1]:null}},{key:"Cr",value:function(e,t){var n=this.Sr(e);return Io.er(n,t)}},{key:"Nr",value:function(e,t){var n=this.wr.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return xo.er(new V(i),r,t)}},{key:"$r",value:function(e,t){var n=this.mr.exec(e),r=Number(n[1]);return bo.er(r,t)}},{key:"Ir",value:function(e){return To.er(e)}},{key:"Or",value:function(e){return JSON.parse(e)}},{key:"kr",value:function(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(e.user.uid!==this.currentUser.uid){t.next=2;break}return t.abrupt("return",this.syncEngine.Br(e.batchId,e.state,e.error));case 2:G("SharedClientState","Ignoring mutation for non-active user ".concat(e.user.uid));case 3:case"end":return t.stop()}},null,this,null,Promise)}},{key:"Mr",value:function(e){return this.syncEngine.Lr(e.targetId,e.state,e.error)}},{key:"Dr",value:function(e,t){var n=this,r=t?this.ar.insert(e,t):this.ar.remove(e),i=this.Er(this.ar),a=this.Er(r),u=[],o=[];return a.forEach(function(e){i.has(e)||u.push(e)}),i.forEach(function(e){a.has(e)||o.push(e)}),this.syncEngine.qr(u,o).then(function(){n.ar=r})}},{key:"Tr",value:function(e){this.ar.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}},{key:"Er",value:function(e){var t=Ur();return e.forEach(function(e,n){t=t.unionWith(n.activeTargetIds)}),t}}],[{key:"C",value:function(e){return!(!e||!e.localStorage)}}]),e}(),_o=function(){function e(){P(this,e),this.Ur=new Eo,this.Kr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}return L(e,[{key:"addPendingMutation",value:function(e){}},{key:"updateMutationState",value:function(e,t,n){}},{key:"addLocalQueryTarget",value:function(e){return this.Ur.sr(e),this.Kr[e]||"not-current"}},{key:"updateQueryState",value:function(e,t,n){this.Kr[e]=t}},{key:"removeLocalQueryTarget",value:function(e){this.Ur.ir(e)}},{key:"isLocalQueryTarget",value:function(e){return this.Ur.activeTargetIds.has(e)}},{key:"clearQueryState",value:function(e){delete this.Kr[e]}},{key:"getAllActiveQueryTargets",value:function(){return this.Ur.activeTargetIds}},{key:"isActiveQueryTarget",value:function(e){return this.Ur.activeTargetIds.has(e)}},{key:"start",value:function(){return this.Ur=new Eo,Promise.resolve()}},{key:"handleUserChange",value:function(e,t,n){}},{key:"setOnlineState",value:function(e){}},{key:"shutdown",value:function(){}},{key:"writeSequenceNumber",value:function(e){}},{key:"notifyBundleLoaded",value:function(e){}}]),e}(),Ao=function(){function e(){P(this,e)}return L(e,[{key:"Gr",value:function(e){}},{key:"shutdown",value:function(){}}]),e}(),Do=function(){function e(){var t=this;P(this,e),this.Qr=function(){return t.jr()},this.zr=function(){return t.Wr()},this.Hr=[],this.Jr()}return L(e,[{key:"Gr",value:function(e){this.Hr.push(e)}},{key:"shutdown",value:function(){window.removeEventListener("online",this.Qr),window.removeEventListener("offline",this.zr)}},{key:"Jr",value:function(){window.addEventListener("online",this.Qr),window.addEventListener("offline",this.zr)}},{key:"jr",value:function(){G("ConnectivityMonitor","Network connectivity changed: AVAILABLE");var e,t=p(this.Hr);try{for(t.s();!(e=t.n()).done;){(0,e.value)(0)}}catch(n){t.e(n)}finally{t.f()}}},{key:"Wr",value:function(){G("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");var e,t=p(this.Hr);try{for(t.s();!(e=t.n()).done;){(0,e.value)(1)}}catch(n){t.e(n)}finally{t.f()}}}],[{key:"C",value:function(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}]),e}(),No=null;function Co(){return null===No?No=268435456+Math.round(2147483648*Math.random()):No++,"0x"+No.toString(16)}var Po={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},Fo=function(){function e(t){P(this,e),this.Yr=t.Yr,this.Zr=t.Zr}return L(e,[{key:"Xr",value:function(e){this.eo=e}},{key:"no",value:function(e){this.so=e}},{key:"onMessage",value:function(e){this.io=e}},{key:"close",value:function(){this.Zr()}},{key:"send",value:function(e){this.Yr(e)}},{key:"ro",value:function(){this.eo()}},{key:"oo",value:function(e){this.so(e)}},{key:"uo",value:function(e){this.io(e)}}]),e}(),Lo="WebChannelConnection",Ro=function(e){g(n,function(){function e(t){P(this,e);this.databaseInfo=t,this.databaseId=t.databaseId;var n=t.ssl?"https":"http";this.co=n+"://"+t.host,this.ao="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}L(e,[{key:"ho",get:function e(){return!1}},{key:"lo",value:function e(t,n,r,i,a){var u=Co(),o=this.fo(t,n);G("RestConnection","Sending RPC '".concat(t,"' ").concat(u,":"),o,r);var s={};return this._o(s,i,a),this.wo(t,o,s,r).then(function(e){return G("RestConnection","Received RPC '".concat(t,"' ").concat(u,": "),e),e},function(e){throw j("RestConnection","RPC '".concat(t,"' ").concat(u," failed with error: "),e,"url: ",o,"request:",r),e})}},{key:"mo",value:function e(t,n,r,i,a,u){return this.lo(t,n,r,i,a)}},{key:"_o",value:function e(t,n,r){t["X-Goog-Api-Client"]="gl-js/ fire/"+q,t["Content-Type"]="text/plain",this.databaseInfo.appId&&(t["X-Firebase-GMPID"]=this.databaseInfo.appId),n&&n.headers.forEach(function(e,n){return t[n]=e}),r&&r.headers.forEach(function(e,n){return t[n]=e})}},{key:"fo",value:function e(t,n){var r=Po[t];return"".concat(this.co,"/v1/").concat(n,":").concat(r)}}]);return e}());var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this,e)).forceLongPolling=e.forceLongPolling,r.autoDetectLongPolling=e.autoDetectLongPolling,r.useFetchStreams=e.useFetchStreams,r}return L(n,[{key:"wo",value:function(e,t,n,r){var i=Co();return new Promise(function(a,o){var s=new u.XhrIo;s.setWithCredentials(!0),s.listenOnce(u.EventType.COMPLETE,function(){try{switch(s.getLastErrorCode()){case u.ErrorCode.NO_ERROR:var t=s.getResponseJson();G(Lo,"XHR for RPC '".concat(e,"' ").concat(i," received:"),JSON.stringify(t)),a(t);break;case u.ErrorCode.TIMEOUT:G(Lo,"RPC '".concat(e,"' ").concat(i," timed out")),o(new Z(J.DEADLINE_EXCEEDED,"Request time out"));break;case u.ErrorCode.HTTP_ERROR:var n=s.getStatus();if(G(Lo,"RPC '".concat(e,"' ").concat(i," failed with status:"),n,"response text:",s.getResponseText()),n>0){var r=s.getResponseJson();Array.isArray(r)&&(r=r[0]);var c=null==r?void 0:r.error;if(c&&c.status&&c.message){var l=(f=c.status.toLowerCase().replace(/_/g,"-"),Object.values(J).indexOf(f)>=0?f:J.UNKNOWN);o(new Z(l,c.message))}else o(new Z(J.UNKNOWN,"Server responded with status "+s.getStatus()))}else o(new Z(J.UNAVAILABLE,"Connection failed."));break;default:W()}}finally{G(Lo,"RPC '".concat(e,"' ").concat(i," completed."))}var f});var c=JSON.stringify(r);G(Lo,"RPC '".concat(e,"' ").concat(i," sending request:"),r),s.send(t,"POST",c,n,15)})}},{key:"yo",value:function(e,t,n){var r=Co(),i=[this.co,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=(0,u.createWebChannelTransport)(),o=(0,u.getStatEventTarget)(),s={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/".concat(this.databaseId.projectId,"/databases/").concat(this.databaseId.database)},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(s.xmlHttpFactory=new u.FetchXmlHttpFactory({})),this._o(s.initMessageHeaders,t,n),s.encodeInitMessageHeaders=!0;var c=i.join("");G(Lo,"Creating RPC '".concat(e,"' stream ").concat(r,": ").concat(c),s);var l=a.createWebChannel(c,s),f=!1,h=!1,d=new Fo({Yr:function(t){h?G(Lo,"Not sending because RPC '".concat(e,"' stream ").concat(r," is closed:"),t):(f||(G(Lo,"Opening RPC '".concat(e,"' stream ").concat(r," transport.")),l.open(),f=!0),G(Lo,"RPC '".concat(e,"' stream ").concat(r," sending:"),t),l.send(t))},Zr:function(){return l.close()}}),v=function(e,t,n){e.listen(t,function(e){try{n(e)}catch(e){setTimeout(function(){throw e},0)}})};return v(l,u.WebChannel.EventType.OPEN,function(){h||G(Lo,"RPC '".concat(e,"' stream ").concat(r," transport opened."))}),v(l,u.WebChannel.EventType.CLOSE,function(){h||(h=!0,G(Lo,"RPC '".concat(e,"' stream ").concat(r," transport closed")),d.oo())}),v(l,u.WebChannel.EventType.ERROR,function(t){h||(h=!0,j(Lo,"RPC '".concat(e,"' stream ").concat(r," transport errored:"),t),d.oo(new Z(J.UNAVAILABLE,"The operation could not be completed")))}),v(l,u.WebChannel.EventType.MESSAGE,function(t){var n;if(!h){var i=t.data[0];H(!!i);var a=i,u=a.error||(null===(n=a[0])||void 0===n?void 0:n.error);if(u){G(Lo,"RPC '".concat(e,"' stream ").concat(r," received error:"),u);var o=u.status,s=function(e){var t=wr[o];if(void 0!==t)return Sr(t)}(),c=u.message;void 0===s&&(s=J.INTERNAL,c="Unknown error status: "+o+" with message "+u.message),h=!0,d.oo(new Z(s,c)),l.close()}else G(Lo,"RPC '".concat(e,"' stream ").concat(r," received:"),i),d.uo(i)}}),v(o,u.Event.STAT_EVENT,function(t){t.stat===u.Stat.PROXY?G(Lo,"RPC '".concat(e,"' stream ").concat(r," detected buffering proxy")):t.stat===u.Stat.NOPROXY&&G(Lo,"RPC '".concat(e,"' stream ").concat(r," detected no buffering proxy"))}),setTimeout(function(){d.ro()},0),d}}]),n}();function Mo(){return"undefined"!=typeof window?window:null}function Oo(){return"undefined"!=typeof document?document:null}function Vo(e){return new $r(e,!0)}var qo=function(){function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1.5,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4;P(this,e),this.Ys=t,this.timerId=n,this.po=r,this.Io=i,this.To=a,this.Eo=0,this.Ao=null,this.Ro=Date.now(),this.reset()}return L(e,[{key:"reset",value:function(){this.Eo=0}},{key:"Po",value:function(){this.Eo=this.To}},{key:"vo",value:function(e){var t=this;this.cancel();var n=Math.floor(this.Eo+this.bo()),r=Math.max(0,Date.now()-this.Ro),i=Math.max(0,n-r);i>0&&G("ExponentialBackoff","Backing off for ".concat(i," ms (base delay: ").concat(this.Eo," ms, delay with jitter: ").concat(n," ms, last attempt: ").concat(r," ms ago)")),this.Ao=this.Ys.enqueueAfterDelay(this.timerId,i,function(){return t.Ro=Date.now(),e()}),this.Eo*=this.Io,this.Eo<this.po&&(this.Eo=this.po),this.Eo>this.To&&(this.Eo=this.To)}},{key:"Vo",value:function(){null!==this.Ao&&(this.Ao.skipDelay(),this.Ao=null)}},{key:"cancel",value:function(){null!==this.Ao&&(this.Ao.cancel(),this.Ao=null)}},{key:"bo",value:function(){return(Math.random()-.5)*this.Eo}}]),e}(),Uo=function(){function e(t,n,r,i,a,u,o,s){P(this,e),this.Ys=t,this.So=r,this.Do=i,this.connection=a,this.authCredentialsProvider=u,this.appCheckCredentialsProvider=o,this.listener=s,this.state=0,this.Co=0,this.xo=null,this.No=null,this.stream=null,this.ko=new qo(t,n)}return L(e,[{key:"$o",value:function(){return 1===this.state||5===this.state||this.Mo()}},{key:"Mo",value:function(){return 2===this.state||3===this.state}},{key:"start",value:function(){4!==this.state?this.auth():this.Oo()}},{key:"stop",value:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.$o(),!e.t0){e.next=4;break}return e.next=4,m().awrap(this.close(0));case 4:case"end":return e.stop()}},null,this,null,Promise)}},{key:"Fo",value:function(){this.state=0,this.ko.reset()}},{key:"Bo",value:function(){var e=this;this.Mo()&&null===this.xo&&(this.xo=this.Ys.enqueueAfterDelay(this.So,6e4,function(){return e.Lo()}))}},{key:"qo",value:function(e){this.Uo(),this.stream.send(e)}},{key:"Lo",value:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.Mo()){e.next=2;break}return e.abrupt("return",this.close(0));case 2:case"end":return e.stop()}},null,this,null,Promise)}},{key:"Uo",value:function(){this.xo&&(this.xo.cancel(),this.xo=null)}},{key:"Ko",value:function(){this.No&&(this.No.cancel(),this.No=null)}},{key:"close",value:function(e,t){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return this.Uo(),this.Ko(),this.ko.cancel(),this.Co++,4!==e?this.ko.reset():t&&t.code===J.RESOURCE_EXHAUSTED?(Q(t.toString()),Q("Using maximum backoff delay to prevent overloading the backend."),this.ko.Po()):t&&t.code===J.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Go(),this.stream.close(),this.stream=null),this.state=e,n.next=9,m().awrap(this.listener.no(t));case 9:case"end":return n.stop()}},null,this,null,Promise)}},{key:"Go",value:function(){}},{key:"auth",value:function(){var e=this;this.state=1;var t=this.Qo(this.Co),n=this.Co;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(function(t){var r=c(t,2),i=r[0],a=r[1];e.Co===n&&e.jo(i,a)},function(n){t(function(){var t=new Z(J.UNKNOWN,"Fetching auth token failed: "+n.message);return e.zo(t)})})}},{key:"jo",value:function(e,t){var n=this,r=this.Qo(this.Co);this.stream=this.Wo(e,t),this.stream.Xr(function(){r(function(){return n.state=2,n.No=n.Ys.enqueueAfterDelay(n.Do,1e4,function(){return n.Mo()&&(n.state=3),Promise.resolve()}),n.listener.Xr()})}),this.stream.no(function(e){r(function(){return n.zo(e)})}),this.stream.onMessage(function(e){r(function(){return n.onMessage(e)})})}},{key:"Oo",value:function(){var e=this;this.state=5,this.ko.vo(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:e.state=0,e.start();case 1:case"end":return t.stop()}},null,null,null,Promise)})}},{key:"zo",value:function(e){return G("PersistentStream","close with error: ".concat(e)),this.stream=null,this.close(4,e)}},{key:"Qo",value:function(e){var t=this;return function(n){t.Ys.enqueueAndForget(function(){return t.Co===e?n():(G("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}}}]),e}(),Bo=function(e){g(n,Uo);var t=w(n);function n(e,r,i,a,u,o){var s;return P(this,n),(s=t.call(this,e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",r,i,a,o)).Tt=u,s}return L(n,[{key:"Wo",value:function(e,t){return this.connection.yo("Listen",e,t)}},{key:"onMessage",value:function(e){this.ko.reset();var t=yi(this.Tt,e),n=function(e){if(!("targetChange"in e))return ye.min();var t=e.targetChange;return t.targetIds&&t.targetIds.length?ye.min():t.readTime?ri(t.readTime):ye.min()}(e);return this.listener.Ho(t,n)}},{key:"Jo",value:function(e){var t={};t.database=li(this.Tt),t.addTarget=function(e,t){var n,r=t.target;return(n=xn(r)?{documents:ki(e,r)}:{query:wi(e,r)}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0?n.resumeToken=ti(e,t.resumeToken):t.snapshotVersion.compareTo(ye.min())>0&&(n.readTime=ei(e,t.snapshotVersion.toTimestamp())),n}(this.Tt,e);var n=bi(this.Tt,e);n&&(t.labels=n),this.qo(t)}},{key:"Yo",value:function(e){var t={};t.database=li(this.Tt),t.removeTarget=e,this.qo(t)}}]),n}(),Ko=function(e){g(n,Uo);var t=w(n);function n(e,r,i,a,u,o){var s;return P(this,n),(s=t.call(this,e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",r,i,a,o)).Tt=u,s.Zo=!1,s}return L(n,[{key:"Xo",get:function(){return this.Zo}},{key:"start",value:function(){this.Zo=!1,this.lastStreamToken=void 0,o(T(n.prototype),"start",this).call(this)}},{key:"Go",value:function(){this.Zo&&this.tu([])}},{key:"Wo",value:function(e,t){return this.connection.yo("Write",e,t)}},{key:"onMessage",value:function(e){if(H(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Zo){this.ko.reset();var t=gi(e.writeResults,e.commitTime),n=ri(e.commitTime);return this.listener.eu(n,t)}return H(!e.writeResults||0===e.writeResults.length),this.Zo=!0,this.listener.nu()}},{key:"su",value:function(){var e={};e.database=li(this.Tt),this.qo(e)}},{key:"tu",value:function(e){var t=this,n={streamToken:this.lastStreamToken,writes:e.map(function(e){return pi(t.Tt,e)})};this.qo(n)}}]),n}(),Go=function(e){g(n,function(){function e(){P(this,e)}return L(e)}());var t=w(n);function n(e,r,i,a){var u;return P(this,n),(u=t.call(this)).authCredentials=e,u.appCheckCredentials=r,u.connection=i,u.Tt=a,u.iu=!1,u}return L(n,[{key:"ru",value:function(){if(this.iu)throw new Z(J.FAILED_PRECONDITION,"The client has already been terminated.")}},{key:"lo",value:function(e,t,n){var r=this;return this.ru(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(function(i){var a=c(i,2),u=a[0],o=a[1];return r.connection.lo(e,t,n,u,o)}).catch(function(e){throw"FirebaseError"===e.name?(e.code===J.UNAUTHENTICATED&&(r.authCredentials.invalidateToken(),r.appCheckCredentials.invalidateToken()),e):new Z(J.UNKNOWN,e.toString())})}},{key:"mo",value:function(e,t,n,r){var i=this;return this.ru(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(function(a){var u=c(a,2),o=u[0],s=u[1];return i.connection.mo(e,t,n,o,s,r)}).catch(function(e){throw"FirebaseError"===e.name?(e.code===J.UNAUTHENTICATED&&(i.authCredentials.invalidateToken(),i.appCheckCredentials.invalidateToken()),e):new Z(J.UNKNOWN,e.toString())})}},{key:"terminate",value:function(){this.iu=!0}}]),n}();function Qo(e,t,n){var r,i,a,u,o,s;return m().async(function(c){for(;;)switch(c.prev=c.next){case 0:return r=Y(e),i=function(e,t,n){var r=wi(e,t),i=[];return n.forEach(function(e){"count"===e.lt?i.push({alias:e.alias.canonicalString(),count:{}}):"avg"===e.lt?i.push({alias:e.alias.canonicalString(),avg:{field:_i(e.fieldPath)}}):"sum"===e.lt&&i.push({alias:e.alias.canonicalString(),sum:{field:_i(e.fieldPath)}})}),{structuredAggregationQuery:{aggregations:i,structuredQuery:r.structuredQuery},parent:r.parent}}(r.Tt,Fn(t),n),a=i.parent,r.connection.ho||delete i.parent,c.next=4,m().awrap(r.mo("RunAggregationQuery",a,i,1));case 4:return u=c.sent.filter(function(e){return!!e.result}),c.abrupt("return",(H(1===u.length),(o=u[0]).result,o.result.aggregateFields,new vn({mapValue:{fields:null===(s=o.result)||void 0===s?void 0:s.aggregateFields}})));case 6:case"end":return c.stop()}},null,null,null,Promise)}var jo=function(){function e(t,n){P(this,e),this.asyncQueue=t,this.onlineStateHandler=n,this.state="Unknown",this.ou=0,this.uu=null,this.cu=!0}return L(e,[{key:"au",value:function(){var e=this;0===this.ou&&(this.hu("Unknown"),this.uu=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,function(){return e.uu=null,e.lu("Backend didn't respond within 10 seconds."),e.hu("Offline"),Promise.resolve()}))}},{key:"fu",value:function(e){"Online"===this.state?this.hu("Unknown"):(this.ou++,this.ou>=1&&(this.du(),this.lu("Connection failed 1 times. Most recent error: ".concat(e.toString())),this.hu("Offline")))}},{key:"set",value:function(e){this.du(),this.ou=0,"Online"===e&&(this.cu=!1),this.hu(e)}},{key:"hu",value:function(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}},{key:"lu",value:function(e){var t="Could not reach Cloud Firestore backend. ".concat(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.cu?(Q(t),this.cu=!1):G("OnlineStateTracker",t)}},{key:"du",value:function(){null!==this.uu&&(this.uu.cancel(),this.uu=null)}}]),e}(),zo=L(function e(t,n,r,i,a){var u=this;P(this,e),this.localStore=t,this.datastore=n,this.asyncQueue=r,this.remoteSyncer={},this._u=[],this.wu=new Map,this.mu=new Set,this.gu=[],this.yu=a,this.yu.Gr(function(e){r.enqueueAndForget(function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=ts(u),!e.t0){e.next=5;break}return G("RemoteStore","Restarting streams for network reachability change."),e.next=5,m().awrap(function(e){var t;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return(t=Y(e)).mu.add(4),n.next=4,m().awrap(Ho(t));case 4:return t.pu.set("Unknown"),t.mu.delete(4),n.next=8,m().awrap(Wo(t));case 8:case"end":return n.stop()}},null,null,null,Promise)}(u));case 5:case"end":return e.stop()}},null,null,null,Promise)})}),this.pu=new jo(r,i)});function Wo(e){var t,n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(!ts(e)){i.next=18;break}t=p(e.gu),i.prev=2,t.s();case 4:if((n=t.n()).done){i.next=10;break}return r=n.value,i.next=8,m().awrap(r(!0));case 8:i.next=4;break;case 10:i.next=15;break;case 12:i.prev=12,i.t0=i.catch(2),t.e(i.t0);case 15:return i.prev=15,t.f(),i.finish(15);case 18:case"end":return i.stop()}},null,null,[[2,12,15,18]],Promise)}function Ho(e){var t,n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:t=p(e.gu),i.prev=1,t.s();case 3:if((n=t.n()).done){i.next=9;break}return r=n.value,i.next=7,m().awrap(r(!1));case 7:i.next=3;break;case 9:i.next=14;break;case 11:i.prev=11,i.t0=i.catch(1),t.e(i.t0);case 14:return i.prev=14,t.f(),i.finish(14);case 17:case"end":return i.stop()}},null,null,[[1,11,14,17]],Promise)}function Xo(e,t){var n=Y(e);n.wu.has(t.targetId)||(n.wu.set(t.targetId,t),es(n)?$o(n):ks(n).Mo()&&Jo(n,t))}function Yo(e,t){var n=Y(e),r=ks(n);n.wu.delete(t),r.Mo()&&Zo(n,t),0===n.wu.size&&(r.Mo()?r.Bo():ts(n)&&n.pu.set("Unknown"))}function Jo(e,t){e.Iu.Ot(t.targetId),ks(e).Jo(t)}function Zo(e,t){e.Iu.Ot(t),ks(e).Yo(t)}function $o(e){e.Iu=new Wr({getRemoteKeysForTarget:function(t){return e.remoteSyncer.getRemoteKeysForTarget(t)},ie:function(t){return e.wu.get(t)||null}}),ks(e).start(),e.pu.au()}function es(e){return ts(e)&&!ks(e).$o()&&e.wu.size>0}function ts(e){return 0===Y(e).mu.size}function ns(e){e.Iu=void 0}function rs(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:e.wu.forEach(function(t,n){Jo(e,t)});case 1:case"end":return t.stop()}},null,null,null,Promise)}function is(e,t){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:ns(e),es(e)?(e.pu.fu(t),$o(e)):e.pu.set("Unknown");case 1:case"end":return n.stop()}},null,null,null,Promise)}function as(e,t,n){var r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(e.pu.set("Online"),!(t instanceof jr&&2===t.state&&t.cause)){i.next=13;break}return i.prev=1,i.next=4,m().awrap(function(e,t){var n,r,i,a;return m().async(function(u){for(;;)switch(u.prev=u.next){case 0:n=t.cause,r=p(t.targetIds),u.prev=2,r.s();case 4:if((i=r.n()).done){u.next=14;break}if(a=i.value,u.t0=e.wu.has(a),!u.t0){u.next=12;break}return u.next=10,m().awrap(e.remoteSyncer.rejectListen(a,n));case 10:e.wu.delete(a),e.Iu.removeTarget(a);case 12:u.next=4;break;case 14:u.next=19;break;case 16:u.prev=16,u.t1=u.catch(2),r.e(u.t1);case 19:return u.prev=19,r.f(),u.finish(19);case 22:case"end":return u.stop()}},null,null,[[2,16,19,22]],Promise)}(e,t));case 4:i.next=11;break;case 6:return i.prev=6,i.t0=i.catch(1),G("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),i.t0),i.next=11,m().awrap(us(e,i.t0));case 11:i.next=29;break;case 13:if(t instanceof Gr?e.Iu.Qt(t):t instanceof Qr?e.Iu.Zt(t):e.Iu.Wt(t),n.isEqual(ye.min())){i.next=29;break}return i.prev=14,i.next=17,m().awrap(ao(e.localStore));case 17:if(r=i.sent,i.t1=n.compareTo(r)>=0,!i.t1){i.next=22;break}return i.next=22,m().awrap(function(e,t){var n=e.Iu.ee(t);return n.targetChanges.forEach(function(n,r){if(n.resumeToken.approximateByteSize()>0){var i=e.wu.get(r);i&&e.wu.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach(function(t){var n=e.wu.get(t);if(n){e.wu.set(t,n.withResumeToken(ot.EMPTY_BYTE_STRING,n.snapshotVersion)),Zo(e,t);var r=new la(n.target,t,1,n.sequenceNumber);Jo(e,r)}}),e.remoteSyncer.applyRemoteEvent(n)}(e,n));case 22:i.next=29;break;case 24:return i.prev=24,i.t2=i.catch(14),G("RemoteStore","Failed to raise snapshot:",i.t2),i.next=29,m().awrap(us(e,i.t2));case 29:case"end":return i.stop()}},null,null,[[1,6],[14,24]],Promise)}function us(e,t,n){return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(Ue(t)){r.next=2;break}throw t;case 2:return e.mu.add(1),r.next=5,m().awrap(Ho(e));case 5:e.pu.set("Offline"),n||(n=function(){return ao(e.localStore)}),e.asyncQueue.enqueueRetryable(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return G("RemoteStore","Retrying IndexedDB access"),t.next=3,m().awrap(n());case 3:return e.mu.delete(1),t.next=6,m().awrap(Wo(e));case 6:case"end":return t.stop()}},null,null,null,Promise)});case 8:case"end":return r.stop()}},null,null,null,Promise)}function os(e,t){return t().catch(function(n){return us(e,n,t)})}function ss(e){var t,n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:t=Y(e),n=ws(t),r=t._u.length>0?t._u[t._u.length-1].batchId:-1;case 2:if(!cs(t)){a.next=19;break}return a.prev=3,a.next=6,m().awrap(so(t.localStore,r));case 6:if(null!==(i=a.sent)){a.next=10;break}return 0===t._u.length&&n.Bo(),a.abrupt("break",19);case 10:r=i.batchId,ls(t,i),a.next=17;break;case 13:return a.prev=13,a.t0=a.catch(3),a.next=17,m().awrap(us(t,a.t0));case 17:a.next=2;break;case 19:fs(t)&&hs(t);case 20:case"end":return a.stop()}},null,null,[[3,13]],Promise)}function cs(e){return ts(e)&&e._u.length<10}function ls(e,t){e._u.push(t);var n=ws(e);n.Mo()&&n.Xo&&n.tu(t.mutations)}function fs(e){return ts(e)&&!ws(e).$o()&&e._u.length>0}function hs(e){ws(e).start()}function ds(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:ws(e).su();case 1:case"end":return t.stop()}},null,null,null,Promise)}function vs(e){var t,n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:t=ws(e),n=p(e._u);try{for(n.s();!(r=n.n()).done;)i=r.value,t.tu(i.mutations)}catch(u){n.e(u)}finally{n.f()}case 3:case"end":return a.stop()}},null,null,null,Promise)}function ys(e,t,n){var r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return r=e._u.shift(),i=sa.from(r,t,n),a.next=3,m().awrap(os(e,function(){return e.remoteSyncer.applySuccessfulWrite(i)}));case 3:return a.next=5,m().awrap(ss(e));case 5:case"end":return a.stop()}},null,null,null,Promise)}function ps(e,t){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=t&&ws(e).Xo,!n.t0){n.next=4;break}return n.next=4,m().awrap(function(e,t){var n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(!Er(r=t.code)||r===J.ABORTED){i.next=7;break}return n=e._u.shift(),ws(e).Fo(),i.next=5,m().awrap(os(e,function(){return e.remoteSyncer.rejectFailedWrite(n.batchId,t)}));case 5:return i.next=7,m().awrap(ss(e));case 7:case"end":return i.stop()}},null,null,null,Promise)}(e,t));case 4:fs(e)&&hs(e);case 5:case"end":return n.stop()}},null,null,null,Promise)}function ms(e,t){var n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return(n=Y(e)).asyncQueue.verifyOperationInProgress(),G("RemoteStore","RemoteStore received new credentials"),r=ts(n),n.mu.add(3),i.next=6,m().awrap(Ho(n));case 6:return r&&n.pu.set("Unknown"),i.next=9,m().awrap(n.remoteSyncer.handleCredentialChange(t));case 9:return n.mu.delete(3),i.next=12,m().awrap(Wo(n));case 12:case"end":return i.stop()}},null,null,null,Promise)}function gs(e,t){var n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(n=Y(e),!t){r.next=7;break}return n.mu.delete(2),r.next=5,m().awrap(Wo(n));case 5:r.next=13;break;case 7:if(r.t0=t,r.t0){r.next=13;break}return n.mu.add(2),r.next=12,m().awrap(Ho(n));case 12:n.pu.set("Unknown");case 13:case"end":return r.stop()}},null,null,null,Promise)}function ks(e){return e.Tu||(e.Tu=function(e,t,n){var r=Y(e);return r.ru(),new Bo(t,r.connection,r.authCredentials,r.appCheckCredentials,r.Tt,n)}(e.datastore,e.asyncQueue,{Xr:rs.bind(null,e),no:is.bind(null,e),Ho:as.bind(null,e)}),e.gu.push(function(t){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!t){n.next=4;break}e.Tu.Fo(),es(e)?$o(e):e.pu.set("Unknown"),n.next=7;break;case 4:return n.next=6,m().awrap(e.Tu.stop());case 6:ns(e);case 7:case"end":return n.stop()}},null,null,null,Promise)})),e.Tu}function ws(e){return e.Eu||(e.Eu=function(e,t,n){var r=Y(e);return r.ru(),new Ko(t,r.connection,r.authCredentials,r.appCheckCredentials,r.Tt,n)}(e.datastore,e.asyncQueue,{Xr:ds.bind(null,e),no:ps.bind(null,e),nu:vs.bind(null,e),eu:ys.bind(null,e)}),e.gu.push(function(t){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!t){n.next=6;break}return e.Eu.Fo(),n.next=4,m().awrap(ss(e));case 4:n.next=9;break;case 6:return n.next=8,m().awrap(e.Eu.stop());case 8:e._u.length>0&&(G("RemoteStore","Stopping write stream with ".concat(e._u.length," pending writes")),e._u=[]);case 9:case"end":return n.stop()}},null,null,null,Promise)})),e.Eu}var xs=function(){function e(t,n,r,i,a){P(this,e),this.asyncQueue=t,this.timerId=n,this.targetTimeMs=r,this.op=i,this.removalCallback=a,this.deferred=new $,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(function(e){})}return L(e,[{key:"start",value:function(e){var t=this;this.timerHandle=setTimeout(function(){return t.handleDelayElapsed()},e)}},{key:"skipDelay",value:function(){return this.handleDelayElapsed()}},{key:"cancel",value:function(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Z(J.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}},{key:"handleDelayElapsed",value:function(){var e=this;this.asyncQueue.enqueueAndForget(function(){return null!==e.timerHandle?(e.clearTimeout(),e.op().then(function(t){return e.deferred.resolve(t)})):Promise.resolve()})}},{key:"clearTimeout",value:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)})}],[{key:"createAndSchedule",value:function(t,n,r,i,a){var u=new e(t,n,Date.now()+r,i,a);return u.start(r),u}}]),e}();function bs(e,t){if(Q("AsyncQueue","".concat(t,": ").concat(e)),Ue(e))return new Z(J.UNAVAILABLE,"".concat(t,": ").concat(e));throw e}var Is=function(){function e(t){P(this,e),this.comparator=t?function(e,n){return t(e,n)||we.comparator(e.key,n.key)}:function(e,t){return we.comparator(e.key,t.key)},this.keyedMap=Cr(),this.sortedSet=new on(this.comparator)}return L(e,[{key:"has",value:function(e){return null!=this.keyedMap.get(e)}},{key:"get",value:function(e){return this.keyedMap.get(e)}},{key:"first",value:function(){return this.sortedSet.minKey()}},{key:"last",value:function(){return this.sortedSet.maxKey()}},{key:"isEmpty",value:function(){return this.sortedSet.isEmpty()}},{key:"indexOf",value:function(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}},{key:"size",get:function(){return this.sortedSet.size}},{key:"forEach",value:function(e){this.sortedSet.inorderTraversal(function(t,n){return e(t),!1})}},{key:"add",value:function(e){var t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}},{key:"delete",value:function(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}},{key:"isEqual",value:function(t){if(!(t instanceof e))return!1;if(this.size!==t.size)return!1;for(var n=this.sortedSet.getIterator(),r=t.sortedSet.getIterator();n.hasNext();){var i=n.getNext().key,a=r.getNext().key;if(!i.isEqual(a))return!1}return!0}},{key:"toString",value:function(){var e=[];return this.forEach(function(t){e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}},{key:"copy",value:function(t,n){var r=new e;return r.comparator=this.comparator,r.keyedMap=t,r.sortedSet=n,r}}],[{key:"emptySet",value:function(t){return new e(t.comparator)}}]),e}(),Ts=function(){function e(){P(this,e),this.Au=new on(we.comparator)}return L(e,[{key:"track",value:function(e){var t=e.doc.key,n=this.Au.get(t);n?0!==e.type&&3===n.type?this.Au=this.Au.insert(t,e):3===e.type&&1!==n.type?this.Au=this.Au.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Au=this.Au.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Au=this.Au.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Au=this.Au.remove(t):1===e.type&&2===n.type?this.Au=this.Au.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Au=this.Au.insert(t,{type:2,doc:e.doc}):W():this.Au=this.Au.insert(t,e)}},{key:"Ru",value:function(){var e=[];return this.Au.inorderTraversal(function(t,n){e.push(n)}),e}}]),e}(),Es=function(){function e(t,n,r,i,a,u,o,s,c){P(this,e),this.query=t,this.docs=n,this.oldDocs=r,this.docChanges=i,this.mutatedKeys=a,this.fromCache=u,this.syncStateChanged=o,this.excludesMetadataChanges=s,this.hasCachedResults=c}return L(e,[{key:"hasPendingWrites",get:function(){return!this.mutatedKeys.isEmpty()}},{key:"isEqual",value:function(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Mn(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;var t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(var r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}],[{key:"fromInitialDocuments",value:function(t,n,r,i,a){var u=[];return n.forEach(function(e){u.push({type:0,doc:e})}),new e(t,n,Is.emptySet(n),u,r,i,!0,!1,a)}}]),e}(),Ss=L(function e(){P(this,e),this.Pu=void 0,this.listeners=[]}),_s=L(function e(){P(this,e),this.queries=new _r(function(e){return On(e)},Mn),this.onlineState="Unknown",this.vu=new Set});function As(e,t){var n,r,i,a,u;return m().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(n=Y(e),r=t.query,i=!1,(a=n.queries.get(r))||(i=!0,a=new Ss),!i){o.next=13;break}return o.prev=3,o.next=6,m().awrap(n.onListen(r));case 6:a.Pu=o.sent,o.next=13;break;case 9:return o.prev=9,o.t0=o.catch(3),u=bs(o.t0,"Initialization of query '".concat(Vn(t.query),"' failed")),o.abrupt("return",void t.onError(u));case 13:n.queries.set(r,a),a.listeners.push(t),t.bu(n.onlineState),a.Pu&&t.Vu(a.Pu)&&Ps(n);case 14:case"end":return o.stop()}},null,null,[[3,9]],Promise)}function Ds(e,t){var n,r,i,a,u;return m().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(n=Y(e),r=t.query,i=!1,(a=n.queries.get(r))&&(u=a.listeners.indexOf(t))>=0&&(a.listeners.splice(u,1),i=0===a.listeners.length),!i){o.next=6;break}return o.abrupt("return",(n.queries.delete(r),n.onUnlisten(r)));case 6:case"end":return o.stop()}},null,null,null,Promise)}function Ns(e,t){var n,r=Y(e),i=!1,a=p(t);try{for(a.s();!(n=a.n()).done;){var u=n.value,o=u.query,s=r.queries.get(o);if(s){var c,l=p(s.listeners);try{for(l.s();!(c=l.n()).done;){c.value.Vu(u)&&(i=!0)}}catch(f){l.e(f)}finally{l.f()}s.Pu=u}}}catch(f){a.e(f)}finally{a.f()}i&&Ps(r)}function Cs(e,t,n){var r=Y(e),i=r.queries.get(t);if(i){var a,u=p(i.listeners);try{for(u.s();!(a=u.n()).done;){a.value.onError(n)}}catch(o){u.e(o)}finally{u.f()}}r.queries.delete(t)}function Ps(e){e.vu.forEach(function(e){e.next()})}var Fs=function(){function e(t,n,r){P(this,e),this.query=t,this.Su=n,this.Du=!1,this.Cu=null,this.onlineState="Unknown",this.options=r||{}}return L(e,[{key:"Vu",value:function(e){if(!this.options.includeMetadataChanges){var t,n=[],r=p(e.docChanges);try{for(r.s();!(t=r.n()).done;){var i=t.value;3!==i.type&&n.push(i)}}catch(u){r.e(u)}finally{r.f()}e=new Es(e.query,e.docs,e.oldDocs,n,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}var a=!1;return this.Du?this.xu(e)&&(this.Su.next(e),a=!0):this.Nu(e,this.onlineState)&&(this.ku(e),a=!0),this.Cu=e,a}},{key:"onError",value:function(e){this.Su.error(e)}},{key:"bu",value:function(e){this.onlineState=e;var t=!1;return this.Cu&&!this.Du&&this.Nu(this.Cu,e)&&(this.ku(this.Cu),t=!0),t}},{key:"Nu",value:function(e,t){if(!e.fromCache)return!0;var n="Offline"!==t;return(!this.options.$u||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}},{key:"xu",value:function(e){if(e.docChanges.length>0)return!0;var t=this.Cu&&this.Cu.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}},{key:"ku",value:function(e){e=Es.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Du=!0,this.Su.next(e)}}]),e}(),Ls=function(){function e(t,n){P(this,e),this.Mu=t,this.byteLength=n}return L(e,[{key:"Ou",value:function(){return"metadata"in this.Mu}}]),e}(),Rs=function(){function e(t){P(this,e),this.Tt=t}return L(e,[{key:"Zi",value:function(e){return oi(this.Tt,e)}},{key:"Xi",value:function(e){return e.metadata.exists?di(this.Tt,e.document,!1):pn.newNoDocument(this.Zi(e.metadata.name),this.tr(e.metadata.readTime))}},{key:"tr",value:function(e){return ri(e)}}]),e}(),Ms=function(){function e(t,n,r){P(this,e),this.Fu=t,this.localStore=n,this.Tt=r,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Os(t)}return L(e,[{key:"Bu",value:function(e){this.progress.bytesLoaded+=e.byteLength;var t=this.progress.documentsLoaded;if(e.Mu.namedQuery)this.queries.push(e.Mu.namedQuery);else if(e.Mu.documentMetadata){this.documents.push({metadata:e.Mu.documentMetadata}),e.Mu.documentMetadata.exists||++t;var n=me.fromString(e.Mu.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.Mu.document&&(this.documents[this.documents.length-1].document=e.Mu.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}},{key:"Lu",value:function(e){var t,n=new Map,r=new Rs(this.Tt),i=p(e);try{for(i.s();!(t=i.n()).done;){var a=t.value;if(a.metadata.queries){var u,o=r.Zi(a.metadata.name),s=p(a.metadata.queries);try{for(s.s();!(u=s.n()).done;){var c=u.value,l=(n.get(c)||Vr()).add(o);n.set(c,l)}}catch(f){s.e(f)}finally{s.f()}}}}catch(f){i.e(f)}finally{i.f()}return n}},{key:"complete",value:function(){var e,t,n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.next=2,m().awrap(po(this.localStore,new Rs(this.Tt),this.documents,this.Fu.id));case 2:e=a.sent,t=this.Lu(this.documents),n=p(this.queries),a.prev=5,n.s();case 7:if((r=n.n()).done){a.next=13;break}return i=r.value,a.next=11,m().awrap(mo(this.localStore,i,t.get(i.name)));case 11:a.next=7;break;case 13:a.next=18;break;case 15:a.prev=15,a.t0=a.catch(5),n.e(a.t0);case 18:return a.prev=18,n.f(),a.finish(18);case 21:return a.abrupt("return",(this.progress.taskState="Success",{progress:this.progress,qu:this.collectionGroups,Uu:e}));case 22:case"end":return a.stop()}},null,this,[[5,15,18,21]],Promise)}}]),e}();function Os(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}var Vs=L(function e(t){P(this,e),this.key=t}),qs=L(function e(t){P(this,e),this.key=t}),Us=function(){function e(t,n){P(this,e),this.query=t,this.Ku=n,this.Gu=null,this.hasCachedResults=!1,this.current=!1,this.Qu=Vr(),this.mutatedKeys=Vr(),this.ju=Bn(t),this.zu=new Is(this.ju)}return L(e,[{key:"Wu",get:function(){return this.Ku}},{key:"Hu",value:function(e,t){var n=this,r=t?t.Ju:new Ts,i=t?t.zu:this.zu,a=t?t.mutatedKeys:this.mutatedKeys,u=i,o=!1,s="F"===this.query.limitType&&i.size===this.query.limit?i.last():null,c="L"===this.query.limitType&&i.size===this.query.limit?i.first():null;if(e.inorderTraversal(function(e,t){var l=i.get(e),f=qn(n.query,t)?t:null,h=!!l&&n.mutatedKeys.has(l.key),d=!!f&&(f.hasLocalMutations||n.mutatedKeys.has(f.key)&&f.hasCommittedMutations),v=!1;l&&f?l.data.isEqual(f.data)?h!==d&&(r.track({type:3,doc:f}),v=!0):n.Yu(l,f)||(r.track({type:2,doc:f}),v=!0,(s&&n.ju(f,s)>0||c&&n.ju(f,c)<0)&&(o=!0)):!l&&f?(r.track({type:0,doc:f}),v=!0):l&&!f&&(r.track({type:1,doc:l}),v=!0,(s||c)&&(o=!0)),v&&(f?(u=u.add(f),a=d?a.add(e):a.delete(e)):(u=u.delete(e),a=a.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){var l="F"===this.query.limitType?u.last():u.first();u=u.delete(l.key),a=a.delete(l.key),r.track({type:1,doc:l})}return{zu:u,Ju:r,Li:o,mutatedKeys:a}}},{key:"Yu",value:function(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}},{key:"applyChanges",value:function(e,t,n){var r=this,i=this.zu;this.zu=e.zu,this.mutatedKeys=e.mutatedKeys;var a=e.Ju.Ru();a.sort(function(e,t){return function(e,t){var n=function(e){switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return W()}};return n(e)-n(t)}(e.type,t.type)||r.ju(e.doc,t.doc)}),this.Zu(n);var u=t?this.Xu():[],o=0===this.Qu.size&&this.current?1:0,s=o!==this.Gu;return this.Gu=o,0!==a.length||s?{snapshot:new Es(this.query,e.zu,i,a,e.mutatedKeys,0===o,s,!1,!!n&&n.resumeToken.approximateByteSize()>0),tc:u}:{tc:u}}},{key:"bu",value:function(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({zu:this.zu,Ju:new Ts,mutatedKeys:this.mutatedKeys,Li:!1},!1)):{tc:[]}}},{key:"ec",value:function(e){return!this.Ku.has(e)&&!!this.zu.has(e)&&!this.zu.get(e).hasLocalMutations}},{key:"Zu",value:function(e){var t=this;e&&(e.addedDocuments.forEach(function(e){return t.Ku=t.Ku.add(e)}),e.modifiedDocuments.forEach(function(e){}),e.removedDocuments.forEach(function(e){return t.Ku=t.Ku.delete(e)}),this.current=e.current)}},{key:"Xu",value:function(){var e=this;if(!this.current)return[];var t=this.Qu;this.Qu=Vr(),this.zu.forEach(function(t){e.ec(t.key)&&(e.Qu=e.Qu.add(t.key))});var n=[];return t.forEach(function(t){e.Qu.has(t)||n.push(new qs(t))}),this.Qu.forEach(function(e){t.has(e)||n.push(new Vs(e))}),n}},{key:"nc",value:function(e){this.Ku=e.Yi,this.Qu=Vr();var t=this.Hu(e.documents);return this.applyChanges(t,!0)}},{key:"sc",value:function(){return Es.fromInitialDocuments(this.query,this.zu,this.mutatedKeys,0===this.Gu,this.hasCachedResults)}}]),e}(),Bs=L(function e(t,n,r){P(this,e),this.query=t,this.targetId=n,this.view=r}),Ks=L(function e(t){P(this,e),this.key=t,this.ic=!1}),Gs=function(){function e(t,n,r,i,a,u){P(this,e),this.localStore=t,this.remoteStore=n,this.eventManager=r,this.sharedClientState=i,this.currentUser=a,this.maxConcurrentLimboResolutions=u,this.rc={},this.oc=new _r(function(e){return On(e)},Mn),this.uc=new Map,this.cc=new Set,this.ac=new on(we.comparator),this.hc=new Map,this.lc=new Ou,this.fc={},this.dc=new Map,this._c=du.Sn(),this.onlineState="Unknown",this.wc=void 0}return L(e,[{key:"isPrimaryClient",get:function(){return!0===this.wc}}]),e}();function Qs(e,t){var n,r,i,a,u,o;return m().async(function(s){for(;;)switch(s.prev=s.next){case 0:if(n=kc(e),!(a=n.oc.get(t))){s.next=6;break}r=a.targetId,n.sharedClientState.addLocalQueryTarget(r),i=a.view.sc(),s.next=15;break;case 6:return s.next=8,m().awrap(co(n.localStore,Fn(t)));case 8:return u=s.sent,n.isPrimaryClient&&Xo(n.remoteStore,u),o=n.sharedClientState.addLocalQueryTarget(u.targetId),r=u.targetId,s.next=14,m().awrap(js(n,t,r,"current"===o,u.resumeToken));case 14:i=s.sent;case 15:return s.abrupt("return",i);case 16:case"end":return s.stop()}},null,null,null,Promise)}function js(e,t,n,r,i){var a,u,o,s,c,l;return m().async(function(f){for(;;)switch(f.prev=f.next){case 0:return e.mc=function(t,n,r){return function(e,t,n,r){var i,a,u;return m().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(i=t.view.Hu(n),o.t0=i.Li,!o.t0){o.next=6;break}return o.next=5,m().awrap(fo(e.localStore,t.query,!1).then(function(e){var n=e.documents;return t.view.Hu(n,i)}));case 5:i=o.sent;case 6:return a=r&&r.targetChanges.get(t.targetId),u=t.view.applyChanges(i,e.isPrimaryClient,a),o.abrupt("return",(ic(e,t.targetId,u.tc),u.snapshot));case 8:case"end":return o.stop()}},null,null,null,Promise)}(e,t,n,r)},f.next=3,m().awrap(fo(e.localStore,t,!0));case 3:return a=f.sent,u=new Us(t,a.Yi),o=u.Hu(a.documents),s=Kr.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),c=u.applyChanges(o,e.isPrimaryClient,s),ic(e,n,c.tc),l=new Bs(t,n,u),f.abrupt("return",(e.oc.set(t,l),e.uc.has(n)?e.uc.get(n).push(t):e.uc.set(n,[t]),c.snapshot));case 11:case"end":return f.stop()}},null,null,null,Promise)}function zs(e,t){var n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:if(n=Y(e),r=n.oc.get(t),!((i=n.uc.get(r.targetId)).length>1)){a.next=3;break}return a.abrupt("return",(n.uc.set(r.targetId,i.filter(function(e){return!Mn(e,t)})),void n.oc.delete(t)));case 3:if(!n.isPrimaryClient){a.next=11;break}if(n.sharedClientState.removeLocalQueryTarget(r.targetId),a.t0=n.sharedClientState.isActiveQueryTarget(r.targetId),a.t0){a.next=9;break}return a.next=9,m().awrap(lo(n.localStore,r.targetId,!1).then(function(){n.sharedClientState.clearQueryState(r.targetId),Yo(n.remoteStore,r.targetId),nc(n,r.targetId)}).catch(Le));case 9:a.next=14;break;case 11:return nc(n,r.targetId),a.next=14,m().awrap(lo(n.localStore,r.targetId,!0));case 14:case"end":return a.stop()}},null,null,null,Promise)}function Ws(e,t,n){var r,i,a;return m().async(function(u){for(;;)switch(u.prev=u.next){case 0:return r=wc(e),u.prev=1,u.next=4,m().awrap(function(e,t){var n,r,i=Y(e),a=ve.now(),u=t.reduce(function(e,t){return e.add(t.key)},Vr());return i.persistence.runTransaction("Locally write mutations","readwrite",function(e){var o=Dr(),s=Vr();return i.ji.getEntries(e,u).next(function(e){(o=e).forEach(function(e,t){t.isValidDocument()||(s=s.add(e))})}).next(function(){return i.localDocuments.getOverlayedDocuments(e,o)}).next(function(r){n=r;var u,o=[],s=p(t);try{for(s.s();!(u=s.n()).done;){var c=u.value,l=dr(c,n.get(c.key).overlayedDocument);null!=l&&o.push(new pr(c.key,l,yn(l.value.mapValue),or.exists(!0)))}}catch(f){s.e(f)}finally{s.f()}return i.mutationQueue.addMutationBatch(e,a,o,t)}).next(function(t){r=t;var a=t.applyToLocalDocumentSet(n,s);return i.documentOverlayCache.saveOverlays(e,t.batchId,a)})}).then(function(){return{batchId:r.batchId,changes:Pr(n)}})}(r.localStore,t));case 4:return i=u.sent,r.sharedClientState.addPendingMutation(i.batchId),function(e,t,n){var r=e.fc[e.currentUser.toKey()];r||(r=new on(fe)),r=r.insert(t,n),e.fc[e.currentUser.toKey()]=r}(r,i.batchId,n),u.next=9,m().awrap(oc(r,i.changes));case 9:return u.next=11,m().awrap(ss(r.remoteStore));case 11:u.next=17;break;case 13:u.prev=13,u.t0=u.catch(1),a=bs(u.t0,"Failed to persist write"),n.reject(a);case 17:case"end":return u.stop()}},null,null,[[1,13]],Promise)}function Hs(e,t){var n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return n=Y(e),i.prev=1,i.next=4,m().awrap(uo(n.localStore,t));case 4:return r=i.sent,t.targetChanges.forEach(function(e,t){var r=n.hc.get(t);r&&(H(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.ic=!0:e.modifiedDocuments.size>0?H(r.ic):e.removedDocuments.size>0&&(H(r.ic),r.ic=!1))}),i.next=8,m().awrap(oc(n,r,t));case 8:i.next=14;break;case 10:return i.prev=10,i.t0=i.catch(1),i.next=14,m().awrap(Le(i.t0));case 14:case"end":return i.stop()}},null,null,[[1,10]],Promise)}function Xs(e,t,n){var r=Y(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){var i=[];r.oc.forEach(function(e,n){var r=n.view.bu(t);r.snapshot&&i.push(r.snapshot)}),function(e,t){var n=Y(e);n.onlineState=t;var r=!1;n.queries.forEach(function(e,n){var i,a=p(n.listeners);try{for(a.s();!(i=a.n()).done;){i.value.bu(t)&&(r=!0)}}catch(u){a.e(u)}finally{a.f()}}),r&&Ps(n)}(r.eventManager,t),i.length&&r.rc.Ho(i),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}function Ys(e,t,n){var r,i,a,u,o,s;return m().async(function(c){for(;;)switch(c.prev=c.next){case 0:if((r=Y(e)).sharedClientState.updateQueryState(t,"rejected",n),i=r.hc.get(t),!(a=i&&i.key)){c.next=14;break}return u=(u=new on(we.comparator)).insert(a,pn.newNoDocument(a,ye.min())),o=Vr().add(a),s=new Br(ye.min(),new Map,new ln(fe),u,o),c.next=9,m().awrap(Hs(r,s));case 9:r.ac=r.ac.remove(a),r.hc.delete(t),uc(r),c.next=16;break;case 14:return c.next=16,m().awrap(lo(r.localStore,t,!1).then(function(){return nc(r,t,n)}).catch(Le));case 16:case"end":return c.stop()}},null,null,null,Promise)}function Js(e,t){var n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=Y(e),r=t.batch.batchId,a.prev=1,a.next=4,m().awrap(io(n.localStore,t));case 4:return i=a.sent,tc(n,r,null),ec(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),a.next=10,m().awrap(oc(n,i));case 10:a.next=16;break;case 12:return a.prev=12,a.t0=a.catch(1),a.next=16,m().awrap(Le(a.t0));case 16:case"end":return a.stop()}},null,null,[[1,12]],Promise)}function Zs(e,t,n){var r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return r=Y(e),a.prev=1,a.next=4,m().awrap(function(e,t){var n=Y(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",function(e){var r;return n.mutationQueue.lookupMutationBatch(e,t).next(function(t){return H(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)}).next(function(){return n.mutationQueue.performConsistencyCheck(e)}).next(function(){return n.documentOverlayCache.removeOverlaysForBatchId(e,r,t)}).next(function(){return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r)}).next(function(){return n.localDocuments.getDocuments(e,r)})})}(r.localStore,t));case 4:return i=a.sent,tc(r,t,n),ec(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),a.next=10,m().awrap(oc(r,i));case 10:a.next=16;break;case 12:return a.prev=12,a.t0=a.catch(1),a.next=16,m().awrap(Le(a.t0));case 16:case"end":return a.stop()}},null,null,[[1,12]],Promise)}function $s(e,t){var n,r,i,a;return m().async(function(u){for(;;)switch(u.prev=u.next){case 0:return ts((n=Y(e)).remoteStore)||G("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),u.prev=2,u.next=5,m().awrap(function(e){var t=Y(n.localStore);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",function(e){return t.mutationQueue.getHighestUnacknowledgedBatchId(e)})}());case 5:if(-1!==(r=u.sent)){u.next=8;break}return u.abrupt("return",void t.resolve());case 8:(i=n.dc.get(r)||[]).push(t),n.dc.set(r,i),u.next=16;break;case 12:u.prev=12,u.t0=u.catch(2),a=bs(u.t0,"Initialization of waitForPendingWrites() operation failed"),t.reject(a);case 16:case"end":return u.stop()}},null,null,[[2,12]],Promise)}function ec(e,t){(e.dc.get(t)||[]).forEach(function(e){e.resolve()}),e.dc.delete(t)}function tc(e,t,n){var r=Y(e),i=r.fc[r.currentUser.toKey()];if(i){var a=i.get(t);a&&(n?a.reject(n):a.resolve(),i=i.remove(t)),r.fc[r.currentUser.toKey()]=i}}function nc(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;e.sharedClientState.removeLocalQueryTarget(t);var r,i=p(e.uc.get(t));try{for(i.s();!(r=i.n()).done;){var a=r.value;e.oc.delete(a),n&&e.rc.gc(a,n)}}catch(u){i.e(u)}finally{i.f()}e.uc.delete(t),e.isPrimaryClient&&e.lc.ds(t).forEach(function(t){e.lc.containsKey(t)||rc(e,t)})}function rc(e,t){e.cc.delete(t.path.canonicalString());var n=e.ac.get(t);null!==n&&(Yo(e.remoteStore,n),e.ac=e.ac.remove(t),e.hc.delete(n),uc(e))}function ic(e,t,n){var r,i=p(n);try{for(i.s();!(r=i.n()).done;){var a=r.value;a instanceof Vs?(e.lc.addReference(a.key,t),ac(e,a)):a instanceof qs?(G("SyncEngine","Document no longer in limbo: "+a.key),e.lc.removeReference(a.key,t),e.lc.containsKey(a.key)||rc(e,a.key)):W()}}catch(u){i.e(u)}finally{i.f()}}function ac(e,t){var n=t.key,r=n.path.canonicalString();e.ac.get(n)||e.cc.has(r)||(G("SyncEngine","New document in limbo: "+n),e.cc.add(r),uc(e))}function uc(e){for(;e.cc.size>0&&e.ac.size<e.maxConcurrentLimboResolutions;){var t=e.cc.values().next().value;e.cc.delete(t);var n=new we(me.fromString(t)),r=e._c.next();e.hc.set(r,new Ks(n)),e.ac=e.ac.insert(n,r),Xo(e.remoteStore,new la(Fn(_n(n.path)),r,2,We.at))}}function oc(e,t,n){var r,i,a,u;return m().async(function(o){for(;;)switch(o.prev=o.next){case 0:if(r=Y(e),i=[],a=[],u=[],o.t0=r.oc.isEmpty(),o.t0){o.next=9;break}return r.oc.forEach(function(e,o){u.push(r.mc(o,t,n).then(function(e){if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(o.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){i.push(e);var t=$u.Ni(o.targetId,e);a.push(t)}}))}),o.next=6,m().awrap(Promise.all(u));case 6:return r.rc.Ho(i),o.next=9,m().awrap(function(e,t){var n,r,i,a,u,o,s,c;return m().async(function(l){for(;;)switch(l.prev=l.next){case 0:return n=Y(e),l.prev=1,l.next=4,m().awrap(n.persistence.runTransaction("notifyLocalViewChanges","readwrite",function(e){return Re.forEach(t,function(t){return Re.forEach(t.Ci,function(r){return n.persistence.referenceDelegate.addReference(e,t.targetId,r)}).next(function(){return Re.forEach(t.xi,function(r){return n.persistence.referenceDelegate.removeReference(e,t.targetId,r)})})})}));case 4:l.next=11;break;case 6:if(l.prev=6,l.t0=l.catch(1),Ue(l.t0)){l.next=10;break}throw l.t0;case 10:G("LocalStore","Failed to update sequence numbers: "+l.t0);case 11:r=p(t);try{for(r.s();!(i=r.n()).done;)a=i.value,u=a.targetId,a.fromCache||(o=n.Ki.get(u),s=o.snapshotVersion,c=o.withLastLimboFreeSnapshotVersion(s),n.Ki=n.Ki.insert(u,c))}catch(f){r.e(f)}finally{r.f()}case 13:case"end":return l.stop()}},null,null,[[1,6]],Promise)}(r.localStore,a));case 9:case"end":return o.stop()}},null,null,null,Promise)}function sc(e,t){var n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:if((n=Y(e)).currentUser.isEqual(t)){i.next=11;break}return G("SyncEngine","User change. New user:",t.toKey()),i.next=5,m().awrap(ro(n.localStore,t));case 5:return r=i.sent,n.currentUser=t,function(e,t){e.dc.forEach(function(e){e.forEach(function(e){e.reject(new Z(J.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.dc.clear()}(n),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),i.next=11,m().awrap(oc(n,r.Wi));case 11:case"end":return i.stop()}},null,null,null,Promise)}function cc(e,t){var n=Y(e),r=n.hc.get(t);if(r&&r.ic)return Vr().add(r.key);var i=Vr(),a=n.uc.get(t);if(!a)return i;var u,o=p(a);try{for(o.s();!(u=o.n()).done;){var s=u.value,c=n.oc.get(s);i=i.unionWith(c.view.Wu)}}catch(l){o.e(l)}finally{o.f()}return i}function lc(e,t){var n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=Y(e),a.next=3,m().awrap(fo(n.localStore,t.query,!0));case 3:return r=a.sent,i=t.view.nc(r),a.abrupt("return",(n.isPrimaryClient&&ic(n,t.targetId,i.tc),i));case 6:case"end":return a.stop()}},null,null,null,Promise)}function fc(e,t){var n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return n=Y(e),r.abrupt("return",vo(n.localStore,t).then(function(e){return oc(n,e)}));case 2:case"end":return r.stop()}},null,null,null,Promise)}function hc(e,t,n,r){var i,a;return m().async(function(u){for(;;)switch(u.prev=u.next){case 0:return i=Y(e),u.next=3,m().awrap(function(e,t){var n=Y(e),r=Y(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",function(e){return r.An(e,t).next(function(t){return t?n.localDocuments.getDocuments(e,t):Re.resolve(null)})})}(i.localStore,t));case 3:if(null===(a=u.sent)){u.next=15;break}if("pending"!==n){u.next=10;break}return u.next=8,m().awrap(ss(i.remoteStore));case 8:u.next=11;break;case 10:"acknowledged"===n||"rejected"===n?(tc(i,t,r||null),ec(i,t),function(e,t){Y(Y(e).mutationQueue).Pn(t)}(i.localStore,t)):W();case 11:return u.next=13,m().awrap(oc(i,a));case 13:u.next=16;break;case 15:G("SyncEngine","Cannot apply mutation batch with id: "+t);case 16:case"end":return u.stop()}},null,null,null,Promise)}function dc(e,t){var n,r,i,a,u,o,s,c;return m().async(function(l){for(;;)switch(l.prev=l.next){case 0:if(kc(n=Y(e)),wc(n),!0!==t||!0===n.wc){l.next=13;break}return r=n.sharedClientState.getAllActiveQueryTargets(),l.next=5,m().awrap(vc(n,r.toArray()));case 5:return i=l.sent,n.wc=!0,l.next=9,m().awrap(gs(n.remoteStore,!0));case 9:a=p(i);try{for(a.s();!(u=a.n()).done;)o=u.value,Xo(n.remoteStore,o)}catch(f){a.e(f)}finally{a.f()}l.next=25;break;case 13:if(!1!==t||!1===n.wc){l.next=25;break}return s=[],c=Promise.resolve(),n.uc.forEach(function(e,t){n.sharedClientState.isLocalQueryTarget(t)?s.push(t):c=c.then(function(){return nc(n,t),lo(n.localStore,t,!0)}),Yo(n.remoteStore,t)}),l.next=19,m().awrap(c);case 19:return l.next=21,m().awrap(vc(n,s));case 21:return function(e){var t=Y(n);t.hc.forEach(function(e,n){Yo(t.remoteStore,n)}),t.lc._s(),t.hc=new Map,t.ac=new on(we.comparator)}(),n.wc=!1,l.next=25,m().awrap(gs(n.remoteStore,!1));case 25:case"end":return l.stop()}},null,null,null,Promise)}function vc(e,t,n){var r,i,a,u,o,s,c,l,f,h,d,v,y,g;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:r=Y(e),i=[],a=[],u=p(t),n.prev=2,u.s();case 4:if((o=u.n()).done){n.next=45;break}if(s=o.value,c=void 0,!(l=r.uc.get(s))||0===l.length){n.next=34;break}return n.next=11,m().awrap(co(r.localStore,Fn(l[0])));case 11:c=n.sent,f=p(l),n.prev=13,f.s();case 15:if((h=f.n()).done){n.next=24;break}return d=h.value,v=r.oc.get(d),n.next=20,m().awrap(lc(r,v));case 20:(y=n.sent).snapshot&&a.push(y.snapshot);case 22:n.next=15;break;case 24:n.next=29;break;case 26:n.prev=26,n.t0=n.catch(13),f.e(n.t0);case 29:return n.prev=29,f.f(),n.finish(29);case 32:n.next=42;break;case 34:return n.next=36,m().awrap(ho(r.localStore,s));case 36:return g=n.sent,n.next=39,m().awrap(co(r.localStore,g));case 39:return c=n.sent,n.next=42,m().awrap(js(r,yc(g),s,!1,c.resumeToken));case 42:i.push(c);case 43:n.next=4;break;case 45:n.next=50;break;case 47:n.prev=47,n.t1=n.catch(2),u.e(n.t1);case 50:return n.prev=50,u.f(),n.finish(50);case 53:return n.abrupt("return",(r.rc.Ho(a),i));case 54:case"end":return n.stop()}},null,null,[[2,47,50,53],[13,26,29,32]],Promise)}function yc(e){return Sn(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function pc(e){var t=Y(e);return Y(Y(t.localStore).persistence).Si()}function mc(e,t,n,r){var i,a,u,o;return m().async(function(s){for(;;)switch(s.prev=s.next){case 0:if(!(i=Y(e)).wc){s.next=3;break}return s.abrupt("return",void G("SyncEngine","Ignoring unexpected query state notification."));case 3:if(!((a=i.uc.get(t))&&a.length>0)){s.next=20;break}s.t0=n,s.next="current"===s.t0?8:"not-current"===s.t0?8:"rejected"===s.t0?15:19;break;case 8:return s.next=10,m().awrap(vo(i.localStore,Un(a[0])));case 10:return u=s.sent,o=Br.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,ot.EMPTY_BYTE_STRING),s.next=14,m().awrap(oc(i,u,o));case 14:return s.abrupt("break",20);case 15:return s.next=17,m().awrap(lo(i.localStore,t,!0));case 17:return nc(i,t,r),s.abrupt("break",20);case 19:W();case 20:case"end":return s.stop()}},null,null,null,Promise)}function gc(e,t,n){var r,i,a,u,o,s,c,l,f;return m().async(function(h){for(;;)switch(h.prev=h.next){case 0:if(!(r=kc(e)).wc){h.next=46;break}i=p(t),h.prev=3,i.s();case 5:if((a=i.n()).done){h.next=21;break}if(u=a.value,!r.uc.has(u)){h.next=10;break}return G("SyncEngine","Adding an already active target "+u),h.abrupt("continue",19);case 10:return h.next=12,m().awrap(ho(r.localStore,u));case 12:return o=h.sent,h.next=15,m().awrap(co(r.localStore,o));case 15:return s=h.sent,h.next=18,m().awrap(js(r,yc(o),s.targetId,!1,s.resumeToken));case 18:Xo(r.remoteStore,s);case 19:h.next=5;break;case 21:h.next=26;break;case 23:h.prev=23,h.t0=h.catch(3),i.e(h.t0);case 26:return h.prev=26,i.f(),h.finish(26);case 29:c=p(n),h.prev=30,f=function(){var e;return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(e=l.value,t.t0=r.uc.has(e),!t.t0){t.next=5;break}return t.next=5,m().awrap(lo(r.localStore,e,!1).then(function(){Yo(r.remoteStore,e),nc(r,e)}).catch(Le));case 5:case"end":return t.stop()}},null,null,null,Promise)},c.s();case 33:if((l=c.n()).done){h.next=38;break}return h.next=36,m().awrap(f());case 36:h.next=33;break;case 38:h.next=43;break;case 40:h.prev=40,h.t1=h.catch(30),c.e(h.t1);case 43:return h.prev=43,c.f(),h.finish(43);case 46:case"end":return h.stop()}},null,null,[[3,23,26,29],[30,40,43,46]],Promise)}function kc(e){var t=Y(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Hs.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=cc.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Ys.bind(null,t),t.rc.Ho=Ns.bind(null,t.eventManager),t.rc.gc=Cs.bind(null,t.eventManager),t}function wc(e){var t=Y(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Js.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Zs.bind(null,t),t}function xc(e,t,n){var r=Y(e);(function(e,t,n){var r,i,a,u,o;return m().async(function(s){for(;;)switch(s.prev=s.next){case 0:return s.prev=0,s.next=3,m().awrap(t.getMetadata());case 3:return r=s.sent,s.next=6,m().awrap(function(e,t){var n=Y(e),r=ri(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",function(e){return n.$s.getBundleMetadata(e,t.id)}).then(function(e){return!!e&&e.createTime.compareTo(r)>=0})}(e.localStore,r));case 6:if(!s.sent){s.next=11;break}return s.next=9,m().awrap(t.close());case 9:return n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),s.abrupt("return",Promise.resolve(new Set));case 11:return n._updateProgress(Os(r)),i=new Ms(r,e.localStore,t.Tt),s.next=15,m().awrap(t.yc());case 15:a=s.sent;case 16:if(!a){s.next=26;break}return s.next=19,m().awrap(i.Bu(a));case 19:return(u=s.sent)&&n._updateProgress(u),s.next=23,m().awrap(t.yc());case 23:a=s.sent;case 24:s.next=16;break;case 26:return s.next=28,m().awrap(i.complete());case 28:return o=s.sent,s.next=31,m().awrap(oc(e,o.Uu,void 0));case 31:return s.next=33,m().awrap(function(e,t){var n=Y(e);return n.persistence.runTransaction("Save bundle","readwrite",function(e){return n.$s.saveBundleMetadata(e,t)})}(e.localStore,r));case 33:return n._completeWith(o.progress),s.abrupt("return",Promise.resolve(o.qu));case 37:return s.prev=37,s.t0=s.catch(0),s.abrupt("return",(j("SyncEngine","Loading bundle failed with ".concat(s.t0)),n._failWith(s.t0),Promise.resolve(new Set)));case 40:case"end":return s.stop()}},null,null,[[0,37]],Promise)})(r,t,n).then(function(e){r.sharedClientState.notifyBundleLoaded(e)})}var bc=function(){function e(){P(this,e),this.synchronizeTabs=!1}return L(e,[{key:"initialize",value:function(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return this.Tt=Vo(e.databaseInfo.databaseId),this.sharedClientState=this.Ic(e),this.persistence=this.Tc(e),t.next=5,m().awrap(this.persistence.start());case 5:this.localStore=this.Ec(e),this.gcScheduler=this.Ac(e,this.localStore),this.indexBackfillerScheduler=this.Rc(e,this.localStore);case 8:case"end":return t.stop()}},null,this,null,Promise)}},{key:"Ac",value:function(e,t){return null}},{key:"Rc",value:function(e,t){return null}},{key:"Ec",value:function(e){return no(this.persistence,new eo,e.initialUser,this.Tt)}},{key:"Tc",value:function(e){return new Gu(ju.qs,this.Tt)}},{key:"Ic",value:function(e){return new _o}},{key:"terminate",value:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return this.gcScheduler&&this.gcScheduler.stop(),e.next=3,m().awrap(this.sharedClientState.shutdown());case 3:return e.next=5,m().awrap(this.persistence.shutdown());case 5:case"end":return e.stop()}},null,this,null,Promise)}}]),e}(),Ic=function(e){g(n,bc);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this)).Pc=e,a.cacheSizeBytes=r,a.forceOwnership=i,a.synchronizeTabs=!1,a}return L(n,[{key:"initialize",value:function(e){var t=this;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,m().awrap(o(T(n.prototype),"initialize",this).call(this,e));case 2:return r.next=4,m().awrap(this.Pc.initialize(this,e));case 4:return r.next=6,m().awrap(wc(this.Pc.syncEngine));case 6:return r.next=8,m().awrap(ss(this.Pc.remoteStore));case 8:return r.next=10,m().awrap(this.persistence.di(function(){return t.gcScheduler&&!t.gcScheduler.started&&t.gcScheduler.start(),t.indexBackfillerScheduler&&!t.indexBackfillerScheduler.started&&t.indexBackfillerScheduler.start(),Promise.resolve()}));case 10:case"end":return r.stop()}},null,this,null,Promise)}},{key:"Ec",value:function(e){return no(this.persistence,new eo,e.initialUser,this.Tt)}},{key:"Ac",value:function(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new wu(n,e.asyncQueue,t)}},{key:"Rc",value:function(e,t){var n=new ze(t,this.persistence);return new je(e.asyncQueue,n)}},{key:"Tc",value:function(e){var t=Zu(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?au.withCacheSize(this.cacheSizeBytes):au.DEFAULT;return new Xu(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,Mo(),Oo(),this.Tt,this.sharedClientState,!!this.forceOwnership)}},{key:"Ic",value:function(e){return new _o}}]),n}(),Tc=function(e){g(n,Ic);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e,r,!1)).Pc=e,i.cacheSizeBytes=r,i.synchronizeTabs=!0,i}return L(n,[{key:"initialize",value:function(e){var t,r=this;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,m().awrap(o(T(n.prototype),"initialize",this).call(this,e));case 2:if(t=this.Pc.syncEngine,i.t0=this.sharedClientState instanceof So,!i.t0){i.next=8;break}return this.sharedClientState.syncEngine={Br:hc.bind(null,t),Lr:mc.bind(null,t),qr:gc.bind(null,t),Si:pc.bind(null,t),Fr:fc.bind(null,t)},i.next=8,m().awrap(this.sharedClientState.start());case 8:return i.next=10,m().awrap(this.persistence.di(function(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,m().awrap(dc(r.Pc.syncEngine,e));case 2:r.gcScheduler&&(e&&!r.gcScheduler.started?r.gcScheduler.start():e||r.gcScheduler.stop()),r.indexBackfillerScheduler&&(e&&!r.indexBackfillerScheduler.started?r.indexBackfillerScheduler.start():e||r.indexBackfillerScheduler.stop());case 4:case"end":return t.stop()}},null,null,null,Promise)}));case 10:case"end":return i.stop()}},null,this,null,Promise)}},{key:"Ic",value:function(e){var t=Mo();if(!So.C(t))throw new Z(J.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=Zu(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new So(t,e.asyncQueue,n,e.clientId,e.initialUser)}}]),n}(),Ec=function(){function e(){P(this,e)}return L(e,[{key:"initialize",value:function(e,t){var n=this;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(r.t0=this.localStore,r.t0){r.next=12;break}return 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=function(e){return Xs(n.syncEngine,e,1)},this.remoteStore.remoteSyncer.handleCredentialChange=sc.bind(null,this.syncEngine),r.next=12,m().awrap(gs(this.remoteStore,this.syncEngine.isPrimaryClient));case 12:case"end":return r.stop()}},null,this,null,Promise)}},{key:"createEventManager",value:function(e){return new _s}},{key:"createDatastore",value:function(e){var t,n=Vo(e.databaseInfo.databaseId),r=(t=e.databaseInfo,new Ro(t));return function(e,t,n,r){return new Go(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,r,n)}},{key:"createRemoteStore",value:function(e){var t,n,r,i,a,u=this;return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=function(e){return Xs(u.syncEngine,e,0)},a=Do.C()?new Do:new Ao,new zo(t,n,r,i,a)}},{key:"createSyncEngine",value:function(e,t){return function(e,t,n,r,i,a,u){var o=new Gs(e,t,n,r,i,a);return u&&(o.wc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}},{key:"terminate",value:function(){return e=this.remoteStore,m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return t=Y(e),G("RemoteStore","RemoteStore shutting down."),t.mu.add(5),n.next=5,m().awrap(Ho(t));case 5:t.yu.shutdown(),t.pu.set("Unknown");case 7:case"end":return n.stop()}},null,null,null,Promise);var e,t}}]),e}();function Sc(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10240,n=0;return{read:function(){var r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:if(!(n<e.byteLength)){i.next=3;break}return r={value:e.slice(n,n+t),done:!1},i.abrupt("return",(n+=t,r));case 3:return i.abrupt("return",{done:!0});case 4:case"end":return i.stop()}},null,null,null,Promise)},cancel:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}},null,null,null,Promise)},releaseLock:function(){},closed:Promise.resolve()}}var _c=function(){function e(t){P(this,e),this.observer=t,this.muted=!1}return L(e,[{key:"next",value:function(e){this.observer.next&&this.vc(this.observer.next,e)}},{key:"error",value:function(e){this.observer.error?this.vc(this.observer.error,e):Q("Uncaught Error in snapshot listener:",e.toString())}},{key:"bc",value:function(){this.muted=!0}},{key:"vc",value:function(e,t){var n=this;this.muted||setTimeout(function(){n.muted||e(t)},0)}}]),e}(),Ac=function(){function e(t,n){var r=this;P(this,e),this.Vc=t,this.Tt=n,this.metadata=new $,this.buffer=new Uint8Array,this.Sc=new TextDecoder("utf-8"),this.Dc().then(function(e){e&&e.Ou()?r.metadata.resolve(e.Mu.metadata):r.metadata.reject(new Error("The first element of the bundle is not a metadata, it is\n ".concat(JSON.stringify(null==e?void 0:e.Mu))))},function(e){return r.metadata.reject(e)})}return L(e,[{key:"close",value:function(){return this.Vc.cancel()}},{key:"getMetadata",value:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.metadata.promise);case 1:case"end":return e.stop()}},null,this,null,Promise)}},{key:"yc",value:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,m().awrap(this.getMetadata());case 2:return e.abrupt("return",this.Dc());case 3:case"end":return e.stop()}},null,this,null,Promise)}},{key:"Dc",value:function(){var e,t,n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,m().awrap(this.Cc());case 2:if(null!==(e=i.sent)){i.next=5;break}return i.abrupt("return",null);case 5:return t=this.Sc.decode(e),n=Number(t),isNaN(n)&&this.xc("length string (".concat(t,") is not valid number")),i.next=9,m().awrap(this.Nc(n));case 9:return r=i.sent,i.abrupt("return",new Ls(JSON.parse(r),e.length+n));case 11:case"end":return i.stop()}},null,this,null,Promise)}},{key:"kc",value:function(){return this.buffer.findIndex(function(e){return e==="{".charCodeAt(0)})}},{key:"Cc",value:function(){var e,t;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!(this.kc()<0)){n.next=7;break}return n.next=3,m().awrap(this.$c());case 3:if(!n.sent){n.next=5;break}return n.abrupt("break",7);case 5:n.next=0;break;case 7:if(0!==this.buffer.length){n.next=9;break}return n.abrupt("return",null);case 9:return(e=this.kc())<0&&this.xc("Reached the end of bundle when a length string is expected."),t=this.buffer.slice(0,e),n.abrupt("return",(this.buffer=this.buffer.slice(e),t));case 13:case"end":return n.stop()}},null,this,null,Promise)}},{key:"Nc",value:function(e){var t;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(!(this.buffer.length<e)){n.next=8;break}return n.next=3,m().awrap(this.$c());case 3:if(n.t0=n.sent,!n.t0){n.next=6;break}this.xc("Reached the end of bundle when more is expected.");case 6:n.next=0;break;case 8:return t=this.Sc.decode(this.buffer.slice(0,e)),n.abrupt("return",(this.buffer=this.buffer.slice(e),t));case 10:case"end":return n.stop()}},null,this,null,Promise)}},{key:"xc",value:function(e){throw this.Vc.cancel(),new Error("Invalid bundle format: ".concat(e))}},{key:"$c",value:function(){var e,t;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,m().awrap(this.Vc.read());case 2:return(e=n.sent).done||((t=new Uint8Array(this.buffer.length+e.value.length)).set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t),n.abrupt("return",e.done);case 5:case"end":return n.stop()}},null,this,null,Promise)}}]),e}(),Dc=function(){function e(t){P(this,e),this.datastore=t,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}return L(e,[{key:"lookup",value:function(e){var t,n=this;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(this.ensureCommitNotCalled(),!(this.mutations.length>0)){r.next=2;break}throw new Z(J.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");case 2:return r.next=4,m().awrap(function(e,t){var n,r,i,a,u,o;return m().async(function(s){for(;;)switch(s.prev=s.next){case 0:return n=Y(e),r=li(n.Tt)+"/documents",i={documents:t.map(function(e){return ui(n.Tt,e)})},s.next=5,m().awrap(n.mo("BatchGetDocuments",r,i,t.length));case 5:return a=s.sent,u=new Map,a.forEach(function(e){var t=vi(n.Tt,e);u.set(t.key.toString(),t)}),o=[],s.abrupt("return",(t.forEach(function(e){var t=u.get(e.toString());H(!!t),o.push(t)}),o));case 10:case"end":return s.stop()}},null,null,null,Promise)}(this.datastore,e));case 4:return t=r.sent,r.abrupt("return",(t.forEach(function(e){return n.recordVersion(e)}),t));case 6:case"end":return r.stop()}},null,this,null,Promise)}},{key:"set",value:function(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}},{key:"update",value:function(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}},{key:"delete",value:function(e){this.write(new br(e,this.precondition(e))),this.writtenDocs.add(e.toString())}},{key:"commit",value:function(){var e,t=this;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(this.ensureCommitNotCalled(),!this.lastWriteError){n.next=2;break}throw this.lastWriteError;case 2:return e=this.readVersions,this.mutations.forEach(function(t){e.delete(t.key.toString())}),e.forEach(function(e,n){var r=we.fromPath(n);t.mutations.push(new Ir(r,t.precondition(r)))}),n.next=7,m().awrap(function(e,t){var n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=Y(e),r=li(n.Tt)+"/documents",i={writes:t.map(function(e){return pi(n.Tt,e)})},a.next=3,m().awrap(n.lo("Commit",r,i));case 3:case"end":return a.stop()}},null,null,null,Promise)}(this.datastore,this.mutations));case 7:this.committed=!0;case 8:case"end":return n.stop()}},null,this,null,Promise)}},{key:"recordVersion",value:function(e){var t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw W();t=ye.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new Z(J.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}},{key:"precondition",value:function(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(ye.min())?or.exists(!1):or.updateTime(t):or.none()}},{key:"preconditionForUpdate",value:function(e){var t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(ye.min()))throw new Z(J.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return or.updateTime(t)}return or.exists(!0)}},{key:"write",value:function(e){this.ensureCommitNotCalled(),this.mutations.push(e)}},{key:"ensureCommitNotCalled",value:function(){}}]),e}(),Nc=function(){function e(t,n,r,i,a){P(this,e),this.asyncQueue=t,this.datastore=n,this.options=r,this.updateFunction=i,this.deferred=a,this.Mc=r.maxAttempts,this.ko=new qo(this.asyncQueue,"transaction_retry")}return L(e,[{key:"run",value:function(){this.Mc-=1,this.Oc()}},{key:"Oc",value:function(){var e=this;this.ko.vo(function(){var t,n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:t=new Dc(e.datastore),(n=e.Fc(t))&&n.then(function(n){e.asyncQueue.enqueueAndForget(function(){return t.commit().then(function(){e.deferred.resolve(n)}).catch(function(t){e.Bc(t)})})}).catch(function(t){e.Bc(t)});case 2:case"end":return r.stop()}},null,null,null,Promise)})}},{key:"Fc",value:function(e){try{var t=this.updateFunction(e);return!nt(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}},{key:"Bc",value:function(e){var t=this;this.Mc>0&&this.Lc(e)?(this.Mc-=1,this.asyncQueue.enqueueAndForget(function(){return t.Oc(),Promise.resolve()})):this.deferred.reject(e)}},{key:"Lc",value:function(e){if("FirebaseError"===e.name){var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!Er(t)}return!1}}]),e}(),Cc=function(){function e(t,n,r,i){var a=this;P(this,e),this.authCredentials=t,this.appCheckCredentials=n,this.asyncQueue=r,this.databaseInfo=i,this.user=V.UNAUTHENTICATED,this.clientId=le.R(),this.authCredentialListener=function(){return Promise.resolve()},this.appCheckCredentialListener=function(){return Promise.resolve()},this.authCredentials.start(r,function(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return G("FirestoreClient","Received user=",e.uid),t.next=3,m().awrap(a.authCredentialListener(e));case 3:a.user=e;case 4:case"end":return t.stop()}},null,null,null,Promise)}),this.appCheckCredentials.start(r,function(e){return G("FirestoreClient","Received new app check token=",e),a.appCheckCredentialListener(e,a.user)})}return L(e,[{key:"getConfiguration",value:function(){return m().async(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100});case 1:case"end":return e.stop()}},null,this,null,Promise)}},{key:"setCredentialChangeListener",value:function(e){this.authCredentialListener=e}},{key:"setAppCheckTokenChangeListener",value:function(e){this.appCheckCredentialListener=e}},{key:"verifyNotTerminated",value:function(){if(this.asyncQueue.isShuttingDown)throw new Z(J.FAILED_PRECONDITION,"The client has already been terminated.")}},{key:"terminate",value:function(){var e=this;this.asyncQueue.enterRestrictedMode();var t=new $;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(function(){var n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:if(r.prev=0,r.t0=e.onlineComponents,!r.t0){r.next=5;break}return r.next=5,m().awrap(e.onlineComponents.terminate());case 5:if(r.t1=e.offlineComponents,!r.t1){r.next=9;break}return r.next=9,m().awrap(e.offlineComponents.terminate());case 9:e.authCredentials.shutdown(),e.appCheckCredentials.shutdown(),t.resolve(),r.next=18;break;case 14:r.prev=14,r.t2=r.catch(0),n=bs(r.t2,"Failed to shutdown persistence"),t.reject(n);case 18:case"end":return r.stop()}},null,null,[[0,14]],Promise)}),t.promise}}]),e}();function Pc(e,t){var n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return e.asyncQueue.verifyOperationInProgress(),G("FirestoreClient","Initializing OfflineComponentProvider"),i.next=3,m().awrap(e.getConfiguration());case 3:return n=i.sent,i.next=6,m().awrap(t.initialize(n));case 6:r=n.initialUser,e.setCredentialChangeListener(function(e){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(n.t0=r.isEqual(e),n.t0){n.next=5;break}return n.next=4,m().awrap(ro(t.localStore,e));case 4:r=e;case 5:case"end":return n.stop()}},null,null,null,Promise)}),t.persistence.setDatabaseDeletedListener(function(){return e.terminate()}),e.offlineComponents=t;case 8:case"end":return i.stop()}},null,null,null,Promise)}function Fc(e,t){var n,r;return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return e.asyncQueue.verifyOperationInProgress(),i.next=3,m().awrap(Lc(e));case 3:return n=i.sent,G("FirestoreClient","Initializing OnlineComponentProvider"),i.next=7,m().awrap(e.getConfiguration());case 7:return r=i.sent,i.next=10,m().awrap(t.initialize(n,r));case 10:e.setCredentialChangeListener(function(e){return ms(t.remoteStore,e)}),e.setAppCheckTokenChangeListener(function(e,n){return ms(t.remoteStore,n)}),e.onlineComponents=t;case 13:case"end":return i.stop()}},null,null,null,Promise)}function Lc(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=e.offlineComponents,t.t0){t.next=5;break}return G("FirestoreClient","Using default OfflineComponentProvider"),t.next=5,m().awrap(Pc(e,new bc));case 5:return t.abrupt("return",e.offlineComponents);case 6:case"end":return t.stop()}},null,null,null,Promise)}function Rc(e){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=e.onlineComponents,t.t0){t.next=5;break}return G("FirestoreClient","Using default OnlineComponentProvider"),t.next=5,m().awrap(Fc(e,new Ec));case 5:return t.abrupt("return",e.onlineComponents);case 6:case"end":return t.stop()}},null,null,null,Promise)}function Mc(e){return Lc(e).then(function(e){return e.persistence})}function Oc(e){return Lc(e).then(function(e){return e.localStore})}function Vc(e){return Rc(e).then(function(e){return e.remoteStore})}function qc(e){return Rc(e).then(function(e){return e.syncEngine})}function Uc(e){return Rc(e).then(function(e){return e.datastore})}function Bc(e){var t,n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,m().awrap(Rc(e));case 2:return t=r.sent,n=t.eventManager,r.abrupt("return",(n.onListen=Qs.bind(null,t.syncEngine),n.onUnlisten=zs.bind(null,t.syncEngine),n));case 5:case"end":return r.stop()}},null,null,null,Promise)}function Kc(e){return e.asyncQueue.enqueue(function(){var t,n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,m().awrap(Mc(e));case 2:return t=r.sent,r.next=5,m().awrap(Vc(e));case 5:return n=r.sent,r.abrupt("return",(t.setNetworkEnabled(!0),function(e){var t=Y(n);return t.mu.delete(0),Wo(t)}()));case 7:case"end":return r.stop()}},null,null,null,Promise)})}function Gc(e){return e.asyncQueue.enqueue(function(){var t,n;return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,m().awrap(Mc(e));case 2:return t=r.sent,r.next=5,m().awrap(Vc(e));case 5:return n=r.sent,r.abrupt("return",(t.setNetworkEnabled(!1),function(e){var t;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return(t=Y(e)).mu.add(0),n.next=4,m().awrap(Ho(t));case 4:t.pu.set("Offline");case 5:case"end":return n.stop()}},null,null,null,Promise)}(n)));case 7:case"end":return r.stop()}},null,null,null,Promise)})}function Qc(e,t){var n=new $;return e.asyncQueue.enqueueAndForget(function(){return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.t0=function(e,t,n){var r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.prev=0,a.next=3,m().awrap(function(e,t){var n=Y(e);return n.persistence.runTransaction("read document","readonly",function(e){return n.localDocuments.getDocument(e,t)})}(e,t));case 3:(r=a.sent).isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new Z(J.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")),a.next=11;break;case 7:a.prev=7,a.t0=a.catch(0),i=bs(a.t0,"Failed to get document '".concat(t," from cache")),n.reject(i);case 11:case"end":return a.stop()}},null,null,[[0,7]],Promise)},r.next=3,m().awrap(Oc(e));case 3:return r.t1=r.sent,r.t2=t,r.t3=n,r.abrupt("return",(0,r.t0)(r.t1,r.t2,r.t3));case 7:case"end":return r.stop()}},null,null,null,Promise)}),n.promise}function jc(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new $;return e.asyncQueue.enqueueAndForget(function(){return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.t0=function(e,t,n,r,i){var a=new _c({next:function(a){t.enqueueAndForget(function(){return Ds(e,u)});var o=a.docs.has(n);!o&&a.fromCache?i.reject(new Z(J.UNAVAILABLE,"Failed to get document because the client is offline.")):o&&a.fromCache&&r&&"server"===r.source?i.reject(new Z(J.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(a)},error:function(e){return i.reject(e)}}),u=new Fs(_n(n.path),a,{includeMetadataChanges:!0,$u:!0});return As(e,u)},i.next=3,m().awrap(Bc(e));case 3:return i.t1=i.sent,i.t2=e.asyncQueue,i.t3=t,i.t4=n,i.t5=r,i.abrupt("return",(0,i.t0)(i.t1,i.t2,i.t3,i.t4,i.t5));case 9:case"end":return i.stop()}},null,null,null,Promise)}),r.promise}function zc(e,t){var n=new $;return e.asyncQueue.enqueueAndForget(function(){return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.t0=function(e,t,n){var r,i,a,u,o;return m().async(function(s){for(;;)switch(s.prev=s.next){case 0:return s.prev=0,s.next=3,m().awrap(fo(e,t,!0));case 3:r=s.sent,i=new Us(t,r.Yi),a=i.Hu(r.documents),u=i.applyChanges(a,!1),n.resolve(u.snapshot),s.next=14;break;case 10:s.prev=10,s.t0=s.catch(0),o=bs(s.t0,"Failed to execute query '".concat(t," against cache")),n.reject(o);case 14:case"end":return s.stop()}},null,null,[[0,10]],Promise)},r.next=3,m().awrap(Oc(e));case 3:return r.t1=r.sent,r.t2=t,r.t3=n,r.abrupt("return",(0,r.t0)(r.t1,r.t2,r.t3));case 7:case"end":return r.stop()}},null,null,null,Promise)}),n.promise}function Wc(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new $;return e.asyncQueue.enqueueAndForget(function(){return m().async(function(i){for(;;)switch(i.prev=i.next){case 0:return i.t0=function(e,t,n,r,i){var a=new _c({next:function(n){t.enqueueAndForget(function(){return Ds(e,u)}),n.fromCache&&"server"===r.source?i.reject(new Z(J.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:function(e){return i.reject(e)}}),u=new Fs(n,a,{includeMetadataChanges:!0,$u:!0});return As(e,u)},i.next=3,m().awrap(Bc(e));case 3:return i.t1=i.sent,i.t2=e.asyncQueue,i.t3=t,i.t4=n,i.t5=r,i.abrupt("return",(0,i.t0)(i.t1,i.t2,i.t3,i.t4,i.t5));case 9:case"end":return i.stop()}},null,null,null,Promise)}),r.promise}function Hc(e,t){var n=new _c(t);return e.asyncQueue.enqueueAndForget(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=function(e,t){Y(e).vu.add(t),t.next()},t.next=3,m().awrap(Bc(e));case 3:return t.t1=t.sent,t.t2=n,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)}),function(){n.bc(),e.asyncQueue.enqueueAndForget(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=function(e,t){Y(e).vu.delete(t)},t.next=3,m().awrap(Bc(e));case 3:return t.t1=t.sent,t.t2=n,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)})}}function Xc(e,t,n,r){var i=function(e,t){return function(e,t){return new Ac(e,t)}(function(e,t){if(e instanceof Uint8Array)return Sc(e,t);if(e instanceof ArrayBuffer)return Sc(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}("string"==typeof e?(new TextEncoder).encode(e):e),t)}(n,Vo(t));e.asyncQueue.enqueueAndForget(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=xc,t.next=3,m().awrap(qc(e));case 3:t.t1=t.sent,t.t2=i,t.t3=r,(0,t.t0)(t.t1,t.t2,t.t3);case 7:case"end":return t.stop()}},null,null,null,Promise)})}function Yc(e,t){return e.asyncQueue.enqueue(function(){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.t0=function(e,t){var n=Y(e);return n.persistence.runTransaction("Get named query","readonly",function(e){return n.$s.getNamedQuery(e,t)})},n.next=3,m().awrap(Oc(e));case 3:return n.t1=n.sent,n.t2=t,n.abrupt("return",(0,n.t0)(n.t1,n.t2));case 6:case"end":return n.stop()}},null,null,null,Promise)})}var Jc=new Map;function Zc(e,t,n){if(!n)throw new Z(J.INVALID_ARGUMENT,"Function ".concat(e,"() cannot be called with an empty ").concat(t,"."))}function $c(e,t,n,r){if(!0===t&&!0===r)throw new Z(J.INVALID_ARGUMENT,"".concat(e," and ").concat(n," cannot be used together."))}function el(e){if(!we.isDocumentKey(e))throw new Z(J.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but ".concat(e," has ").concat(e.length,"."))}function tl(e){if(we.isDocumentKey(e))throw new Z(J.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but ".concat(e," has ").concat(e.length,"."))}function nl(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e="".concat(e.substring(0,20),"...")),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==C(e)){if(e instanceof Array)return"an array";var t=function(e){return e.constructor?e.constructor.name:null}(e);return t?"a custom ".concat(t," object"):"an object"}return"function"==typeof e?"a function":W()}function rl(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new Z(J.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=nl(e);throw new Z(J.INVALID_ARGUMENT,"Expected type '".concat(t.name,"', but it was: ").concat(n))}return e}function il(e,t){if(t<=0)throw new Z(J.INVALID_ARGUMENT,"Function ".concat(e,"() requires a positive number, but it was: ").concat(t,"."))}var al=function(){function e(t){var n;if(P(this,e),void 0===t.host){if(void 0!==t.ssl)throw new Z(J.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=t.host,this.ssl=null===(n=t.ssl)||void 0===n||n;if(this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,void 0===t.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new Z(J.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=t.cacheSizeBytes}this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.useFetchStreams=!!t.useFetchStreams,$c("experimentalForceLongPolling",t.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",t.experimentalAutoDetectLongPolling)}return L(e,[{key:"isEqual",value:function(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}}]),e}(),ul=function(){function e(t,n,r,i){P(this,e),this._authCredentials=t,this._appCheckCredentials=n,this._databaseId=r,this._app=i,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new al({}),this._settingsFrozen=!1}return L(e,[{key:"app",get:function(){if(!this._app)throw new Z(J.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}},{key:"_initialized",get:function(){return this._settingsFrozen}},{key:"_terminated",get:function(){return void 0!==this._terminateTask}},{key:"_setSettings",value:function(e){if(this._settingsFrozen)throw new Z(J.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 al(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new te;switch(e.type){case"gapi":var t=e.client;return new ae(t,e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new Z(J.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}},{key:"_getSettings",value:function(){return this._settings}},{key:"_freezeSettings",value:function(){return this._settingsFrozen=!0,this._settings}},{key:"_delete",value:function(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}},{key:"toJSON",value:function(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}},{key:"_terminate",value:function(){return e=this,(t=Jc.get(e))&&(G("ComponentProvider","Removing Datastore"),Jc.delete(e),t.terminate()),Promise.resolve();var e,t}}]),e}();function ol(e,t,n){var r,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},u=(e=rl(e,ul))._getSettings();if("firestore.googleapis.com"!==u.host&&u.host!==t&&j("Host has been set in both settings() and useEmulator(), emulator host will be used"),e._setSettings(Object.assign(Object.assign({},u),{host:"".concat(t,":").concat(n),ssl:!1})),i.mockUserToken){var o,s;if("string"==typeof i.mockUserToken)o=i.mockUserToken,s=V.MOCK_USER;else{o=(0,a.createMockUserToken)(i.mockUserToken,null===(r=e._app)||void 0===r?void 0:r.options.projectId);var c=i.mockUserToken.sub||i.mockUserToken.user_id;if(!c)throw new Z(J.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");s=new V(c)}e._authCredentials=new ne(new ee(o,s))}}var sl=function(){function e(t,n,r){P(this,e),this.converter=n,this._key=r,this.type="document",this.firestore=t}return L(e,[{key:"_path",get:function(){return this._key.path}},{key:"id",get:function(){return this._key.path.lastSegment()}},{key:"path",get:function(){return this._key.path.canonicalString()}},{key:"parent",get:function(){return new ll(this.firestore,this.converter,this._key.path.popLast())}},{key:"withConverter",value:function(t){return new e(this.firestore,t,this._key)}}]),e}();exports.DocumentReference=sl;var cl=function(){function e(t,n,r){P(this,e),this.converter=n,this._query=r,this.type="query",this.firestore=t}return L(e,[{key:"withConverter",value:function(t){return new e(this.firestore,t,this._query)}}]),e}();exports.Query=cl;var ll=function(e){g(n,cl);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this,e,r,_n(i)))._path=i,a.type="collection",a}return L(n,[{key:"id",get:function(){return this._query.path.lastSegment()}},{key:"path",get:function(){return this._query.path.canonicalString()}},{key:"parent",get:function(){var e=this._path.popLast();return e.isEmpty()?null:new sl(this.firestore,null,new we(e))}},{key:"withConverter",value:function(e){return new n(this.firestore,e,this._path)}}]),n}();function fl(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=(0,a.getModularInstance)(e),Zc("collection","path",t),e instanceof ul){var u=me.fromString.apply(me,[t].concat(r));return tl(u),new ll(e,null,u)}if(!(e instanceof sl||e instanceof ll))throw new Z(J.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");var o=e._path.child(me.fromString.apply(me,[t].concat(r)));return tl(o),new ll(e.firestore,null,o)}function hl(e,t){if(e=rl(e,ul),Zc("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new Z(J.INVALID_ARGUMENT,"Invalid collection ID '".concat(t,"' passed to function collectionGroup(). Collection IDs must not contain '/'."));return new cl(e,null,function(e){return new En(me.emptyPath(),e)}(t))}function dl(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];if(e=(0,a.getModularInstance)(e),1===arguments.length&&(t=le.R()),Zc("doc","path",t),e instanceof ul){var u=me.fromString.apply(me,[t].concat(r));return el(u),new sl(e,null,new we(u))}if(!(e instanceof sl||e instanceof ll))throw new Z(J.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");var o=e._path.child(me.fromString.apply(me,[t].concat(r)));return el(o),new sl(e.firestore,e instanceof ll?e.converter:null,new we(o))}function vl(e,t){return e=(0,a.getModularInstance)(e),t=(0,a.getModularInstance)(t),(e instanceof sl||e instanceof ll)&&(t instanceof sl||t instanceof ll)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function yl(e,t){return e=(0,a.getModularInstance)(e),t=(0,a.getModularInstance)(t),e instanceof cl&&t instanceof cl&&e.firestore===t.firestore&&Mn(e._query,t._query)&&e.converter===t.converter}exports.CollectionReference=ll;var pl=function(){function e(){var t=this;P(this,e),this.qc=Promise.resolve(),this.Uc=[],this.Kc=!1,this.Gc=[],this.Qc=null,this.jc=!1,this.zc=!1,this.Wc=[],this.ko=new qo(this,"async_queue_retry"),this.Hc=function(){var e=Oo();e&&G("AsyncQueue","Visibility state changed to "+e.visibilityState),t.ko.Vo()};var n=Oo();n&&"function"==typeof n.addEventListener&&n.addEventListener("visibilitychange",this.Hc)}return L(e,[{key:"isShuttingDown",get:function(){return this.Kc}},{key:"enqueueAndForget",value:function(e){this.enqueue(e)}},{key:"enqueueAndForgetEvenWhileRestricted",value:function(e){this.Jc(),this.Yc(e)}},{key:"enterRestrictedMode",value:function(e){if(!this.Kc){this.Kc=!0,this.zc=e||!1;var t=Oo();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Hc)}}},{key:"enqueue",value:function(e){var t=this;if(this.Jc(),this.Kc)return new Promise(function(){});var n=new $;return this.Yc(function(){return t.Kc&&t.zc?Promise.resolve():(e().then(n.resolve,n.reject),n.promise)}).then(function(){return n.promise})}},{key:"enqueueRetryable",value:function(e){var t=this;this.enqueueAndForget(function(){return t.Uc.push(e),t.Zc()})}},{key:"Zc",value:function(){var e=this;return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:if(0===this.Uc.length){t.next=14;break}return t.prev=1,t.next=4,m().awrap(this.Uc[0]());case 4:this.Uc.shift(),this.ko.reset(),t.next=13;break;case 8:if(t.prev=8,t.t0=t.catch(1),Ue(t.t0)){t.next=12;break}throw t.t0;case 12:G("AsyncQueue","Operation failed with retryable error: "+t.t0);case 13:this.Uc.length>0&&this.ko.vo(function(){return e.Zc()});case 14:case"end":return t.stop()}},null,this,[[1,8]],Promise)}},{key:"Yc",value:function(e){var t=this,n=this.qc.then(function(){return t.jc=!0,e().catch(function(e){throw t.Qc=e,t.jc=!1,Q("INTERNAL UNHANDLED ERROR: ",function(e){var t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(function(e){return t.jc=!1,e})});return this.qc=n,n}},{key:"enqueueAfterDelay",value:function(e,t,n){var r=this;this.Jc(),this.Wc.indexOf(e)>-1&&(t=0);var i=xs.createAndSchedule(this,e,t,n,function(e){return r.Xc(e)});return this.Gc.push(i),i}},{key:"Jc",value:function(){this.Qc&&W()}},{key:"verifyOperationInProgress",value:function(){}},{key:"ta",value:function(){var e;return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return e=this.qc,t.next=3,m().awrap(e);case 3:if(e!==this.qc){t.next=0;break}case 4:case"end":return t.stop()}},null,this,null,Promise)}},{key:"ea",value:function(e){var t,n=p(this.Gc);try{for(n.s();!(t=n.n()).done;){if(t.value.timerId===e)return!0}}catch(r){n.e(r)}finally{n.f()}return!1}},{key:"na",value:function(e){var t=this;return this.ta().then(function(){t.Gc.sort(function(e,t){return e.targetTimeMs-t.targetTimeMs});var n,r=p(t.Gc);try{for(r.s();!(n=r.n()).done;){var i=n.value;if(i.skipDelay(),"all"!==e&&i.timerId===e)break}}catch(a){r.e(a)}finally{r.f()}return t.ta()})}},{key:"sa",value:function(e){this.Wc.push(e)}},{key:"Xc",value:function(e){var t=this.Gc.indexOf(e);this.Gc.splice(t,1)}}]),e}();function ml(e){return function(e,t){if("object"!=C(e)||null===e)return!1;var n,r=e,i=p(["next","error","complete"]);try{for(i.s();!(n=i.n()).done;){var a=n.value;if(a in r&&"function"==typeof r[a])return!0}}catch(u){i.e(u)}finally{i.f()}return!1}(e)}var gl=function(){function e(){P(this,e),this._progressObserver={},this._taskCompletionResolver=new $,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}return L(e,[{key:"onProgress",value:function(e,t,n){this._progressObserver={next:e,error:t,complete:n}}},{key:"catch",value:function(e){return this._taskCompletionResolver.promise.catch(e)}},{key:"then",value:function(e,t){return this._taskCompletionResolver.promise.then(e,t)}},{key:"_completeWith",value:function(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}},{key:"_failWith",value:function(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}},{key:"_updateProgress",value:function(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}]),e}();exports.LoadBundleTask=gl;var kl=-1;exports.CACHE_SIZE_UNLIMITED=kl;var wl=function(e){g(n,ul);var t=w(n);function n(e,r,i,a){var u;return P(this,n),(u=t.call(this,e,r,i,a)).type="firestore",u._queue=new pl,u._persistenceKey=(null==a?void 0:a.name)||"[DEFAULT]",u}return L(n,[{key:"_terminate",value:function(){return this._firestoreClient||Tl(this),this._firestoreClient.terminate()}}]),n}();function xl(e,t,r){r||(r="(default)");var i=(0,n._getProvider)(e,"firestore");if(i.isInitialized(r)){var u=i.getImmediate({identifier:r}),o=i.getOptions(r);if((0,a.deepEqual)(o,t))return u;throw new Z(J.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new Z(J.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return i.initialize({options:t,instanceIdentifier:r})}function bl(e,t){var r="object"==C(e)?e:(0,n.getApp)(),i="string"==typeof e?e:t||"(default)",u=(0,n._getProvider)(r,"firestore").getImmediate({identifier:i});if(!u._initialized){var o=(0,a.getDefaultEmulatorHostnameAndPort)("firestore");o&&ol.apply(void 0,[u].concat(E(o)))}return u}function Il(e){return e._firestoreClient||Tl(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Tl(e){var t,n=e._freezeSettings(),r=function(e,t,n,r){return new Je(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 Cc(e._authCredentials,e._appCheckCredentials,e._queue,r)}function El(e,t){Rl(e=rl(e,wl));var n=Il(e),r=e._freezeSettings(),i=new Ec;return _l(n,i,new Ic(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}function Sl(e){Rl(e=rl(e,wl));var t=Il(e),n=e._freezeSettings(),r=new Ec;return _l(t,r,new Tc(r,n.cacheSizeBytes))}function _l(e,t,n){var r=new $;return e.asyncQueue.enqueue(function(){var i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.prev=0,a.next=3,m().awrap(Pc(e,n));case 3:return a.next=5,m().awrap(Fc(e,t));case 5:r.resolve(),a.next=14;break;case 8:if(a.prev=8,a.t0=a.catch(0),function(e){return"FirebaseError"===e.name?e.code===J.FAILED_PRECONDITION||e.code===J.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||(22===e.code||20===e.code||11===e.code)}(i=a.t0)){a.next=13;break}throw i;case 13:j("Error enabling offline persistence. Falling back to persistence disabled: "+i),r.reject(i);case 14:case"end":return a.stop()}},null,null,[[0,8]],Promise)}).then(function(){return r.promise})}function Al(e){if(e._initialized&&!e._terminated)throw new Z(J.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");var t=new $;return e._queue.enqueueAndForgetEvenWhileRestricted(function(){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,m().awrap(function(e){var t;return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:if(Oe.C()){n.next=2;break}return n.abrupt("return",Promise.resolve());case 2:return t=e+"main",n.next=5,m().awrap(Oe.delete(t));case 5:case"end":return n.stop()}},null,null,null,Promise)}(Zu(e._databaseId,e._persistenceKey)));case 3:t.resolve(),n.next=9;break;case 6:n.prev=6,n.t0=n.catch(0),t.reject(n.t0);case 9:case"end":return n.stop()}},null,null,[[0,6]],Promise)}),t.promise}function Dl(e){return function(e){var t=new $;return e.asyncQueue.enqueueAndForget(function(){return m().async(function(n){for(;;)switch(n.prev=n.next){case 0:return n.t0=$s,n.next=3,m().awrap(qc(e));case 3:return n.t1=n.sent,n.t2=t,n.abrupt("return",(0,n.t0)(n.t1,n.t2));case 6:case"end":return n.stop()}},null,null,null,Promise)}),t.promise}(Il(e=rl(e,wl)))}function Nl(e){return Kc(Il(e=rl(e,wl)))}function Cl(e){return Gc(Il(e=rl(e,wl)))}function Pl(e){return(0,n._removeServiceInstance)(e.app,"firestore",e._databaseId.database),e._delete()}function Fl(e,t){var n=Il(e=rl(e,wl)),r=new gl;return Xc(n,e._databaseId,t,r),r}function Ll(e,t){return Yc(Il(e=rl(e,wl)),t).then(function(t){return t?new cl(e,null,t.query):null})}function Rl(e){if(e._initialized||e._terminated)throw new Z(J.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}exports.Firestore=wl;var Ml=L(function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"count",n=arguments.length>1?arguments[1]:void 0;P(this,e),this._aggregateType=t,this._internalFieldPath=n,this.type="AggregateField"});exports.AggregateField=Ml;var Ol=function(){function e(t,n,r){P(this,e),this._userDataWriter=n,this._data=r,this.type="AggregateQuerySnapshot",this.query=t}return L(e,[{key:"data",value:function(){return this._userDataWriter.convertValue(this._data.value)}}]),e}();exports.AggregateQuerySnapshot=Ol;var Vl=function(){function e(t){P(this,e),this._byteString=t}return L(e,[{key:"toBase64",value:function(){return this._byteString.toBase64()}},{key:"toUint8Array",value:function(){return this._byteString.toUint8Array()}},{key:"toString",value:function(){return"Bytes(base64: "+this.toBase64()+")"}},{key:"isEqual",value:function(e){return this._byteString.isEqual(e._byteString)}}],[{key:"fromBase64String",value:function(t){try{return new e(ot.fromBase64String(t))}catch(t){throw new Z(J.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}},{key:"fromUint8Array",value:function(t){return new e(ot.fromUint8Array(t))}}]),e}();exports.Bytes=Vl;var ql=function(){function e(){P(this,e);for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var i=0;i<n.length;++i)if(0===n[i].length)throw new Z(J.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new ke(n)}return L(e,[{key:"isEqual",value:function(e){return this._internalPath.isEqual(e._internalPath)}}]),e}();function Ul(){return new ql("__name__")}exports.FieldPath=ql;var Bl=L(function e(t){P(this,e),this._methodName=t});exports.FieldValue=Bl;var Kl=function(){function e(t,n){if(P(this,e),!isFinite(t)||t<-90||t>90)throw new Z(J.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(n)||n<-180||n>180)throw new Z(J.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=t,this._long=n}return L(e,[{key:"latitude",get:function(){return this._lat}},{key:"longitude",get:function(){return this._long}},{key:"isEqual",value:function(e){return this._lat===e._lat&&this._long===e._long}},{key:"toJSON",value:function(){return{latitude:this._lat,longitude:this._long}}},{key:"_compareTo",value:function(e){return fe(this._lat,e._lat)||fe(this._long,e._long)}}]),e}();exports.GeoPoint=Kl;var Gl=/^__.*__$/,Ql=function(){function e(t,n,r){P(this,e),this.data=t,this.fieldMask=n,this.fieldTransforms=r}return L(e,[{key:"toMutation",value:function(e,t){return null!==this.fieldMask?new pr(e,this.data,this.fieldMask,t,this.fieldTransforms):new yr(e,this.data,t,this.fieldTransforms)}}]),e}(),jl=function(){function e(t,n,r){P(this,e),this.data=t,this.fieldMask=n,this.fieldTransforms=r}return L(e,[{key:"toMutation",value:function(e,t){return new pr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}]),e}();function zl(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw W()}}var Wl=function(){function e(t,n,r,i,a,u){P(this,e),this.settings=t,this.databaseId=n,this.Tt=r,this.ignoreUndefinedProperties=i,void 0===a&&this.ia(),this.fieldTransforms=a||[],this.fieldMask=u||[]}return L(e,[{key:"path",get:function(){return this.settings.path}},{key:"ra",get:function(){return this.settings.ra}},{key:"oa",value:function(t){return new e(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.Tt,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}},{key:"ua",value:function(e){var t,n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.oa({path:n,ca:!1});return r.aa(e),r}},{key:"ha",value:function(e){var t,n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.oa({path:n,ca:!1});return r.ia(),r}},{key:"la",value:function(e){return this.oa({path:void 0,ca:!0})}},{key:"fa",value:function(e){return vf(e,this.settings.methodName,this.settings.da||!1,this.path,this.settings._a)}},{key:"contains",value:function(e){return void 0!==this.fieldMask.find(function(t){return e.isPrefixOf(t)})||void 0!==this.fieldTransforms.find(function(t){return e.isPrefixOf(t.field)})}},{key:"ia",value:function(){if(this.path)for(var e=0;e<this.path.length;e++)this.aa(this.path.get(e))}},{key:"aa",value:function(e){if(0===e.length)throw this.fa("Document fields must not be empty");if(zl(this.ra)&&Gl.test(e))throw this.fa('Document fields cannot begin and end with "__"')}}]),e}(),Hl=function(){function e(t,n,r){P(this,e),this.databaseId=t,this.ignoreUndefinedProperties=n,this.Tt=r||Vo(t)}return L(e,[{key:"wa",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new Wl({ra:e,methodName:t,_a:n,path:ke.emptyPath(),ca:!1,da:r},this.databaseId,this.Tt,this.ignoreUndefinedProperties)}}]),e}();function Xl(e){var t=e._freezeSettings(),n=Vo(e._databaseId);return new Hl(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Yl(e,t,n,r,i){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},u=e.wa(a.merge||a.mergeFields?2:0,t,n,i);lf("Data must be an object, but it was:",u,r);var o,s,c=sf(r,u);if(a.merge)o=new dn(u.fieldMask),s=u.fieldTransforms;else if(a.mergeFields){var l,f=[],h=p(a.mergeFields);try{for(h.s();!(l=h.n()).done;){var d=ff(t,l.value,n);if(!u.contains(d))throw new Z(J.INVALID_ARGUMENT,"Field '".concat(d,"' is specified in your field mask but missing from your input data."));yf(f,d)||f.push(d)}}catch(v){h.e(v)}finally{h.f()}o=new dn(f),s=u.fieldTransforms.filter(function(e){return o.covers(e.field)})}else o=null,s=u.fieldTransforms;return new Ql(new vn(c),o,s)}var Jl=function(e){g(n,Bl);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n,[{key:"_toFieldTransform",value:function(e){if(2!==e.ra)throw 1===e.ra?e.fa("".concat(this._methodName,"() can only appear at the top level of your update data")):e.fa("".concat(this._methodName,"() cannot be used with set() unless you pass {merge:true}"));return e.fieldMask.push(e.path),null}},{key:"isEqual",value:function(e){return e instanceof n}}]),n}();function Zl(e,t,n){return new Wl({ra:3,_a:t.settings._a,methodName:e._methodName,ca:n},t.databaseId,t.Tt,t.ignoreUndefinedProperties)}var $l=function(e){g(n,Bl);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n,[{key:"_toFieldTransform",value:function(e){return new ir(e.path,new Yn)}},{key:"isEqual",value:function(e){return e instanceof n}}]),n}(),ef=function(e){g(n,Bl);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e)).ma=r,i}return L(n,[{key:"_toFieldTransform",value:function(e){var t=Zl(this,e,!0),n=this.ma.map(function(e){return of(e,t)}),r=new Jn(n);return new ir(e.path,r)}},{key:"isEqual",value:function(e){return this===e}}]),n}(),tf=function(e){g(n,Bl);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e)).ma=r,i}return L(n,[{key:"_toFieldTransform",value:function(e){var t=Zl(this,e,!0),n=this.ma.map(function(e){return of(e,t)}),r=new $n(n);return new ir(e.path,r)}},{key:"isEqual",value:function(e){return this===e}}]),n}(),nf=function(e){g(n,Bl);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e)).ga=r,i}return L(n,[{key:"_toFieldTransform",value:function(e){var t=new tr(e.Tt,jn(e.Tt,this.ga));return new ir(e.path,t)}},{key:"isEqual",value:function(e){return this===e}}]),n}();function rf(e,t,n,r){var i=e.wa(1,t,n);lf("Data must be an object, but it was:",i,r);var u=[],o=vn.empty();et(r,function(e,r){var s=df(t,e,n);r=(0,a.getModularInstance)(r);var c=i.ha(s);if(r instanceof Jl)u.push(s);else{var l=of(r,c);null!=l&&(u.push(s),o.set(s,l))}});var s=new dn(u);return new jl(o,s,i.fieldTransforms)}function af(e,t,n,r,i,u){var o=e.wa(1,t,n),s=[ff(t,r,n)],c=[i];if(u.length%2!=0)throw new Z(J.INVALID_ARGUMENT,"Function ".concat(t,"() needs to be called with an even number of arguments that alternate between field names and values."));for(var l=0;l<u.length;l+=2)s.push(ff(t,u[l])),c.push(u[l+1]);for(var f=[],h=vn.empty(),d=s.length-1;d>=0;--d)if(!yf(f,s[d])){var v=s[d],y=c[d];y=(0,a.getModularInstance)(y);var p=o.ha(v);if(y instanceof Jl)f.push(v);else{var m=of(y,p);null!=m&&(f.push(v),h.set(v,m))}}var g=new dn(f);return new jl(h,g,o.fieldTransforms)}function uf(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return of(n,e.wa(r?4:3,t))}function of(e,t){if(cf(e=(0,a.getModularInstance)(e)))return lf("Unsupported field value:",t,e),sf(e,t);if(e instanceof Bl)return function(e,t){if(!zl(t.ra))throw t.fa("".concat(e._methodName,"() can only be used with update() and set()"));if(!t.path)throw t.fa("".concat(e._methodName,"() is not currently supported inside arrays"));var 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.ca&&4!==t.ra)throw t.fa("Nested arrays are not supported");return function(e,t){var n,r=[],i=0,a=p(e);try{for(a.s();!(n=a.n()).done;){var u=of(n.value,t.la(i));null==u&&(u={nullValue:"NULL_VALUE"}),r.push(u),i++}}catch(o){a.e(o)}finally{a.f()}return{arrayValue:{values:r}}}(e,t)}return function(e,t){if(null===(e=(0,a.getModularInstance)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return jn(t.Tt,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=ve.fromDate(e);return{timestampValue:ei(t.Tt,n)}}if(e instanceof ve){var r=new ve(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ei(t.Tt,r)}}if(e instanceof Kl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Vl)return{bytesValue:ti(t.Tt,e._byteString)};if(e instanceof sl){var i=t.databaseId,u=e.firestore._databaseId;if(!u.isEqual(i))throw t.fa("Document reference is for database ".concat(u.projectId,"/").concat(u.database," but should be for database ").concat(i.projectId,"/").concat(i.database));return{referenceValue:ii(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.fa("Unsupported field value: ".concat(nl(e)))}(e,t)}function sf(e,t){var n={};return tt(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):et(e,function(e,r){var i=of(r,t.ua(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function cf(e){return!("object"!=C(e)||null===e||e instanceof Array||e instanceof Date||e instanceof ve||e instanceof Kl||e instanceof Vl||e instanceof sl||e instanceof Bl)}function lf(e,t,n){if(!cf(n)||!function(e){return"object"==C(e)&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){var r=nl(n);throw"an object"===r?t.fa(e+" a custom object"):t.fa(e+" "+r)}}function ff(e,t,n){if((t=(0,a.getModularInstance)(t))instanceof ql)return t._internalPath;if("string"==typeof t)return df(e,t);throw vf("Field path arguments must be of type string or ",e,!1,void 0,n)}var hf=new RegExp("[~\\*/\\[\\]]");function df(e,t,n){if(t.search(hf)>=0)throw vf("Invalid field path (".concat(t,"). Paths must not contain '~', '*', '/', '[', or ']'"),e,!1,void 0,n);try{return v(ql,E(t.split(".")))._internalPath}catch(r){throw vf("Invalid field path (".concat(t,"). Paths must not be empty, begin with '.', end with '.', or contain '..'"),e,!1,void 0,n)}}function vf(e,t,n,r,i){var a=r&&!r.isEmpty(),u=void 0!==i,o="Function ".concat(t,"() called with invalid data");n&&(o+=" (via `toFirestore()`)"),o+=". ";var s="";return(a||u)&&(s+=" (found",a&&(s+=" in field ".concat(r)),u&&(s+=" in document ".concat(i)),s+=")"),new Z(J.INVALID_ARGUMENT,o+e+s)}function yf(e,t){return e.some(function(e){return e.isEqual(t)})}var pf=function(){function e(t,n,r,i,a){P(this,e),this._firestore=t,this._userDataWriter=n,this._key=r,this._document=i,this._converter=a}return L(e,[{key:"id",get:function(){return this._key.path.lastSegment()}},{key:"ref",get:function(){return new sl(this._firestore,this._converter,this._key)}},{key:"exists",value:function(){return null!==this._document}},{key:"data",value:function(){if(this._document){if(this._converter){var e=new mf(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}},{key:"get",value:function(e){if(this._document){var t=this._document.data.field(gf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}]),e}(),mf=function(e){g(n,pf);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n,[{key:"data",value:function(){return o(T(n.prototype),"data",this).call(this)}}]),n}();function gf(e,t){return"string"==typeof t?df(e,t):t instanceof ql?t._internalPath:t._delegate._internalPath}function kf(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new Z(J.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var wf=L(function e(){P(this,e)}),xf=function(e){g(n,wf);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n)}();function bf(e,t){for(var n=[],r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a];t instanceof wf&&n.push(t),function(e){var t=e.filter(function(e){return e instanceof Ef}).length,n=e.filter(function(e){return e instanceof If}).length;if(t>1||t>0&&n>0)throw new Z(J.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(n=n.concat(i));var u,o=p(n);try{for(o.s();!(u=o.n()).done;){e=u.value._apply(e)}}catch(s){o.e(s)}finally{o.f()}return e}exports.QueryConstraint=xf;var If=function(e){g(n,xf);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this))._field=e,a._op=r,a._value=i,a.type="where",a}return L(n,[{key:"_apply",value:function(e){var t=this._parse(e);return Kf(e._query,t),new cl(e.firestore,e.converter,Ln(e._query,t))}},{key:"_parse",value:function(e){var t=Xl(e.firestore);return function(e,t,n,r,i,a,u){var o;if(i.isKeyField()){if("array-contains"===a||"array-contains-any"===a)throw new Z(J.INVALID_ARGUMENT,"Invalid Query. You can't perform '".concat(a,"' queries on documentId()."));if("in"===a||"not-in"===a){Bf(u,a);var s,c=[],l=p(u);try{for(l.s();!(s=l.n()).done;){var f=s.value;c.push(Uf(r,e,f))}}catch(h){l.e(h)}finally{l.f()}o={arrayValue:{values:c}}}else o=Uf(r,e,u)}else"in"!==a&&"not-in"!==a&&"array-contains-any"!==a||Bf(u,a),o=uf(n,"where",u,"in"===a||"not-in"===a);return Ut.create(i,a,o)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value)}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function Tf(e,t,n){var r=t,i=gf("where",e);return If._create(i,r,n)}exports.QueryFieldFilterConstraint=If;var Ef=function(e){g(n,wf);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this)).type=e,i._queryConstraints=r,i}return L(n,[{key:"_parse",value:function(e){var t=this._queryConstraints.map(function(t){return t._parse(e)}).filter(function(e){return e.getFilters().length>0});return 1===t.length?t[0]:Bt.create(t,this._getOperator())}},{key:"_apply",value:function(e){var t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){var n,r=e,i=p(t.getFlattenedFilters());try{for(i.s();!(n=i.n()).done;){var a=n.value;Kf(r,a),r=Ln(r,a)}}catch(u){i.e(u)}finally{i.f()}}(e._query,t),new cl(e.firestore,e.converter,Ln(e._query,t)))}},{key:"_getQueryConstraints",value:function(){return this._queryConstraints}},{key:"_getOperator",value:function(){return"and"===this.type?"and":"or"}}],[{key:"_create",value:function(e,t){return new n(e,t)}}]),n}();function Sf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.forEach(function(e){return Qf("or",e)}),Ef._create("or",t)}function _f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.forEach(function(e){return Qf("and",e)}),Ef._create("and",t)}exports.QueryCompositeFilterConstraint=Ef;var Af=function(e){g(n,xf);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this))._field=e,i._direction=r,i.type="orderBy",i}return L(n,[{key:"_apply",value:function(e){var t=function(e,t,n){if(null!==e.startAt)throw new Z(J.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new Z(J.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r=new an(t,n);return function(e,t){if(null===Dn(e)){var n=Nn(e);null!==n&&Gf(e,n,t.field)}}(e,r),r}(e._query,this._field,this._direction);return new cl(e.firestore,e.converter,function(e,t){var n=e.explicitOrderBy.concat([t]);return new En(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}],[{key:"_create",value:function(e,t){return new n(e,t)}}]),n}();function Df(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"asc",n=gf("orderBy",e);return Af._create(n,t)}exports.QueryOrderByConstraint=Af;var Nf=function(e){g(n,xf);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this)).type=e,a._limit=r,a._limitType=i,a}return L(n,[{key:"_apply",value:function(e){return new cl(e.firestore,e.converter,Rn(e._query,this._limit,this._limitType))}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function Cf(e){return il("limit",e),Nf._create("limit",e,"F")}function Pf(e){return il("limitToLast",e),Nf._create("limitToLast",e,"L")}exports.QueryLimitConstraint=Nf;var Ff=function(e){g(n,xf);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this)).type=e,a._docOrFields=r,a._inclusive=i,a}return L(n,[{key:"_apply",value:function(e){var t=qf(e,this.type,this._docOrFields,this._inclusive);return new cl(e.firestore,e.converter,function(e,t){return new En(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function Lf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Ff._create("startAt",t,!0)}function Rf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Ff._create("startAfter",t,!1)}exports.QueryStartAtConstraint=Ff;var Mf=function(e){g(n,xf);var t=w(n);function n(e,r,i){var a;return P(this,n),(a=t.call(this)).type=e,a._docOrFields=r,a._inclusive=i,a}return L(n,[{key:"_apply",value:function(e){var t=qf(e,this.type,this._docOrFields,this._inclusive);return new cl(e.firestore,e.converter,function(e,t){return new En(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}],[{key:"_create",value:function(e,t,r){return new n(e,t,r)}}]),n}();function Of(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Mf._create("endBefore",t,!1)}function Vf(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Mf._create("endAt",t,!0)}function qf(e,t,n,r){if(n[0]=(0,a.getModularInstance)(n[0]),n[0]instanceof pf)return function(e,t,n,r,i){if(!r)throw new Z(J.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for ".concat(n,"()."));var a,u=[],o=p(Pn(e));try{for(o.s();!(a=o.n()).done;){var s=a.value;if(s.field.isKeyField())u.push(Tt(t,r.key));else{var c=r.data.field(s.field);if(ht(c))throw new Z(J.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+s.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===c){var l=s.field.canonicalString();throw new Z(J.INVALID_ARGUMENT,"Invalid query. You are trying to start or end a query using a document for which the field '".concat(l,"' (used as the orderBy) does not exist."))}u.push(c)}}}catch(f){o.e(f)}finally{o.f()}return new Mt(u,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=Xl(e.firestore);return function(e,t,n,r,i,a){var u=e.explicitOrderBy;if(i.length>u.length)throw new Z(J.INVALID_ARGUMENT,"Too many arguments provided to ".concat(r,"(). The number of arguments must be less than or equal to the number of orderBy() clauses"));for(var o=[],s=0;s<i.length;s++){var c=i[s];if(u[s].field.isKeyField()){if("string"!=typeof c)throw new Z(J.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in ".concat(r,"(), but got a ").concat(C(c)));if(!Cn(e)&&-1!==c.indexOf("/"))throw new Z(J.INVALID_ARGUMENT,"Invalid query. When querying a collection and ordering by documentId(), the value passed to ".concat(r,"() must be a plain document ID, but '").concat(c,"' contains a slash."));var l=e.path.child(me.fromString(c));if(!we.isDocumentKey(l))throw new Z(J.INVALID_ARGUMENT,"Invalid query. When querying a collection group and ordering by documentId(), the value passed to ".concat(r,"() must result in a valid document path, but '").concat(l,"' is not because it contains an odd number of segments."));var f=new we(l);o.push(Tt(t,f))}else{var h=uf(n,r,c);o.push(h)}}return new Mt(o,a)}(e._query,e.firestore._databaseId,i,t,n,r)}function Uf(e,t,n){if("string"==typeof(n=(0,a.getModularInstance)(n))){if(""===n)throw new Z(J.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Cn(t)&&-1!==n.indexOf("/"))throw new Z(J.INVALID_ARGUMENT,"Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '".concat(n,"' contains a '/' character."));var r=t.path.child(me.fromString(n));if(!we.isDocumentKey(r))throw new Z(J.INVALID_ARGUMENT,"Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '".concat(r,"' is not because it has an odd number of segments (").concat(r.length,")."));return Tt(e,new we(r))}if(n instanceof sl)return Tt(e,n._key);throw new Z(J.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ".concat(nl(n),"."))}function Bf(e,t){if(!Array.isArray(e)||0===e.length)throw new Z(J.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '".concat(t.toString(),"' filters."))}function Kf(e,t){if(t.isInequality()){var n=Nn(e),r=t.field;if(null!==n&&!n.isEqual(r))throw new Z(J.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '".concat(n.toString(),"' and '").concat(r.toString(),"'"));var i=Dn(e);null!==i&&Gf(e,r,i)}var a=function(e,t){var n,r=p(e);try{for(r.s();!(n=r.n()).done;){var i,a=p(n.value.getFlattenedFilters());try{for(a.s();!(i=a.n()).done;){var u=i.value;if(t.indexOf(u.op)>=0)return u.op}}catch(o){a.e(o)}finally{a.f()}}}catch(o){r.e(o)}finally{r.f()}return null}(e.filters,function(e){switch(t.op){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}());if(null!==a)throw a===t.op?new Z(J.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '".concat(t.op.toString(),"' filter.")):new Z(J.INVALID_ARGUMENT,"Invalid query. You cannot use '".concat(t.op.toString(),"' filters with '").concat(a.toString(),"' filters."))}function Gf(e,t,n){if(!n.isEqual(t))throw new Z(J.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '".concat(t.toString(),"' and so you must also use '").concat(t.toString(),"' as your first argument to orderBy(), but your first orderBy() is on field '").concat(n.toString(),"' instead."))}function Qf(e,t){if(!(t instanceof If||t instanceof Ef))throw new Z(J.INVALID_ARGUMENT,"Function ".concat(e,"() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'."))}exports.QueryEndAtConstraint=Mf;var jf=function(){function e(){P(this,e)}return L(e,[{key:"convertValue",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"none";switch(mt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return lt(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(ft(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 W()}}},{key:"convertObject",value:function(e,t){var n=this,r={};return et(e.fields,function(e,i){r[e]=n.convertValue(i,t)}),r}},{key:"convertGeoPoint",value:function(e){return new Kl(lt(e.latitude),lt(e.longitude))}},{key:"convertArray",value:function(e,t){var n=this;return(e.values||[]).map(function(e){return n.convertValue(e,t)})}},{key:"convertServerTimestamp",value:function(e,t){switch(t){case"previous":var n=dt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(vt(e));default:return null}}},{key:"convertTimestamp",value:function(e){var t=ct(e);return new ve(t.seconds,t.nanos)}},{key:"convertDocumentKey",value:function(e,t){var n=me.fromString(e);H(Ci(n));var r=new Ze(n.get(1),n.get(3)),i=new we(n.popFirst(5));return r.isEqual(t)||Q("Document ".concat(i," contains a document reference within a different database (").concat(r.projectId,"/").concat(r.database,") which is not supported. It will be treated as a reference in the current database (").concat(t.projectId,"/").concat(t.database,") instead.")),i}}]),e}();function zf(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}exports.AbstractUserDataWriter=jf;var Wf=function(e){g(n,jf);var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this)).firestore=e,r}return L(n,[{key:"convertBytes",value:function(e){return new Vl(e)}},{key:"convertReference",value:function(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new sl(this.firestore,null,t)}}]),n}();function Hf(e){return new Ml("sum",ff("sum",e))}function Xf(e){return new Ml("avg",ff("average",e))}function Yf(){return new Ml("count")}function Jf(e,t){var n,r;return e instanceof Ml&&t instanceof Ml&&e._aggregateType===t._aggregateType&&(null===(n=e._internalFieldPath)||void 0===n?void 0:n.canonicalString())===(null===(r=t._internalFieldPath)||void 0===r?void 0:r.canonicalString())}function Zf(e,t){return yl(e.query,t.query)&&(0,a.deepEqual)(e.data(),t.data())}var $f=function(){function e(t,n){P(this,e),this.hasPendingWrites=t,this.fromCache=n}return L(e,[{key:"isEqual",value:function(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}]),e}();exports.SnapshotMetadata=$f;var eh=function(e){g(n,pf);var t=w(n);function n(e,r,i,a,u,o){var s;return P(this,n),(s=t.call(this,e,r,i,a,o))._firestore=e,s._firestoreImpl=e,s.metadata=u,s}return L(n,[{key:"exists",value:function(){return o(T(n.prototype),"exists",this).call(this)}},{key:"data",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this._document){if(this._converter){var t=new th(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)}}},{key:"get",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._document){var n=this._document.data.field(gf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}]),n}();exports.DocumentSnapshot=eh;var th=function(e){g(n,eh);var t=w(n);function n(){return P(this,n),t.apply(this,arguments)}return L(n,[{key:"data",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return o(T(n.prototype),"data",this).call(this,e)}}]),n}();exports.QueryDocumentSnapshot=th;var nh=function(){function e(t,n,r,i){P(this,e),this._firestore=t,this._userDataWriter=n,this._snapshot=i,this.metadata=new $f(i.hasPendingWrites,i.fromCache),this.query=r}return L(e,[{key:"docs",get:function(){var e=[];return this.forEach(function(t){return e.push(t)}),e}},{key:"size",get:function(){return this._snapshot.docs.size}},{key:"empty",get:function(){return 0===this.size}},{key:"forEach",value:function(e,t){var n=this;this._snapshot.docs.forEach(function(r){e.call(t,new th(n._firestore,n._userDataWriter,r.key,r,new $f(n._snapshot.mutatedKeys.has(r.key),n._snapshot.fromCache),n.query.converter))})}},{key:"docChanges",value:function(){var e=!!(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new Z(J.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){var n=0;return e._snapshot.docChanges.map(function(t){var r=new th(e._firestore,e._userDataWriter,t.doc.key,t.doc,new $f(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);return t.doc,{type:"added",doc:r,oldIndex:-1,newIndex:n++}})}var r=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(function(e){return t||3!==e.type}).map(function(t){var n=new th(e._firestore,e._userDataWriter,t.doc.key,t.doc,new $f(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,a=-1;return 0!==t.type&&(i=r.indexOf(t.doc.key),r=r.delete(t.doc.key)),1!==t.type&&(a=(r=r.add(t.doc)).indexOf(t.doc.key)),{type:rh(t.type),doc:n,oldIndex:i,newIndex:a}})}(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}]),e}();function rh(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return W()}}function ih(e,t){return e instanceof eh&&t instanceof eh?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof nh&&t instanceof nh&&e._firestore===t._firestore&&yl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function ah(e){e=rl(e,sl);var t=rl(e.firestore,wl);return jc(Il(t),e._key).then(function(n){return kh(t,e,n)})}exports.QuerySnapshot=nh;var uh=function(e){g(n,jf);var t=w(n);function n(e){var r;return P(this,n),(r=t.call(this)).firestore=e,r}return L(n,[{key:"convertBytes",value:function(e){return new Vl(e)}},{key:"convertReference",value:function(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new sl(this.firestore,null,t)}}]),n}();function oh(e){e=rl(e,sl);var t=rl(e.firestore,wl),n=Il(t),r=new uh(t);return Qc(n,e._key).then(function(n){return new eh(t,r,e._key,n,new $f(null!==n&&n.hasLocalMutations,!0),e.converter)})}function sh(e){e=rl(e,sl);var t=rl(e.firestore,wl);return jc(Il(t),e._key,{source:"server"}).then(function(n){return kh(t,e,n)})}function ch(e){e=rl(e,cl);var t=rl(e.firestore,wl),n=Il(t),r=new uh(t);return kf(e._query),Wc(n,e._query).then(function(n){return new nh(t,r,e,n)})}function lh(e){e=rl(e,cl);var t=rl(e.firestore,wl),n=Il(t),r=new uh(t);return zc(n,e._query).then(function(n){return new nh(t,r,e,n)})}function fh(e){e=rl(e,cl);var t=rl(e.firestore,wl),n=Il(t),r=new uh(t);return Wc(n,e._query,{source:"server"}).then(function(n){return new nh(t,r,e,n)})}function hh(e,t,n){e=rl(e,sl);var r=rl(e.firestore,wl),i=zf(e.converter,t,n);return gh(r,[Yl(Xl(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,or.none())])}function dh(e,t,n){e=rl(e,sl);for(var r=rl(e.firestore,wl),i=Xl(r),u=arguments.length,o=new Array(u>3?u-3:0),s=3;s<u;s++)o[s-3]=arguments[s];return gh(r,[("string"==typeof(t=(0,a.getModularInstance)(t))||t instanceof ql?af(i,"updateDoc",e._key,t,n,o):rf(i,"updateDoc",e._key,t)).toMutation(e._key,or.exists(!0))])}function vh(e){return gh(rl(e.firestore,wl),[new br(e._key,or.none())])}function yh(e,t){var n=rl(e.firestore,wl),r=dl(e),i=zf(e.converter,t);return gh(n,[Yl(Xl(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,or.exists(!1))]).then(function(){return r})}function ph(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var i,u,o;e=(0,a.getModularInstance)(e);var s={includeMetadataChanges:!1},c=0;"object"!=C(n[c])||ml(n[c])||(s=n[c],c++);var l,f,h,d={includeMetadataChanges:s.includeMetadataChanges};if(ml(n[c])){var v=n[c];n[c]=null===(i=v.next)||void 0===i?void 0:i.bind(v),n[c+1]=null===(u=v.error)||void 0===u?void 0:u.bind(v),n[c+2]=null===(o=v.complete)||void 0===o?void 0:o.bind(v)}if(e instanceof sl)f=rl(e.firestore,wl),h=_n(e._key.path),l={next:function(t){n[c]&&n[c](kh(f,e,t))},error:n[c+1],complete:n[c+2]};else{var y=rl(e,cl);f=rl(y.firestore,wl),h=y._query;var p=new uh(f);l={next:function(e){n[c]&&n[c](new nh(f,p,y,e))},error:n[c+1],complete:n[c+2]},kf(e._query)}return function(e,t,n,r){var i=new _c(l),a=new Fs(t,i,n);return e.asyncQueue.enqueueAndForget(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=As,t.next=3,m().awrap(Bc(e));case 3:return t.t1=t.sent,t.t2=a,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)}),function(){i.bc(),e.asyncQueue.enqueueAndForget(function(){return m().async(function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=Ds,t.next=3,m().awrap(Bc(e));case 3:return t.t1=t.sent,t.t2=a,t.abrupt("return",(0,t.t0)(t.t1,t.t2));case 6:case"end":return t.stop()}},null,null,null,Promise)})}}(Il(f),h,d)}function mh(e,t){return Hc(Il(e=rl(e,wl)),ml(t)?t:{next:t})}function gh(e,t){return function(e,t){var n=new $;return e.asyncQueue.enqueueAndForget(function(){return m().async(function(r){for(;;)switch(r.prev=r.next){case 0:return r.t0=Ws,r.next=3,m().awrap(qc(e));case 3:return r.t1=r.sent,r.t2=t,r.t3=n,r.abrupt("return",(0,r.t0)(r.t1,r.t2,r.t3));case 7:case"end":return r.stop()}},null,null,null,Promise)}),n.promise}(Il(e),t)}function kh(e,t,n){var r=n.docs.get(t._key),i=new uh(e);return new eh(e,i,t._key,r,new $f(n.hasPendingWrites,n.fromCache),t.converter)}function wh(e){return xh(e,{count:Yf()})}function xh(e,t){var n=rl(e.firestore,wl),r=Il(n),i=function(e,t){var n=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.push(t(e[r],r));return n}(t,function(e,t){return new Ye(new Xe(t),e._aggregateType,e._internalFieldPath)});return function(e,t,n){var r=new $;return e.asyncQueue.enqueueAndForget(function(){var i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.prev=0,a.t0=ts,a.next=4,m().awrap(Vc(e));case 4:if(a.t1=a.sent,!(0,a.t0)(a.t1)){a.next=12;break}return a.next=8,m().awrap(Uc(e));case 8:i=a.sent,r.resolve(Qo(i,t,n)),a.next=13;break;case 12:r.reject(new Z(J.UNAVAILABLE,"Failed to get aggregate result because the client is offline."));case 13:a.next=18;break;case 15:a.prev=15,a.t2=a.catch(0),r.reject(a.t2);case 18:case"end":return a.stop()}},null,null,[[0,15]],Promise)}),r.promise}(r,e._query,i).then(function(t){return function(e,t,n){var r=new uh(e);return new Ol(t,r,n)}(n,e,t)})}var bh={maxAttempts:5},Ih=function(){function e(t,n){P(this,e),this._firestore=t,this._commitHandler=n,this._mutations=[],this._committed=!1,this._dataReader=Xl(t)}return L(e,[{key:"set",value:function(e,t,n){this._verifyNotCommitted();var r=Th(e,this._firestore),i=zf(r.converter,t,n),a=Yl(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(a.toMutation(r._key,or.none())),this}},{key:"update",value:function(e,t,n){this._verifyNotCommitted();for(var r,i=Th(e,this._firestore),u=arguments.length,o=new Array(u>3?u-3:0),s=3;s<u;s++)o[s-3]=arguments[s];return r="string"==typeof(t=(0,a.getModularInstance)(t))||t instanceof ql?af(this._dataReader,"WriteBatch.update",i._key,t,n,o):rf(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(r.toMutation(i._key,or.exists(!0))),this}},{key:"delete",value:function(e){this._verifyNotCommitted();var t=Th(e,this._firestore);return this._mutations=this._mutations.concat(new br(t._key,or.none())),this}},{key:"commit",value:function(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}},{key:"_verifyNotCommitted",value:function(){if(this._committed)throw new Z(J.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}]),e}();function Th(e,t){if((e=(0,a.getModularInstance)(e)).firestore!==t)throw new Z(J.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}exports.WriteBatch=Ih;var Eh=function(e){g(n,e);var t=w(n);function n(e,r){var i;return P(this,n),(i=t.call(this,e,r))._firestore=e,i}return L(n,[{key:"get",value:function(e){var t=this,r=Th(e,this._firestore),i=new uh(this._firestore);return o(T(n.prototype),"get",this).call(this,e).then(function(e){return new eh(t._firestore,i,r._key,e._document,new $f(!1,!1),r.converter)})}}]),n}(function(){function e(t,n){P(this,e),this._firestore=t,this._transaction=n,this._dataReader=Xl(t)}return L(e,[{key:"get",value:function(e){var t=this,n=Th(e,this._firestore),r=new Wf(this._firestore);return this._transaction.lookup([n._key]).then(function(e){if(!e||1!==e.length)return W();var i=e[0];if(i.isFoundDocument())return new pf(t._firestore,r,i.key,i,n.converter);if(i.isNoDocument())return new pf(t._firestore,r,n._key,null,n.converter);throw W()})}},{key:"set",value:function(e,t,n){var r=Th(e,this._firestore),i=zf(r.converter,t,n),a=Yl(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,a),this}},{key:"update",value:function(e,t,n){for(var r,i=Th(e,this._firestore),u=arguments.length,o=new Array(u>3?u-3:0),s=3;s<u;s++)o[s-3]=arguments[s];return r="string"==typeof(t=(0,a.getModularInstance)(t))||t instanceof ql?af(this._dataReader,"Transaction.update",i._key,t,n,o):rf(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,r),this}},{key:"delete",value:function(e){var t=Th(e,this._firestore);return this._transaction.delete(t._key),this}}]),e}());function Sh(e,t,n){e=rl(e,wl);var r=Object.assign(Object.assign({},bh),n);return function(e){if(r.maxAttempts<1)throw new Z(J.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(e,t,n){var r=new $;return e.asyncQueue.enqueueAndForget(function(){var i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return a.next=2,m().awrap(Uc(e));case 2:i=a.sent,new Nc(e.asyncQueue,i,n,t,r).run();case 4:case"end":return a.stop()}},null,null,null,Promise)}),r.promise}(Il(e),function(n){return t(new Eh(e,n))},r)}function _h(){return new Jl("deleteField")}function Ah(){return new $l("serverTimestamp")}function Dh(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new ef("arrayUnion",t)}function Nh(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new tf("arrayRemove",t)}function Ch(e){return new nf("increment",e)}function Ph(e){return Il(e=rl(e,wl)),new Ih(e,function(t){return gh(e,t)})}function Fh(e,t){var n,r=Il(e=rl(e,wl));if(!(null===(n=r.offlineComponents)||void 0===n?void 0:n.indexBackfillerScheduler))return j("Cannot enable indexes when persistence is disabled"),Promise.resolve();var i=function(e){var t="string"==typeof e?function(e){try{return JSON.parse(e)}catch(e){throw new Z(J.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,n=[];if(Array.isArray(t.indexes)){var r,i=p(t.indexes);try{for(i.s();!(r=i.n()).done;){var a=r.value,u=Lh(a,"collectionGroup"),o=[];if(Array.isArray(a.fields)){var s,c=p(a.fields);try{for(c.s();!(s=c.n()).done;){var l=s.value,f=df("setIndexConfiguration",Lh(l,"fieldPath"));"CONTAINS"===l.arrayConfig?o.push(new Ee(f,2)):"ASCENDING"===l.order?o.push(new Ee(f,0)):"DESCENDING"===l.order&&o.push(new Ee(f,1))}}catch(h){c.e(h)}finally{c.f()}}n.push(new xe(xe.UNKNOWN_ID,u,o,_e.empty()))}}catch(h){i.e(h)}finally{i.f()}}return n}(t);return Oc(r).then(function(e){return function(e,t){var n,r,i;return m().async(function(a){for(;;)switch(a.prev=a.next){case 0:return n=Y(e),r=n.indexManager,i=[],a.abrupt("return",n.persistence.runTransaction("Configure indexes","readwrite",function(e){return r.getFieldIndexes(e).next(function(n){return function(e,t,n,r,i){e=E(e),t=E(t),e.sort(n),t.sort(n);for(var a=e.length,u=t.length,o=0,s=0;o<u&&s<a;){var c=n(e[s],t[o]);c<0?i(e[s++]):c>0?r(t[o++]):(o++,s++)}for(;o<u;)r(t[o++]);for(;s<a;)i(e[s++])}(n,t,Te,function(t){i.push(r.addFieldIndex(e,t))},function(t){i.push(r.deleteFieldIndex(e,t))})}).next(function(){return Re.waitFor(i)})}));case 2:case"end":return a.stop()}},null,null,null,Promise)}(e,i)})}function Lh(e,t){if("string"!=typeof e[t])throw new Z(J.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}exports.Transaction=Eh,function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];!function(e){q=e}(n.SDK_VERSION),(0,n._registerComponent)(new r.Component("firestore",function(e,n){var r=n.instanceIdentifier,i=n.options,a=e.getProvider("app").getImmediate(),u=new wl(new re(e.getProvider("auth-internal")),new oe(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new Z(J.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ze(e.options.projectId,t)}(a,r),a);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u},"PUBLIC").setMultipleInstances(!0)),(0,n.registerVersion)(O,"3.9.0",e),(0,n.registerVersion)(O,"3.9.0","esm2017")}();
|
|
508
508
|
},{"@firebase/app":"h2Mb","@firebase/component":"vhY9","@firebase/logger":"JJem","@firebase/util":"chA2","@firebase/webchannel-wrapper":"qQDx","process":"pBGv"}],"LeU4":[function(require,module,exports) {
|
|
509
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerFirestore=W;var e=n(require("@firebase/app-compat")),t=require("@firebase/firestore"),r=require("@firebase/util"),s=require("@firebase/component");function n(e){return e&&e.__esModule?e:{default:e}}const i="@firebase/firestore-compat",a="0.3.3";function o(e,r){if(void 0===r)return{merge:!1};if(void 0!==r.mergeFields&&void 0!==r.merge)throw new t.FirestoreError("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return r}function l(){if("undefined"==typeof Uint8Array)throw new t.FirestoreError("unimplemented","Uint8Arrays are not available in this environment.")}function d(){if(!(0,t._isBase64Available)())throw new t.FirestoreError("unimplemented","Blobs are unavailable in Firestore in this environment.")}class c{constructor(e){this._delegate=e}static fromBase64String(e){return d(),new c(t.Bytes.fromBase64String(e))}static fromUint8Array(e){return l(),new c(t.Bytes.fromUint8Array(e))}toBase64(){return d(),this._delegate.toBase64()}toUint8Array(){return l(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function h(e){return u(e,["next","error","complete"])}function u(e,t){if("object"!=typeof e||null===e)return!1;const r=e;for(const s of t)if(s in r&&"function"==typeof r[s])return!0;return!1}class g{enableIndexedDbPersistence(e,r){return(0,t.enableIndexedDbPersistence)(e._delegate,{forceOwnership:r})}enableMultiTabIndexedDbPersistence(e){return(0,t.enableMultiTabIndexedDbPersistence)(e._delegate)}clearIndexedDbPersistence(e){return(0,t.clearIndexedDbPersistence)(e._delegate)}}class _{constructor(e,r,s){this._delegate=r,this._persistenceProvider=s,this.INTERNAL={delete:()=>this.terminate()},e instanceof t._DatabaseId||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){const r=this._delegate._getSettings();e.merge||r.host===e.host||(0,t._logWarn)("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},r),e)).merge,this._delegate._setSettings(e)}useEmulator(e,r,s={}){(0,t.connectFirestoreEmulator)(this._delegate,e,r,s)}enableNetwork(){return(0,t.enableNetwork)(this._delegate)}disableNetwork(){return(0,t.disableNetwork)(this._delegate)}enablePersistence(e){let r=!1,s=!1;return e&&(r=!!e.synchronizeTabs,s=!!e.experimentalForceOwningTab,(0,t._validateIsNotUsedTogether)("synchronizeTabs",r,"experimentalForceOwningTab",s)),r?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,s)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return(0,t.waitForPendingWrites)(this._delegate)}onSnapshotsInSync(e){return(0,t.onSnapshotsInSync)(this._delegate,e)}get app(){if(!this._appCompat)throw new t.FirestoreError("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new P(this,(0,t.collection)(this._delegate,e))}catch(r){throw b(r,"collection()","Firestore.collection()")}}doc(e){try{return new v(this,(0,t.doc)(this._delegate,e))}catch(r){throw b(r,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new E(this,(0,t.collectionGroup)(this._delegate,e))}catch(r){throw b(r,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(e){return(0,t.runTransaction)(this._delegate,t=>e(new p(this,t)))}batch(){return(0,t.ensureFirestoreConfigured)(this._delegate),new w(new t.WriteBatch(this._delegate,e=>(0,t.executeWrite)(this._delegate,e)))}loadBundle(e){return(0,t.loadBundle)(this._delegate,e)}namedQuery(e){return(0,t.namedQuery)(this._delegate,e).then(e=>e?new E(this,e):null)}}class f extends t.AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new c(new t.Bytes(e))}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return v.forKey(t,this.firestore,null)}}function m(e){(0,t.setLogLevel)(e)}class p{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new f(e)}get(e){const r=x(e);return this._delegate.get(r).then(e=>new F(this._firestore,new t.DocumentSnapshot(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,r.converter)))}set(e,t,r){const s=x(e);return r?(o("Transaction.set",r),this._delegate.set(s,t,r)):this._delegate.set(s,t),this}update(e,t,r,...s){const n=x(e);return 2===arguments.length?this._delegate.update(n,t):this._delegate.update(n,t,r,...s),this}delete(e){const t=x(e);return this._delegate.delete(t),this}}class w{constructor(e){this._delegate=e}set(e,t,r){const s=x(e);return r?(o("WriteBatch.set",r),this._delegate.set(s,t,r)):this._delegate.set(s,t),this}update(e,t,r,...s){const n=x(e);return 2===arguments.length?this._delegate.update(n,t):this._delegate.update(n,t,r,...s),this}delete(e){const t=x(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class y{constructor(e,t,r){this._firestore=e,this._userDataWriter=t,this._delegate=r}fromFirestore(e,r){const s=new t.QueryDocumentSnapshot(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new S(this._firestore,s),null!=r?r:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const r=y.INSTANCES;let s=r.get(e);s||(s=new WeakMap,r.set(e,s));let n=s.get(t);return n||(n=new y(e,new f(e),t),s.set(t,n)),n}}y.INSTANCES=new WeakMap;class v{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new f(e)}static forPath(e,r,s){if(e.length%2!=0)throw new t.FirestoreError("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new v(r,new t.DocumentReference(r._delegate,s,new t._DocumentKey(e)))}static forKey(e,r,s){return new v(r,new t.DocumentReference(r._delegate,s,e))}get id(){return this._delegate.id}get parent(){return new P(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new P(this.firestore,(0,t.collection)(this._delegate,e))}catch(r){throw b(r,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=(0,r.getModularInstance)(e))instanceof t.DocumentReference&&(0,t.refEqual)(this._delegate,e)}set(e,r){r=o("DocumentReference.set",r);try{return r?(0,t.setDoc)(this._delegate,e,r):(0,t.setDoc)(this._delegate,e)}catch(s){throw b(s,"setDoc()","DocumentReference.set()")}}update(e,r,...s){try{return 1===arguments.length?(0,t.updateDoc)(this._delegate,e):(0,t.updateDoc)(this._delegate,e,r,...s)}catch(n){throw b(n,"updateDoc()","DocumentReference.update()")}}delete(){return(0,t.deleteDoc)(this._delegate)}onSnapshot(...e){const r=D(e),s=I(e,e=>new F(this.firestore,new t.DocumentSnapshot(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return(0,t.onSnapshot)(this._delegate,r,s)}get(e){let r;return(r="cache"===(null==e?void 0:e.source)?(0,t.getDocFromCache)(this._delegate):"server"===(null==e?void 0:e.source)?(0,t.getDocFromServer)(this._delegate):(0,t.getDoc)(this._delegate)).then(e=>new F(this.firestore,new t.DocumentSnapshot(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new v(this.firestore,e?this._delegate.withConverter(y.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function b(e,t,r){return e.message=e.message.replace(t,r),e}function D(e){for(const t of e)if("object"==typeof t&&!h(t))return t;return{}}function I(e,t){var r,s;let n;return{next:e=>{n.next&&n.next(t(e))},error:null===(r=(n=h(e[0])?e[0]:h(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]}).error)||void 0===r?void 0:r.bind(n),complete:null===(s=n.complete)||void 0===s?void 0:s.bind(n)}}class F{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new v(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return(0,t.snapshotEqual)(this._delegate,e._delegate)}}class S extends F{data(e){const r=this._delegate.data(e);return(0,t._debugAssert)(void 0!==r,"Document in a QueryDocumentSnapshot should exist"),r}}class E{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new f(e)}where(e,r,s){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.where)(e,r,s)))}catch(n){throw b(n,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(e,r){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.orderBy)(e,r)))}catch(s){throw b(s,/(orderBy|where)\(\)/,"Query.$1()")}}limit(e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.limit)(e)))}catch(r){throw b(r,"limit()","Query.limit()")}}limitToLast(e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.limitToLast)(e)))}catch(r){throw b(r,"limitToLast()","Query.limitToLast()")}}startAt(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.startAt)(...e)))}catch(r){throw b(r,"startAt()","Query.startAt()")}}startAfter(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.startAfter)(...e)))}catch(r){throw b(r,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.endBefore)(...e)))}catch(r){throw b(r,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.endAt)(...e)))}catch(r){throw b(r,"endAt()","Query.endAt()")}}isEqual(e){return(0,t.queryEqual)(this._delegate,e._delegate)}get(e){let r;return(r="cache"===(null==e?void 0:e.source)?(0,t.getDocsFromCache)(this._delegate):"server"===(null==e?void 0:e.source)?(0,t.getDocsFromServer)(this._delegate):(0,t.getDocs)(this._delegate)).then(e=>new C(this.firestore,new t.QuerySnapshot(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){const r=D(e),s=I(e,e=>new C(this.firestore,new t.QuerySnapshot(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return(0,t.onSnapshot)(this._delegate,r,s)}withConverter(e){return new E(this.firestore,e?this._delegate.withConverter(y.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class q{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new S(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class C{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new E(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new S(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new q(this._firestore,e))}forEach(e,t){this._delegate.forEach(r=>{e.call(t,new S(this._firestore,r))})}isEqual(e){return(0,t.snapshotEqual)(this._delegate,e._delegate)}}class P extends E{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){const e=this._delegate.parent;return e?new v(this.firestore,e):null}doc(e){try{return new v(this.firestore,void 0===e?(0,t.doc)(this._delegate):(0,t.doc)(this._delegate,e))}catch(r){throw b(r,"doc()","CollectionReference.doc()")}}add(e){return(0,t.addDoc)(this._delegate,e).then(e=>new v(this.firestore,e))}isEqual(e){return(0,t.refEqual)(this._delegate,e._delegate)}withConverter(e){return new P(this.firestore,e?this._delegate.withConverter(y.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function x(e){return(0,t._cast)(e,t.DocumentReference)}class A{constructor(...e){this._delegate=new t.FieldPath(...e)}static documentId(){return new A(t._FieldPath.keyField().canonicalString())}isEqual(e){return(e=(0,r.getModularInstance)(e))instanceof t.FieldPath&&this._delegate._internalPath.isEqual(e._internalPath)}}class B{constructor(e){this._delegate=e}static serverTimestamp(){const e=(0,t.serverTimestamp)();return e._methodName="FieldValue.serverTimestamp",new B(e)}static delete(){const e=(0,t.deleteField)();return e._methodName="FieldValue.delete",new B(e)}static arrayUnion(...e){const r=(0,t.arrayUnion)(...e);return r._methodName="FieldValue.arrayUnion",new B(r)}static arrayRemove(...e){const r=(0,t.arrayRemove)(...e);return r._methodName="FieldValue.arrayRemove",new B(r)}static increment(e){const r=(0,t.increment)(e);return r._methodName="FieldValue.increment",new B(r)}isEqual(e){return this._delegate.isEqual(e._delegate)}}const T={Firestore:_,GeoPoint:t.GeoPoint,Timestamp:t.Timestamp,Blob:c,Transaction:p,WriteBatch:w,DocumentReference:v,DocumentSnapshot:F,Query:E,QueryDocumentSnapshot:S,QuerySnapshot:C,CollectionReference:P,FieldPath:A,FieldValue:B,setLogLevel:m,CACHE_SIZE_UNLIMITED:t.CACHE_SIZE_UNLIMITED};function N(e,t){e.INTERNAL.registerComponent(new s.Component("firestore-compat",e=>{const r=e.getProvider("app-compat").getImmediate(),s=e.getProvider("firestore").getImmediate();return t(r,s)},"PUBLIC").setServiceProps(Object.assign({},T)))}function W(e){N(e,(e,t)=>new _(e,t,new g)),e.registerVersion(i,a)}W(e.default);
|
|
509
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerFirestore=W;var e=n(require("@firebase/app-compat")),t=require("@firebase/firestore"),r=require("@firebase/util"),s=require("@firebase/component");function n(e){return e&&e.__esModule?e:{default:e}}const i="@firebase/firestore-compat",a="0.3.5";function o(e,r){if(void 0===r)return{merge:!1};if(void 0!==r.mergeFields&&void 0!==r.merge)throw new t.FirestoreError("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return r}function l(){if("undefined"==typeof Uint8Array)throw new t.FirestoreError("unimplemented","Uint8Arrays are not available in this environment.")}function d(){if(!(0,t._isBase64Available)())throw new t.FirestoreError("unimplemented","Blobs are unavailable in Firestore in this environment.")}class c{constructor(e){this._delegate=e}static fromBase64String(e){return d(),new c(t.Bytes.fromBase64String(e))}static fromUint8Array(e){return l(),new c(t.Bytes.fromUint8Array(e))}toBase64(){return d(),this._delegate.toBase64()}toUint8Array(){return l(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function h(e){return u(e,["next","error","complete"])}function u(e,t){if("object"!=typeof e||null===e)return!1;const r=e;for(const s of t)if(s in r&&"function"==typeof r[s])return!0;return!1}class g{enableIndexedDbPersistence(e,r){return(0,t.enableIndexedDbPersistence)(e._delegate,{forceOwnership:r})}enableMultiTabIndexedDbPersistence(e){return(0,t.enableMultiTabIndexedDbPersistence)(e._delegate)}clearIndexedDbPersistence(e){return(0,t.clearIndexedDbPersistence)(e._delegate)}}class _{constructor(e,r,s){this._delegate=r,this._persistenceProvider=s,this.INTERNAL={delete:()=>this.terminate()},e instanceof t._DatabaseId||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){const r=this._delegate._getSettings();e.merge||r.host===e.host||(0,t._logWarn)("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},r),e)).merge,this._delegate._setSettings(e)}useEmulator(e,r,s={}){(0,t.connectFirestoreEmulator)(this._delegate,e,r,s)}enableNetwork(){return(0,t.enableNetwork)(this._delegate)}disableNetwork(){return(0,t.disableNetwork)(this._delegate)}enablePersistence(e){let r=!1,s=!1;return e&&(r=!!e.synchronizeTabs,s=!!e.experimentalForceOwningTab,(0,t._validateIsNotUsedTogether)("synchronizeTabs",r,"experimentalForceOwningTab",s)),r?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,s)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return(0,t.waitForPendingWrites)(this._delegate)}onSnapshotsInSync(e){return(0,t.onSnapshotsInSync)(this._delegate,e)}get app(){if(!this._appCompat)throw new t.FirestoreError("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new P(this,(0,t.collection)(this._delegate,e))}catch(r){throw b(r,"collection()","Firestore.collection()")}}doc(e){try{return new v(this,(0,t.doc)(this._delegate,e))}catch(r){throw b(r,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new E(this,(0,t.collectionGroup)(this._delegate,e))}catch(r){throw b(r,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(e){return(0,t.runTransaction)(this._delegate,t=>e(new p(this,t)))}batch(){return(0,t.ensureFirestoreConfigured)(this._delegate),new w(new t.WriteBatch(this._delegate,e=>(0,t.executeWrite)(this._delegate,e)))}loadBundle(e){return(0,t.loadBundle)(this._delegate,e)}namedQuery(e){return(0,t.namedQuery)(this._delegate,e).then(e=>e?new E(this,e):null)}}class f extends t.AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new c(new t.Bytes(e))}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return v.forKey(t,this.firestore,null)}}function m(e){(0,t.setLogLevel)(e)}class p{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new f(e)}get(e){const r=x(e);return this._delegate.get(r).then(e=>new F(this._firestore,new t.DocumentSnapshot(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,r.converter)))}set(e,t,r){const s=x(e);return r?(o("Transaction.set",r),this._delegate.set(s,t,r)):this._delegate.set(s,t),this}update(e,t,r,...s){const n=x(e);return 2===arguments.length?this._delegate.update(n,t):this._delegate.update(n,t,r,...s),this}delete(e){const t=x(e);return this._delegate.delete(t),this}}class w{constructor(e){this._delegate=e}set(e,t,r){const s=x(e);return r?(o("WriteBatch.set",r),this._delegate.set(s,t,r)):this._delegate.set(s,t),this}update(e,t,r,...s){const n=x(e);return 2===arguments.length?this._delegate.update(n,t):this._delegate.update(n,t,r,...s),this}delete(e){const t=x(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class y{constructor(e,t,r){this._firestore=e,this._userDataWriter=t,this._delegate=r}fromFirestore(e,r){const s=new t.QueryDocumentSnapshot(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new S(this._firestore,s),null!=r?r:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const r=y.INSTANCES;let s=r.get(e);s||(s=new WeakMap,r.set(e,s));let n=s.get(t);return n||(n=new y(e,new f(e),t),s.set(t,n)),n}}y.INSTANCES=new WeakMap;class v{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new f(e)}static forPath(e,r,s){if(e.length%2!=0)throw new t.FirestoreError("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new v(r,new t.DocumentReference(r._delegate,s,new t._DocumentKey(e)))}static forKey(e,r,s){return new v(r,new t.DocumentReference(r._delegate,s,e))}get id(){return this._delegate.id}get parent(){return new P(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new P(this.firestore,(0,t.collection)(this._delegate,e))}catch(r){throw b(r,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=(0,r.getModularInstance)(e))instanceof t.DocumentReference&&(0,t.refEqual)(this._delegate,e)}set(e,r){r=o("DocumentReference.set",r);try{return r?(0,t.setDoc)(this._delegate,e,r):(0,t.setDoc)(this._delegate,e)}catch(s){throw b(s,"setDoc()","DocumentReference.set()")}}update(e,r,...s){try{return 1===arguments.length?(0,t.updateDoc)(this._delegate,e):(0,t.updateDoc)(this._delegate,e,r,...s)}catch(n){throw b(n,"updateDoc()","DocumentReference.update()")}}delete(){return(0,t.deleteDoc)(this._delegate)}onSnapshot(...e){const r=D(e),s=I(e,e=>new F(this.firestore,new t.DocumentSnapshot(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return(0,t.onSnapshot)(this._delegate,r,s)}get(e){let r;return(r="cache"===(null==e?void 0:e.source)?(0,t.getDocFromCache)(this._delegate):"server"===(null==e?void 0:e.source)?(0,t.getDocFromServer)(this._delegate):(0,t.getDoc)(this._delegate)).then(e=>new F(this.firestore,new t.DocumentSnapshot(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new v(this.firestore,e?this._delegate.withConverter(y.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function b(e,t,r){return e.message=e.message.replace(t,r),e}function D(e){for(const t of e)if("object"==typeof t&&!h(t))return t;return{}}function I(e,t){var r,s;let n;return{next:e=>{n.next&&n.next(t(e))},error:null===(r=(n=h(e[0])?e[0]:h(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]}).error)||void 0===r?void 0:r.bind(n),complete:null===(s=n.complete)||void 0===s?void 0:s.bind(n)}}class F{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new v(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return(0,t.snapshotEqual)(this._delegate,e._delegate)}}class S extends F{data(e){const r=this._delegate.data(e);return(0,t._debugAssert)(void 0!==r,"Document in a QueryDocumentSnapshot should exist"),r}}class E{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new f(e)}where(e,r,s){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.where)(e,r,s)))}catch(n){throw b(n,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(e,r){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.orderBy)(e,r)))}catch(s){throw b(s,/(orderBy|where)\(\)/,"Query.$1()")}}limit(e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.limit)(e)))}catch(r){throw b(r,"limit()","Query.limit()")}}limitToLast(e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.limitToLast)(e)))}catch(r){throw b(r,"limitToLast()","Query.limitToLast()")}}startAt(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.startAt)(...e)))}catch(r){throw b(r,"startAt()","Query.startAt()")}}startAfter(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.startAfter)(...e)))}catch(r){throw b(r,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.endBefore)(...e)))}catch(r){throw b(r,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new E(this.firestore,(0,t.query)(this._delegate,(0,t.endAt)(...e)))}catch(r){throw b(r,"endAt()","Query.endAt()")}}isEqual(e){return(0,t.queryEqual)(this._delegate,e._delegate)}get(e){let r;return(r="cache"===(null==e?void 0:e.source)?(0,t.getDocsFromCache)(this._delegate):"server"===(null==e?void 0:e.source)?(0,t.getDocsFromServer)(this._delegate):(0,t.getDocs)(this._delegate)).then(e=>new C(this.firestore,new t.QuerySnapshot(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){const r=D(e),s=I(e,e=>new C(this.firestore,new t.QuerySnapshot(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return(0,t.onSnapshot)(this._delegate,r,s)}withConverter(e){return new E(this.firestore,e?this._delegate.withConverter(y.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class q{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new S(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class C{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new E(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new S(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new q(this._firestore,e))}forEach(e,t){this._delegate.forEach(r=>{e.call(t,new S(this._firestore,r))})}isEqual(e){return(0,t.snapshotEqual)(this._delegate,e._delegate)}}class P extends E{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){const e=this._delegate.parent;return e?new v(this.firestore,e):null}doc(e){try{return new v(this.firestore,void 0===e?(0,t.doc)(this._delegate):(0,t.doc)(this._delegate,e))}catch(r){throw b(r,"doc()","CollectionReference.doc()")}}add(e){return(0,t.addDoc)(this._delegate,e).then(e=>new v(this.firestore,e))}isEqual(e){return(0,t.refEqual)(this._delegate,e._delegate)}withConverter(e){return new P(this.firestore,e?this._delegate.withConverter(y.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function x(e){return(0,t._cast)(e,t.DocumentReference)}class A{constructor(...e){this._delegate=new t.FieldPath(...e)}static documentId(){return new A(t._FieldPath.keyField().canonicalString())}isEqual(e){return(e=(0,r.getModularInstance)(e))instanceof t.FieldPath&&this._delegate._internalPath.isEqual(e._internalPath)}}class B{constructor(e){this._delegate=e}static serverTimestamp(){const e=(0,t.serverTimestamp)();return e._methodName="FieldValue.serverTimestamp",new B(e)}static delete(){const e=(0,t.deleteField)();return e._methodName="FieldValue.delete",new B(e)}static arrayUnion(...e){const r=(0,t.arrayUnion)(...e);return r._methodName="FieldValue.arrayUnion",new B(r)}static arrayRemove(...e){const r=(0,t.arrayRemove)(...e);return r._methodName="FieldValue.arrayRemove",new B(r)}static increment(e){const r=(0,t.increment)(e);return r._methodName="FieldValue.increment",new B(r)}isEqual(e){return this._delegate.isEqual(e._delegate)}}const T={Firestore:_,GeoPoint:t.GeoPoint,Timestamp:t.Timestamp,Blob:c,Transaction:p,WriteBatch:w,DocumentReference:v,DocumentSnapshot:F,Query:E,QueryDocumentSnapshot:S,QuerySnapshot:C,CollectionReference:P,FieldPath:A,FieldValue:B,setLogLevel:m,CACHE_SIZE_UNLIMITED:t.CACHE_SIZE_UNLIMITED};function N(e,t){e.INTERNAL.registerComponent(new s.Component("firestore-compat",e=>{const r=e.getProvider("app-compat").getImmediate(),s=e.getProvider("firestore").getImmediate();return t(r,s)},"PUBLIC").setServiceProps(Object.assign({},T)))}function W(e){N(e,(e,t)=>new _(e,t,new g)),e.registerVersion(i,a)}W(e.default);
|
|
510
510
|
},{"@firebase/app-compat":"CMFQ","@firebase/firestore":"lBbe","@firebase/util":"chA2","@firebase/component":"vhY9"}],"oDOu":[function(require,module,exports) {
|
|
511
511
|
"use strict";require("@firebase/firestore-compat");
|
|
512
512
|
},{"@firebase/firestore-compat":"LeU4"}],"TX5A":[function(require,module,exports) {
|
|
@@ -538,7 +538,7 @@ var r=Array.isArray;function n(n){if(r(n))return t(n);var e=null,u="string"==typ
|
|
|
538
538
|
},{"rxjs":"Zr8e","rxjs/operators":"v3iE","fast-deep-equal":"jIGR","../types/status":"Ttuy"}],"qny3":[function(require,module,exports) {
|
|
539
539
|
"use strict";function r(r,n){return i(r)||o(r,n)||e(r,n)||t()}function t(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function e(r,t){if(r){if("string"==typeof r)return n(r,t);var e=Object.prototype.toString.call(r).slice(8,-1);return"Object"===e&&r.constructor&&(e=r.constructor.name),"Map"===e||"Set"===e?Array.from(r):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?n(r,t):void 0}}function n(r,t){(null==t||t>r.length)&&(t=r.length);for(var e=0,n=new Array(t);e<t;e++)n[e]=r[e];return n}function o(r,t){var e=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=e){var n,o,i,u,a=[],l=!0,c=!1;try{if(i=(e=e.call(r)).next,0===t){if(Object(e)!==e)return;l=!1}else for(;!(l=(n=i.call(e)).done)&&(a.push(n.value),a.length!==t);l=!0);}catch(f){c=!0,o=f}finally{try{if(!l&&null!=e.return&&(u=e.return(),Object(u)!==u))return}finally{if(c)throw o}}return a}}function i(r){if(Array.isArray(r))return r}Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterInternalKeys=void 0;var u=require("rxjs"),a=require("rxjs/operators");function l(){return(0,u.pipe)((0,a.map)(function(t){return t?Object.entries(t).reduce(function(t,e){var n=r(e,2),o=n[0],i=n[1];return o.startsWith("__")||(t[o]=i),t},{}):t}))}exports.filterInternalKeys=l;
|
|
540
540
|
},{"rxjs":"Zr8e","rxjs/operators":"v3iE"}],"LXvB":[function(require,module,exports) {
|
|
541
|
-
"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){return s(e)||o(e,t)||n(e,t)||r()}function r(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(e,t){if(e){if("string"==typeof e)return i(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function o(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,s,a=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(f){u=!0,i=f}finally{try{if(!c&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw i}}return a}}function s(e){if(Array.isArray(e))return e}function a(){a=function(){return t};var t={},r=Object.prototype,n=r.hasOwnProperty,i=Object.defineProperty||function(e,t,r){e[t]=r.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",c=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(U){f=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var o=t&&t.prototype instanceof p?t:p,s=Object.create(o.prototype),a=new E(n||[]);return i(s,"_invoke",{value:D(e,r,a)}),s}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(U){return{type:"throw",arg:U}}}t.wrap=l;var v={};function p(){}function d(){}function y(){}var b={};f(b,s,function(){return this});var m=Object.getPrototypeOf,g=m&&m(m(O([])));g&&g!==r&&n.call(g,s)&&(b=g);var w=y.prototype=p.prototype=Object.create(b);function x(e){["next","throw","return"].forEach(function(t){f(e,t,function(e){return this._invoke(t,e)})})}function k(t,r){var o;i(this,"_invoke",{value:function(i,s){function a(){return new r(function(o,a){!function i(o,s,a,c){var u=h(t[o],t,s);if("throw"!==u.type){var f=u.arg,l=f.value;return l&&"object"==e(l)&&n.call(l,"__await")?r.resolve(l.__await).then(function(e){i("next",e,a,c)},function(e){i("throw",e,a,c)}):r.resolve(l).then(function(e){f.value=e,a(f)},function(e){return i("throw",e,a,c)})}c(u.arg)}(i,s,o,a)})}return o=o?o.then(a,a):a()}})}function D(e,t,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return L()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=S(s,r);if(a){if(a===v)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===v)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),v;var i=h(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,v;var o=i.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,v):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function E(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function O(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return i.next=i}}return{next:L}}function L(){return{value:void 0,done:!0}}return d.prototype=y,i(w,"constructor",{value:y,configurable:!0}),i(y,"constructor",{value:d,configurable:!0}),d.displayName=f(y,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,f(e,u,"GeneratorFunction")),e.prototype=Object.create(w),e},t.awrap=function(e){return{__await:e}},x(k.prototype),f(k.prototype,c,function(){return this}),t.AsyncIterator=k,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var s=new k(l(e,r,n,i),o);return t.isGeneratorFunction(r)?s:s.next().then(function(e){return e.done?e.value:s.next()})},x(w),f(w,u,"Generator"),f(w,s,function(){return this}),f(w,"toString",function(){return"[object Generator]"}),t.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=O,E.prototype={constructor:E,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(j),!e)for(var t in this)"t"===t.charAt(0)&&n.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(r,n){return s.type="throw",s.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var a=n.call(o,"catchLoc"),c=n.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,v):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),v},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;j(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:O(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),v}},t}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,l(n.key),n)}}function f(e,t,r){return t&&u(e.prototype,t),r&&u(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(t){var r=h(t,"string");return"symbol"===e(r)?r:String(r)}function h(t,r){if("object"!==e(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var i=n.call(t,r||"default");if("object"!==e(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}var v=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(t){o(t)}}function a(e){try{c(n.throw(e))}catch(t){o(t)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CloudClient=exports.SERVER_TIMESTAMP=exports.createUser=exports.credentialWithLink=void 0;var p=require("rxjs"),d=require("rxjs"),y=require("rxjs/operators"),b=require("./firebase"),m=require("../timesync"),g=require("../subscriptions/SubscriptionManager"),w=require("../utils/heartbeat"),x=require("../utils/filterInternalKeys"),k=require("./firebase");Object.defineProperty(exports,"credentialWithLink",{enumerable:!0,get:function(){return k.credentialWithLink}}),Object.defineProperty(exports,"createUser",{enumerable:!0,get:function(){return k.createUser}}),Object.defineProperty(exports,"SERVER_TIMESTAMP",{enumerable:!0,get:function(){return k.SERVER_TIMESTAMP}});var D=function(){function e(t){var r=this;c(this,e),this._selectedDevice=new p.ReplaySubject(1),this.options=t,this.subscriptionManager=new g.SubscriptionManager,this.firebaseApp=new b.FirebaseApp(t),this.firebaseUser=new b.FirebaseUser(this.firebaseApp),this._selectedDevice.next(void 0),this.status$=(0,w.heartbeatAwareStatus)(this.observeNamespace("status").pipe((0,y.share)())).pipe((0,x.filterInternalKeys)(),(0,y.shareReplay)(1)),this.osVersion$=this.observeNamespace("info/osVersion").pipe((0,y.shareReplay)(1)),this.firebaseUser.onAuthStateChanged().subscribe(function(e){r.user=e}),this.firebaseUser.onUserClaimsChange().subscribe(function(e){r.userClaims=e}),this.onDeviceChange().subscribe(function(e){r.firebaseDevice&&r.firebaseDevice.disconnect(),e&&(r.firebaseDevice=new b.FirebaseDevice({deviceId:e.deviceId,firebaseApp:r.firebaseApp,dependencies:{subscriptionManager:r.subscriptionManager}}),r.options.timesync&&(r.timesync=new m.Timesync({status$:r.status(),getTimesync:r.firebaseDevice.getTimesync.bind(r.firebaseDevice)})))})}return f(e,[{key:"onDeviceChange",value:function(){return this._selectedDevice.asObservable().pipe((0,y.filter)(function(e){return void 0!==e}))}},{key:"osVersion",value:function(){return this.osVersion$}},{key:"setAutoSelectedDevice",value:function(){return v(this,void 0,void 0,a().mark(function e(){var t=this;return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.options.deviceId){e.next=4;break}return e.next=3,this.selectDevice(function(e){return e.find(function(e){return e.deviceId===t.options.deviceId})});case 3:return e.abrupt("return",e.sent);case 4:if(this.options.deviceId||!this.options.autoSelectDevice){e.next=8;break}return e.next=7,this.selectDevice(function(e){return e[0]});case 7:return e.abrupt("return",e.sent);case 8:return e.abrupt("return",null);case 9:case"end":return e.stop()}},e,this)}))}},{key:"actions",get:function(){var e=this;return{dispatch:function(t){return e.firebaseDevice.dispatchAction(t)}}}},{key:"dispatchAction",value:function(e){return v(this,void 0,void 0,a().mark(function t(){return a().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.firebaseDevice.dispatchAction(e);case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}},t,this)}))}},{key:"disconnect",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.firebaseApp.disconnect());case 1:case"end":return e.stop()}},e,this)}))}},{key:"getInfo",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.firebaseDevice.getInfo();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e,this)}))}},{key:"login",value:function(e){return v(this,void 0,void 0,a().mark(function t(){var r,n;return a().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.user){t.next=2;break}return t.abrupt("return",Promise.reject("Already logged in."));case 2:return t.next=4,this.firebaseUser.login(e);case 4:return r=t.sent,t.next=7,this.setAutoSelectedDevice();case 7:return n=t.sent,t.abrupt("return",Object.assign(Object.assign({},r),{selectedDevice:n}));case 9:case"end":return t.stop()}},t,this)}))}},{key:"logout",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.firebaseDevice&&this.firebaseDevice.disconnect(),e.next=3,this.firebaseUser.logout();case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}},e,this)}))}},{key:"onAuthStateChanged",value:function(){var e=this;return this.firebaseUser.onAuthStateChanged().pipe((0,y.switchMap)(function(t){return v(e,void 0,void 0,a().mark(function e(){var r;return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}return e.abrupt("return",null);case 2:if(!this.didSelectDevice()){e.next=8;break}return e.next=5,this.getSelectedDevice();case 5:e.t0=e.sent,e.next=11;break;case 8:return e.next=10,this.setAutoSelectedDevice();case 10:e.t0=e.sent;case 11:return r=e.t0,e.abrupt("return",Object.assign(Object.assign({},t),{selectedDevice:r}));case 13:case"end":return e.stop()}},e,this)}))}))}},{key:"getDevices",value:function(){return this.firebaseUser.getDevices()}},{key:"addDevice",value:function(e){return this.firebaseUser.addDevice(e)}},{key:"removeDevice",value:function(e){return v(this,void 0,void 0,a().mark(function r(){var n,i,o,s,c;return a().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.firebaseUser.removeDevice(e).then(function(){return[!1]}).catch(function(e){return[!0,e]});case 2:if(n=r.sent,i=t(n,2),o=i[0],s=i[1],!o){r.next=8;break}return r.abrupt("return",Promise.reject(s));case 8:return r.next=10,this.getSelectedDevice();case 10:(null==(c=r.sent)?void 0:c.deviceId)===e&&this._selectedDevice.next(null);case 12:case"end":return r.stop()}},r,this)}))}},{key:"transferDevice",value:function(e){return v(this,void 0,void 0,a().mark(function r(){var n,i,o,s,c;return a().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.firebaseUser.transferDevice(e).then(function(){return[!1]}).catch(function(e){return[!0,e]});case 2:if(n=r.sent,i=t(n,2),o=i[0],s=i[1],!o){r.next=8;break}return r.abrupt("return",Promise.reject(s));case 8:return r.next=10,this.getSelectedDevice();case 10:(null==(c=r.sent)?void 0:c.deviceId)===e.deviceId&&this._selectedDevice.next(null);case 12:case"end":return r.stop()}},r,this)}))}},{key:"onUserDevicesChange",value:function(){return this.firebaseUser.onUserDevicesChange()}},{key:"onUserClaimsChange",value:function(){return this.firebaseUser.onUserClaimsChange()}},{key:"didSelectDevice",value:function(){return v(this,void 0,void 0,a().mark(function e(){var t;return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getSelectedDevice();case 2:return t=e.sent,e.abrupt("return",!!t);case 4:case"end":return e.stop()}},e,this)}))}},{key:"selectDevice",value:function(e){return v(this,void 0,void 0,a().mark(function r(){var n,i,o;return a().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.getDevices();case 2:if(n=r.sent){r.next=5;break}return r.abrupt("return",Promise.reject("Did not find any devices for this user. Make sure your device is claimed by your Neurosity account."));case 5:if(i=function(r){return r.find(function(r){if(!Array.isArray(e))return!1;var n=t(e,2),i=n[0],o=n[1];return JSON.stringify(null==r?void 0:r[i])===JSON.stringify(o)})},o="function"==typeof e?e(n):i(n)){r.next=9;break}return r.abrupt("return",Promise.reject("A device was not provided. Try returning a device from the devicesList provided in the callback."));case 9:return r.next=11,this.firebaseUser.hasDevicePermission(o.deviceId);case 11:if(r.sent){r.next=14;break}return r.abrupt("return",Promise.reject("Rejected device access due to permissions."));case 14:return this._selectedDevice.next(o),r.abrupt("return",o);case 16:case"end":return r.stop()}},r,this)}))}},{key:"getSelectedDevice",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,d.firstValueFrom)(this._selectedDevice);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e,this)}))}},{key:"status",value:function(){return this.status$}},{key:"observeNamespace",value:function(e){var t=this;return this.onDeviceChange().pipe((0,y.switchMap)(function(r){return r?(0,d.fromEventPattern)(function(r){return t.firebaseDevice.onNamespace(e,r)},function(r){return t.firebaseDevice.offNamespace(e,r)}):p.EMPTY}))}},{key:"onceNamespace",value:function(e){return v(this,void 0,void 0,a().mark(function t(){return a().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.firebaseDevice.onceNamespace(e);case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}},t,this)}))}},{key:"metrics",get:function(){var e=this;return{next:function(t,r){e.firebaseDevice.nextMetric(t,r)},on:function(t,r){return e.firebaseDevice.onMetric(t,r)},subscribe:function(t){var r=e.firebaseDevice.subscribeToMetric(t);return e.subscriptionManager.add(r),r},unsubscribe:function(t,r){e.subscriptionManager.remove(t),e.firebaseDevice.unsubscribeFromMetric(t),e.firebaseDevice.removeMetricListener(t,r)}}}},{key:"createAccount",value:function(e){return this.firebaseUser.createAccount(e)}},{key:"deleteAccount",value:function(){return this.firebaseUser.deleteAccount()}},{key:"createBluetoothToken",value:function(){return this.firebaseDevice.createBluetoothToken()}},{key:"createCustomToken",value:function(){return this.firebaseUser.createCustomToken()}},{key:"removeOAuthAccess",value:function(){return this.firebaseUser.removeOAuthAccess()}},{key:"onUserExperiments",value:function(){return this.firebaseUser.onUserExperiments()}},{key:"deleteUserExperiment",value:function(e){return this.firebaseUser.deleteUserExperiment(e)}},{key:"skills",get:function(){var e=this;return{get:function(t){return v(e,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.firebaseDevice.getSkill(t));case 1:case"end":return e.stop()}},e,this)}))}}}},{key:"timestamp",get:function(){return this.options.timesync?this.timesync.timestamp:Date.now()}},{key:"getTimesyncOffset",value:function(){return this.timesync.offset}},{key:"changeSettings",value:function(e){return this.firebaseDevice.changeSettings(e)}},{key:"goOffline",value:function(){this.firebaseApp.goOffline()}},{key:"goOnline",value:function(){this.firebaseApp.goOnline()}},{key:"__getApp",value:function(){return this.firebaseApp.app}}]),e}();exports.CloudClient=D;
|
|
541
|
+
"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){return s(e)||o(e,t)||n(e,t)||r()}function r(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(e,t){if(e){if("string"==typeof e)return i(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function o(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,s,a=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(f){u=!0,i=f}finally{try{if(!c&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw i}}return a}}function s(e){if(Array.isArray(e))return e}function a(){a=function(){return t};var t={},r=Object.prototype,n=r.hasOwnProperty,i=Object.defineProperty||function(e,t,r){e[t]=r.value},o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",c=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(U){f=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var o=t&&t.prototype instanceof p?t:p,s=Object.create(o.prototype),a=new E(n||[]);return i(s,"_invoke",{value:D(e,r,a)}),s}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(U){return{type:"throw",arg:U}}}t.wrap=l;var v={};function p(){}function d(){}function y(){}var b={};f(b,s,function(){return this});var m=Object.getPrototypeOf,g=m&&m(m(O([])));g&&g!==r&&n.call(g,s)&&(b=g);var w=y.prototype=p.prototype=Object.create(b);function x(e){["next","throw","return"].forEach(function(t){f(e,t,function(e){return this._invoke(t,e)})})}function k(t,r){var o;i(this,"_invoke",{value:function(i,s){function a(){return new r(function(o,a){!function i(o,s,a,c){var u=h(t[o],t,s);if("throw"!==u.type){var f=u.arg,l=f.value;return l&&"object"==e(l)&&n.call(l,"__await")?r.resolve(l.__await).then(function(e){i("next",e,a,c)},function(e){i("throw",e,a,c)}):r.resolve(l).then(function(e){f.value=e,a(f)},function(e){return i("throw",e,a,c)})}c(u.arg)}(i,s,o,a)})}return o=o?o.then(a,a):a()}})}function D(e,t,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return L()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=S(s,r);if(a){if(a===v)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===v)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),v;var i=h(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,v;var o=i.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,v):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function E(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function O(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;)if(n.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return i.next=i}}return{next:L}}function L(){return{value:void 0,done:!0}}return d.prototype=y,i(w,"constructor",{value:y,configurable:!0}),i(y,"constructor",{value:d,configurable:!0}),d.displayName=f(y,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,f(e,u,"GeneratorFunction")),e.prototype=Object.create(w),e},t.awrap=function(e){return{__await:e}},x(k.prototype),f(k.prototype,c,function(){return this}),t.AsyncIterator=k,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var s=new k(l(e,r,n,i),o);return t.isGeneratorFunction(r)?s:s.next().then(function(e){return e.done?e.value:s.next()})},x(w),f(w,u,"Generator"),f(w,s,function(){return this}),f(w,"toString",function(){return"[object Generator]"}),t.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=O,E.prototype={constructor:E,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(j),!e)for(var t in this)"t"===t.charAt(0)&&n.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(r,n){return s.type="throw",s.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var a=n.call(o,"catchLoc"),c=n.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,v):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),v},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;j(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:O(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),v}},t}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,l(n.key),n)}}function f(e,t,r){return t&&u(e.prototype,t),r&&u(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(t){var r=h(t,"string");return"symbol"===e(r)?r:String(r)}function h(t,r){if("object"!==e(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var i=n.call(t,r||"default");if("object"!==e(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}var v=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(t){o(t)}}function a(e){try{c(n.throw(e))}catch(t){o(t)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CloudClient=exports.SERVER_TIMESTAMP=exports.createUser=exports.credentialWithLink=void 0;var p=require("rxjs"),d=require("rxjs"),y=require("rxjs/operators"),b=require("./firebase"),m=require("../timesync"),g=require("../subscriptions/SubscriptionManager"),w=require("../utils/heartbeat"),x=require("../utils/filterInternalKeys"),k=require("./firebase");Object.defineProperty(exports,"credentialWithLink",{enumerable:!0,get:function(){return k.credentialWithLink}}),Object.defineProperty(exports,"createUser",{enumerable:!0,get:function(){return k.createUser}}),Object.defineProperty(exports,"SERVER_TIMESTAMP",{enumerable:!0,get:function(){return k.SERVER_TIMESTAMP}});var D=function(){function e(t){var r=this;c(this,e),this._selectedDevice=new p.ReplaySubject(1),this.options=t,this.subscriptionManager=new g.SubscriptionManager,this.firebaseApp=new b.FirebaseApp(t),this.firebaseUser=new b.FirebaseUser(this.firebaseApp),this._selectedDevice.next(void 0),this.status$=(0,w.heartbeatAwareStatus)(this.observeNamespace("status").pipe((0,y.share)())).pipe((0,x.filterInternalKeys)(),(0,y.shareReplay)(1)),this.osVersion$=this.observeNamespace("info/osVersion").pipe((0,y.shareReplay)(1)),this.firebaseUser.onAuthStateChanged().subscribe(function(e){r.user=e}),this.firebaseUser.onUserClaimsChange().subscribe(function(e){r.userClaims=e}),this.onDeviceChange().subscribe(function(e){r.firebaseDevice&&r.firebaseDevice.disconnect(),e&&(r.firebaseDevice=new b.FirebaseDevice({deviceId:e.deviceId,firebaseApp:r.firebaseApp,dependencies:{subscriptionManager:r.subscriptionManager}}),r.options.timesync&&(r.timesync=new m.Timesync({status$:r.status(),getTimesync:r.firebaseDevice.getTimesync.bind(r.firebaseDevice)})))})}return f(e,[{key:"onDeviceChange",value:function(){return this._selectedDevice.asObservable().pipe((0,y.filter)(function(e){return void 0!==e}))}},{key:"osVersion",value:function(){return this.osVersion$}},{key:"setAutoSelectedDevice",value:function(){return v(this,void 0,void 0,a().mark(function e(){var t=this;return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.options.deviceId){e.next=4;break}return e.next=3,this.selectDevice(function(e){return e.find(function(e){return e.deviceId===t.options.deviceId})});case 3:return e.abrupt("return",e.sent);case 4:if(this.options.deviceId||!this.options.autoSelectDevice){e.next=8;break}return e.next=7,this.selectDevice(function(e){return e[0]});case 7:return e.abrupt("return",e.sent);case 8:return e.abrupt("return",null);case 9:case"end":return e.stop()}},e,this)}))}},{key:"actions",get:function(){var e=this;return{dispatch:function(t){return e.firebaseDevice.dispatchAction(t)}}}},{key:"dispatchAction",value:function(e){return v(this,void 0,void 0,a().mark(function t(){return a().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.firebaseDevice.dispatchAction(e);case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}},t,this)}))}},{key:"disconnect",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.firebaseApp.disconnect());case 1:case"end":return e.stop()}},e,this)}))}},{key:"getInfo",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.firebaseDevice.getInfo();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e,this)}))}},{key:"login",value:function(e){return v(this,void 0,void 0,a().mark(function t(){var r,n;return a().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.user){t.next=2;break}return t.abrupt("return",Promise.reject("Already logged in."));case 2:return t.next=4,this.firebaseUser.login(e);case 4:return r=t.sent,t.next=7,this.setAutoSelectedDevice();case 7:return n=t.sent,t.abrupt("return",Object.assign(Object.assign({},r),{selectedDevice:n}));case 9:case"end":return t.stop()}},t,this)}))}},{key:"logout",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.firebaseDevice&&this.firebaseDevice.disconnect(),e.next=3,this.firebaseUser.logout();case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}},e,this)}))}},{key:"onAuthStateChanged",value:function(){var e=this;return this.firebaseUser.onAuthStateChanged().pipe((0,y.switchMap)(function(t){return v(e,void 0,void 0,a().mark(function e(){var r,n;return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}return e.abrupt("return",null);case 2:if(!this.didSelectDevice()){e.next=8;break}return e.next=5,this.getSelectedDevice();case 5:e.t0=e.sent,e.next=11;break;case 8:return e.next=10,this.setAutoSelectedDevice();case 10:e.t0=e.sent;case 11:return r=e.t0,n=Object.assign(t,{selectedDevice:r}),e.abrupt("return",n);case 14:case"end":return e.stop()}},e,this)}))}))}},{key:"getDevices",value:function(){return this.firebaseUser.getDevices()}},{key:"addDevice",value:function(e){return this.firebaseUser.addDevice(e)}},{key:"removeDevice",value:function(e){return v(this,void 0,void 0,a().mark(function r(){var n,i,o,s,c;return a().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.firebaseUser.removeDevice(e).then(function(){return[!1]}).catch(function(e){return[!0,e]});case 2:if(n=r.sent,i=t(n,2),o=i[0],s=i[1],!o){r.next=8;break}return r.abrupt("return",Promise.reject(s));case 8:return r.next=10,this.getSelectedDevice();case 10:(null==(c=r.sent)?void 0:c.deviceId)===e&&this._selectedDevice.next(null);case 12:case"end":return r.stop()}},r,this)}))}},{key:"transferDevice",value:function(e){return v(this,void 0,void 0,a().mark(function r(){var n,i,o,s,c;return a().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.firebaseUser.transferDevice(e).then(function(){return[!1]}).catch(function(e){return[!0,e]});case 2:if(n=r.sent,i=t(n,2),o=i[0],s=i[1],!o){r.next=8;break}return r.abrupt("return",Promise.reject(s));case 8:return r.next=10,this.getSelectedDevice();case 10:(null==(c=r.sent)?void 0:c.deviceId)===e.deviceId&&this._selectedDevice.next(null);case 12:case"end":return r.stop()}},r,this)}))}},{key:"onUserDevicesChange",value:function(){return this.firebaseUser.onUserDevicesChange()}},{key:"onUserClaimsChange",value:function(){return this.firebaseUser.onUserClaimsChange()}},{key:"didSelectDevice",value:function(){return v(this,void 0,void 0,a().mark(function e(){var t;return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getSelectedDevice();case 2:return t=e.sent,e.abrupt("return",!!t);case 4:case"end":return e.stop()}},e,this)}))}},{key:"selectDevice",value:function(e){return v(this,void 0,void 0,a().mark(function r(){var n,i,o;return a().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.getDevices();case 2:if(n=r.sent){r.next=5;break}return r.abrupt("return",Promise.reject("Did not find any devices for this user. Make sure your device is claimed by your Neurosity account."));case 5:if(i=function(r){return r.find(function(r){if(!Array.isArray(e))return!1;var n=t(e,2),i=n[0],o=n[1];return JSON.stringify(null==r?void 0:r[i])===JSON.stringify(o)})},o="function"==typeof e?e(n):i(n)){r.next=9;break}return r.abrupt("return",Promise.reject("A device was not provided. Try returning a device from the devicesList provided in the callback."));case 9:return r.next=11,this.firebaseUser.hasDevicePermission(o.deviceId);case 11:if(r.sent){r.next=14;break}return r.abrupt("return",Promise.reject("Rejected device access due to permissions."));case 14:return this._selectedDevice.next(o),r.abrupt("return",o);case 16:case"end":return r.stop()}},r,this)}))}},{key:"getSelectedDevice",value:function(){return v(this,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,(0,d.firstValueFrom)(this._selectedDevice);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}},e,this)}))}},{key:"status",value:function(){return this.status$}},{key:"observeNamespace",value:function(e){var t=this;return this.onDeviceChange().pipe((0,y.switchMap)(function(r){return r?(0,d.fromEventPattern)(function(r){return t.firebaseDevice.onNamespace(e,r)},function(r){return t.firebaseDevice.offNamespace(e,r)}):p.EMPTY}))}},{key:"onceNamespace",value:function(e){return v(this,void 0,void 0,a().mark(function t(){return a().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.firebaseDevice.onceNamespace(e);case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}},t,this)}))}},{key:"metrics",get:function(){var e=this;return{next:function(t,r){e.firebaseDevice.nextMetric(t,r)},on:function(t,r){return e.firebaseDevice.onMetric(t,r)},subscribe:function(t){var r=e.firebaseDevice.subscribeToMetric(t);return e.subscriptionManager.add(r),r},unsubscribe:function(t,r){e.subscriptionManager.remove(t),e.firebaseDevice.unsubscribeFromMetric(t),e.firebaseDevice.removeMetricListener(t,r)}}}},{key:"createAccount",value:function(e){return this.firebaseUser.createAccount(e)}},{key:"deleteAccount",value:function(){return this.firebaseUser.deleteAccount()}},{key:"createBluetoothToken",value:function(){return this.firebaseDevice.createBluetoothToken()}},{key:"createCustomToken",value:function(){return this.firebaseUser.createCustomToken()}},{key:"removeOAuthAccess",value:function(){return this.firebaseUser.removeOAuthAccess()}},{key:"onUserExperiments",value:function(){return this.firebaseUser.onUserExperiments()}},{key:"deleteUserExperiment",value:function(e){return this.firebaseUser.deleteUserExperiment(e)}},{key:"skills",get:function(){var e=this;return{get:function(t){return v(e,void 0,void 0,a().mark(function e(){return a().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.firebaseDevice.getSkill(t));case 1:case"end":return e.stop()}},e,this)}))}}}},{key:"timestamp",get:function(){return this.options.timesync?this.timesync.timestamp:Date.now()}},{key:"getTimesyncOffset",value:function(){return this.timesync.offset}},{key:"changeSettings",value:function(e){return this.firebaseDevice.changeSettings(e)}},{key:"goOffline",value:function(){this.firebaseApp.goOffline()}},{key:"goOnline",value:function(){this.firebaseApp.goOnline()}},{key:"__getApp",value:function(){return this.firebaseApp.app}}]),e}();exports.CloudClient=D;
|
|
542
542
|
},{"rxjs":"Zr8e","rxjs/operators":"v3iE","./firebase":"kM30","../timesync":"CXqr","../subscriptions/SubscriptionManager":"BX8M","../utils/heartbeat":"ImaE","../utils/filterInternalKeys":"qny3"}],"rekm":[function(require,module,exports) {
|
|
543
543
|
"use strict";var t,o;Object.defineProperty(exports,"__esModule",{value:!0}),exports.STREAMING_MODE=exports.STREAMING_TYPE=void 0,function(t){t.WIFI="wifi",t.BLUETOOTH="bluetooth"}(t=exports.STREAMING_TYPE||(exports.STREAMING_TYPE={})),function(t){t.WIFI_ONLY="wifi-only",t.WIFI_WITH_BLUETOOTH_FALLBACK="wifi-with-bluetooth-fallback",t.BLUETOOTH_WITH_WIFI_FALLBACK="bluetooth-with-wifi-fallback"}(o=exports.STREAMING_MODE||(exports.STREAMING_MODE={}));
|
|
544
544
|
},{}],"A5u5":[function(require,module,exports) {
|