firebase 10.11.1-dataconnect-preview.f2ddc3d7b → 10.11.1-dataconnect-preview.42eb5e521
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/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-analytics-compat.js +1 -1
- package/firebase-analytics.js +1 -1
- package/firebase-app-check-compat.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +5 -5
- package/firebase-auth-compat.js +1 -1
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-web-extension.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +3 -3
- package/firebase-data-connect.js +1 -1
- package/firebase-database-compat.js +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-functions-compat.js +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations-compat.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-compat.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-compat.js +1 -1
- package/firebase-performance-standalone-compat.es2017.js +21 -21
- package/firebase-performance-standalone-compat.js +1 -1
- package/firebase-performance.js +1 -1
- package/firebase-remote-config-compat.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage-compat.js +1 -1
- package/firebase-storage.js +1 -1
- package/package.json +28 -28
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(ol,ul){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(ol);function n(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let h=0;h<n.length;h+=3){var s=n[h],a=h+1<n.length,o=a?n[h+1]:0,u=h+2<n.length,c=u?n[h+2]:0;let e=(15&o)<<2|c>>6,t=63&c;u||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u<e.length;){var i=n[e.charAt(u++)],s=u<e.length?n[e.charAt(u)]:0;++u;var a=u<e.length?n[e.charAt(u)]:64;++u;var o=u<e.length?n[e.charAt(u)]:64;if(++u,null==i||null==s||null==a||null==o)throw new c;r.push(i<<2|s>>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const i=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,s=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},a=()=>{try{return i()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||s()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function h(){return!function(){var e=null===(e=a())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class d extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,f.prototype.create)}}class f{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(g,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new d(i,s,n)}}const g=/\{\$([^}]+)}/g;function m(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;var i=e[a],s=t[a];if(p(i)&&p(s)){if(!m(i,s))return!1}else if(i!==s)return!1}for(const o of r)if(!n.includes(o))return!1;return!0}function p(e){return null!==e&&"object"==typeof e}function y(e){return e&&e._delegate?e._delegate:e}class v{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}(cc=l=l||{})[cc.DEBUG=0]="DEBUG",cc[cc.VERBOSE=1]="VERBOSE",cc[cc.INFO=2]="INFO",cc[cc.WARN=3]="WARN",cc[cc.ERROR=4]="ERROR",cc[cc.SILENT=5]="SILENT";const w={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},_=l.INFO,b={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},I=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=b[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};var E,T,S="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!(function(){var e,t,s;function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function r(){}function a(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((a=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function c(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}t=n,r.prototype=(s=function(){this.blockSize=-1}).prototype,t.D=s.prototype,t.prototype=new r,(t.prototype.constructor=t).C=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)},n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},n.prototype.u=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.B,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)a(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){a(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){a(this,r),i=0;break}}this.h=i,this.o+=t},n.prototype.v=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.o,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.u(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var i={};function o(e){return-128<=e&&e<128?(t=e,n=function(e){return new c([0|e],e<0?-1:0)},r=i,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new c([0|e],e<0?-1:0);var t,n,r}function h(e){if(isNaN(e)||!isFinite(e))return l;if(e<0)return m(h(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=4294967296;return new c(t,0)}var l=o(0),u=o(1),d=o(16777216);function f(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function g(e){return-1==e.h}function m(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new c(n,~e.h).add(u)}function p(e,t){return e.add(m(t))}function y(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function v(e,t){this.g=e,this.h=t}function w(e,t){if(f(t))throw Error("division by zero");if(f(e))return new v(l,l);if(g(e))return t=w(m(e),t),new v(m(t.g),m(t.h));if(g(t))return t=w(e,m(t)),new v(m(t.g),t.h);if(30<e.g.length){if(g(e)||g(t))throw Error("slowDivide_ only works with positive integers.");for(var n=u,r=t;r.l(e)<=0;)n=_(n),r=_(r);for(var i=b(n,1),s=b(r,1),r=b(r,2),n=b(n,2);!f(r);){var a=s.add(r);a.l(e)<=0&&(i=i.add(n),s=a),r=b(r,1),n=b(n,1)}return t=p(e,i.j(t)),new v(i,t)}for(i=l;0<=e.l(t);){for(n=Math.max(1,Math.floor(e.m()/t.m())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=h(n)).j(t);g(a)||0<a.l(e);)a=(s=h(n-=r)).j(t);f(s)&&(s=u),i=i.add(s),e=p(e,a)}return new v(i,e)}function _(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.i(r)<<1|e.i(r-1)>>>31;return new c(n,e.h)}function b(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.i(s+n)>>>t|e.i(s+n+1)<<32-t:e.i(s+n);return new c(i,e.h)}(e=c.prototype).m=function(){if(g(this))return-m(this).m();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(f(this))return"0";if(g(this))return"-"+m(this).toString(e);for(var t=h(Math.pow(e,6)),n=this,r="";;){var i=w(n,t).g,s=((0<(n=p(n,i.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(f(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return g(e=p(this,e))?-1:f(e)?0:1},e.abs=function(){return g(this)?m(this):this},e.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.i(i))+(65535&e.i(i)),a=(s>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new c(n,-2147483648&n[n.length-1]?-1:0)},e.j=function(e){if(f(this)||f(e))return l;if(g(this))return g(e)?m(this).j(m(e)):m(m(this).j(e));if(g(e))return m(this.j(m(e)));if(this.l(d)<0&&e.l(d)<0)return h(this.m()*e.m());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.i(r)>>>16,a=65535&this.i(r),o=e.i(i)>>>16,u=65535&e.i(i);n[2*r+2*i]+=a*u,y(n,2*r+2*i),n[2*r+2*i+1]+=s*u,y(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,y(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,y(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new c(n,0)},e.A=function(e){return w(this,e).h},e.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)&e.i(r);return new c(n,this.h&e.h)},e.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)|e.i(r);return new c(n,this.h|e.h)},e.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)^e.i(r);return new c(n,this.h^e.h)},n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,T=n,c.prototype.multiply=c.prototype.j,c.prototype.modulo=c.prototype.A,c.prototype.compare=c.prototype.l,c.prototype.toNumber=c.prototype.m,c.prototype.getBits=c.prototype.i,c.fromNumber=h,c.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return m(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=h(Math.pow(n,8)),i=l,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n),i=a<8?(a=h(Math.pow(n,a)),i.j(a).add(h(o))):(i=i.j(r)).add(h(o));return i},E=c}).apply(void 0!==S?S:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var dn,fn,gn,mn,pn,yn,vn,wn,_n,x,D,C,bn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!(function(){var e,s="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};var a=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof bn&&bn];for(var t=0;t<e.length;++t){var n=e[t];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);!function(e,t){if(t)e:{var n=a;e=e.split(".");for(var r=0;r<e.length-1;r++){var i=e[r];if(!(i in n))break e;n=n[i]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&s(n,e,{configurable:!0,writable:!0,value:t})}}("Array.prototype.values",function(e){return e||function(){return function(t,n){t instanceof String&&(t+="");var r=0,i=!1,e={next:function(){if(!i&&r<t.length){var e=r++;return{value:n(e,t[e]),done:!1}}return{done:i=!0,value:void 0}}};return e[Symbol.iterator]=function(){return e},e}(this,function(e,t){return t})}});var o=o||{},T=this||self;function u(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function c(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function r(e,t,n){return e.call.apply(e.bind,arguments)}function i(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function p(e,t,n){return(p=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?r:i).apply(null,arguments)}function h(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function t(e,s){function t(){}t.prototype=s.prototype,e.aa=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Qb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function l(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function n(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(u(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function S(e){return/^[\s\xa0]*$/.test(e)}function d(){var e=T.navigator;return(e=e&&e.userAgent)?e:""}function f(e){return f[" "](e),e}f[" "]=function(){};var g=!(-1==d().indexOf("Gecko")||-1!=d().toLowerCase().indexOf("webkit")&&-1==d().indexOf("Edge")||-1!=d().indexOf("Trident")||-1!=d().indexOf("MSIE")||-1!=d().indexOf("Edge"));function m(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function y(e){const t={};for(const n in e)t[n]=e[n];return t}const v="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function w(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<v.length;e++)n=v[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}var _=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new b,e=>e.reset());class b{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let I,E=!1,x=new class{constructor(){this.h=this.g=null}add(e,t){const n=_.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},D=()=>{const e=T.Promise.resolve(void 0);I=()=>{e.then(C)}};var C=()=>{for(var e;e=function(){var e=x;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){T.setTimeout(()=>{throw e},0)}(e)}var t=_;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}E=!1};function A(){this.s=this.s,this.C=this.C}function N(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}A.prototype.s=!1,A.prototype.ma=function(){this.s||(this.s=!0,this.N())},A.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},N.prototype.h=function(){this.defaultPrevented=!0};var k=function(){if(!T.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var n=()=>{};T.addEventListener("test",n,t),T.removeEventListener("test",n,t)}catch(e){}return e}();function R(e,t){if(N.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(g){e:{try{f(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:M[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&R.aa.h.call(this)}}t(R,N);var M={2:"touch",3:"pen",4:"mouse"};R.prototype.h=function(){R.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var L="closure_listenable_"+(1e6*Math.random()|0),O=0;function F(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++O,this.da=this.fa=!1}function P(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function V(e){this.src=e,this.g={},this.h=0}function U(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Array.prototype.indexOf.call(n,t,void 0)))&&Array.prototype.splice.call(n,r,1),i&&(P(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function B(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}V.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=B(e,t,r,i);return-1<a?(t=e[a],n||(t.fa=!1)):((t=new F(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var q="closure_lm_"+(1e6*Math.random()|0),j={};function G(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Y(r);return t&&t[L]?t.L(n,r,c(i)?!!i.capture:!!i,s):z(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)G(e,t[s],n,r,i);return null}return n=Y(n),e&&e[L]?e.K(t,n,c(r)?!!r.capture:!!r,i):z(e,t,n,!1,r,i)}function z(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=c(i)?!!i.capture:!!i,o=H(e);if(o||(e[q]=o=new V(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=Q;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!k?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent($(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function K(e){var t,n,r;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[L]?U(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent($(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=H(t))?(U(n,e),0==n.h&&(n.src=null,t[q]=null)):P(e)))}function $(e){return e in j?j[e]:j[e]="on"+e}function Q(e,t){var n,r;return e=!!e.da||(t=new R(t,this),n=e.listener,r=e.ha||e.src,e.fa&&K(e),n.call(r,t))}function H(e){return(e=e[q])instanceof V?e:null}var W="__closure_events_fn_"+(1e9*Math.random()>>>0);function Y(t){return"function"==typeof t?t:(t[W]||(t[W]=function(e){return t.handleEvent(e)}),t[W])}function J(){A.call(this),this.i=new V(this),(this.M=this).F=null}function X(e,t){var n,r=e.F;if(r)for(n=[];r;r=r.F)n.push(r);if(e=e.M,r=t.type||t,"string"==typeof t?t=new N(t,e):t instanceof N?t.target=t.target||e:(a=t,w(t=new N(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Z(s,r,!0,t)&&a;if(a=Z(s=t.g=e,r,!0,t)&&a,a=Z(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Z(s=t.g=n[i],r,!1,t)&&a}function Z(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,u=t[s];u&&!u.da&&u.capture==n&&(a=u.listener,o=u.ha||u.src,u.fa&&U(e.i,u),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}function ee(e,t,n){if("function"==typeof e)n&&(e=p(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=p(e.handleEvent,e)}return 2147483647<Number(t)?-1:T.setTimeout(e,t||0)}t(J,A),J.prototype[L]=!0,J.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=c(i)?!!i.capture:!!i,r=Y(r),t&&t[L]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=B(a=t.g[n],r,i,s))&&(P(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&H(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?B(n,r,i,s):t)?n[t]:null)&&K(r))}(this,e,t,n,r)},J.prototype.N=function(){if(J.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)P(n[r]);delete t.g[e],t.h--}}this.F=null},J.prototype.K=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},J.prototype.L=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};class te extends A{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=ee(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.l);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}N(){super.N(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ne(e){A.call(this),this.h=e,this.g={}}t(ne,A);var re=[];function ie(e){m(e.g,function(e,t){this.g.hasOwnProperty(t)&&K(e)},e),e.g={}}ne.prototype.N=function(){ne.aa.N.call(this),ie(this)},ne.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var se=T.JSON.stringify,ae=T.JSON.parse,oe=class{stringify(e){return T.JSON.stringify(e,void 0)}parse(e){return T.JSON.parse(e,void 0)}};function ue(){}function ce(e){return e.h||(e.h=e.i())}function he(){}ue.prototype.h=null;var le={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function de(){N.call(this,"d")}function fe(){N.call(this,"c")}t(de,N),t(fe,N);var ge={},me=null;function pe(){return me=me||new J}function ye(e){N.call(this,ge.La,e)}function ve(){var e=pe();X(e,new ye(e))}function we(e,t){N.call(this,ge.STAT_EVENT,e),this.stat=t}function _e(e){var t=pe();X(t,new we(t,e))}function be(e,t){N.call(this,ge.Ma,e),this.size=t}function Ie(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return T.setTimeout(function(){e()},t)}function Ee(){this.g=!0}function Te(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return se(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}ge.La="serverreachability",t(ye,N),ge.STAT_EVENT="statevent",t(we,N),ge.Ma="timingevent",t(be,N),Ee.prototype.xa=function(){this.g=!1},Ee.prototype.info=function(){};var Se={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},xe={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function De(){}function Ce(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new ne(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Ae}function Ae(){this.i=null,this.g="",this.h=!1}t(De,ue),De.prototype.g=function(){return new XMLHttpRequest},De.prototype.i=function(){return{}};var Ne=new De,ke={},Re={};function Me(e,t,n){e.L=1,e.v=it(Ze(t)),e.m=n,e.P=!0,Le(e,null)}function Le(e,t){e.F=Date.now(),Fe(e),e.A=Ze(e.v);var n=e.A,r=e.R;Array.isArray(r)||(r=[String(r)]),vt(n.i,"t",r),e.C=0,n=e.j.J,e.h=new Ae,e.g=sn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new te(p(e.Y,e,e.g),e.O)),t=e.U;var n=e.g,r=e.ca,i="readystatechange";Array.isArray(i)||(i&&(re[0]=i.toString()),i=re);for(var a,o,u,c,h,l,s=0;s<i.length;s++){var d=G(n,i[s],r||t.handleEvent,!1,t.h||t);if(!d)break;t.g[d.key]=d}t=e.H?y(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),ve(),a=e.i,o=e.u,u=e.A,c=e.l,h=e.R,l=e.m,a.info(function(){if(a.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+h+"]: "+o+"\n"+u+"\n"+e})}function Oe(e){return e.g&&("GET"==e.u&&2!=e.L&&e.j.Ca)}function Fe(e){e.S=Date.now()+e.I,Pe(e,e.I)}function Pe(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Ie(p(e.ba,e),t)}function Ve(e){e.B&&(T.clearTimeout(e.B),e.B=null)}function Ue(e){0==e.j.G||e.J||Zt(e.j,e)}function Be(e){Ve(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,ie(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function qe(e,t){try{var n=e.j;if(0!=n.G&&(n.g==e||$e(n.h,e)))if(!e.K&&$e(n.h,e)&&3==n.G){try{var r=n.Da.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Xt(n),jt(n)}Wt(n),_e(18)}}else n.za=i[1],0<n.za-n.T&&i[2]<37500&&n.F&&0==n.v&&!n.C&&(n.C=Ie(p(n.Za,n),6e3));if(Ke(n.h)<=1&&n.ca){try{n.ca()}catch(e){}n.ca=void 0}}else tn(n,11)}else if(!e.K&&n.g!=e||Xt(n),!S(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.T=s[0],s=s[1],2==n.G)if("c"==s[0]){n.K=s[1],n.ia=s[2];var a=s[3];null!=a&&(n.la=a,n.j.info("VER="+n.la));var o=s[4];null!=o&&(n.Aa=o,n.j.info("SVER="+n.Aa));var u,c,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.L=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;if(g){const m=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null;m&&((u=r.h).g||-1==m.indexOf("spdy")&&-1==m.indexOf("quic")&&-1==m.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(Qe(u,u.h),u.h=null))),!r.D||(c=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.ya=c,rt(r.I,r.D,c))}n.G=3,n.l&&n.l.ua(),n.ba&&(n.R=Date.now()-e.F,n.j.info("Handshake RTT: "+n.R+"ms"));var l,d,f=e;(r=n).qa=rn(r,r.J?r.ia:null,r.W),f.K?(He(r.h,f),l=f,(d=r.L)&&(l.I=d),l.B&&(Ve(l),Fe(l)),r.g=f):Ht(r),0<n.i.length&&zt(n)}else"stop"!=s[0]&&"close"!=s[0]||tn(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?tn(n,7):qt(n):"noop"!=s[0]&&n.l&&n.l.ta(s),n.v=0)}ve()}catch(e){}}Ce.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Pt(e)?t.j():this.Y(e)},Ce.prototype.Y=function(e){try{if(e==this.g)e:{var t=Pt(this.g),n=this.g.Ba();this.g.Z();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.oa()||Vt(this.g)))){this.J||4!=t||7==n||ve(),Ve(this);var r=this.g.Z();this.X=r;t:if(Oe(this)){var i=Vt(this.g);e="";var s=i.length,a=4==Pt(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Be(this),Ue(this);var o="";break t}this.h.i=new T.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:!(a&&n==s-1)});i.length=0,this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.oa();if(this.o=200==r,y=this.i,v=this.u,w=this.A,_=this.l,b=this.R,I=t,E=r,y.info(function(){return"XMLHTTP RESP ("+_+") [ attempt "+b+"]: "+v+"\n"+w+"\n"+I+" "+E}),this.o){if(this.T&&!this.K){t:{if(this.g){var u,c=this.g;if((u=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!S(u)){var h=u;break t}}h=null}if(!(r=h)){this.o=!1,this.s=3,_e(12),Be(this),Ue(this);break e}Te(this.i,this.l,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,qe(this,r)}if(this.P){for(var l,d,r=!0;!this.J&&this.C<o.length;){if(g=o,p=m=void 0,m=(f=this).C,(l=-1==(p=g.indexOf("\n",m))?Re:(m=Number(g.substring(m,p)),isNaN(m)?ke:(p+=1)+m>g.length?Re:(g=g.slice(p,p+m),f.C=p+m,g)))==Re){4==t&&(this.s=4,_e(14),r=!1),Te(this.i,this.l,null,"[Incomplete Response]");break}if(l==ke){this.s=4,_e(15),Te(this.i,this.l,o,"[Invalid Chunk]"),r=!1;break}Te(this.i,this.l,l,null),qe(this,l)}Oe(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=o.length||this.h.h||(this.s=1,_e(16),r=!1),this.o=this.o&&r,r?0<o.length&&!this.W&&(this.W=!0,(d=this.j).g==this&&d.ba&&!d.M&&(d.j.info("Great, no buffering proxy detected. Bytes received: "+o.length),Yt(d),d.M=!0,_e(11))):(Te(this.i,this.l,o,"[Invalid Chunked Response]"),Be(this),Ue(this))}else Te(this.i,this.l,o,null),qe(this,o);4==t&&Be(this),this.o&&!this.J&&(4==t?Zt(this.j,this):(this.o=!1,Fe(this)))}else(function(e){const t={};e=(e.g&&2<=Pt(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!S(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<o.indexOf("Unknown SID")?(this.s=3,_e(12)):(this.s=0,_e(13)),Be(this),Ue(this)}}}catch(e){}var f,g,m,p,y,v,w,_,b,I,E},Ce.prototype.cancel=function(){this.J=!0,Be(this)},Ce.prototype.ba=function(){this.B=null;var e,t,n=Date.now();0<=n-this.S?(e=this.i,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(ve(),_e(17)),Be(this),this.s=2,Ue(this)):Pe(this,this.S-n)};var je=class{constructor(e,t){this.g=e,this.map=t}};function Ge(e){this.l=e||10,e=T.PerformanceNavigationTiming?0<(e=T.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(T.chrome&&T.chrome.loadTimes&&T.chrome.loadTimes()&&T.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function ze(e){return e.h||e.g&&e.g.size>=e.j}function Ke(e){return e.h?1:e.g?e.g.size:0}function $e(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Qe(e,t){e.g?e.g.add(t):e.h=t}function He(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function We(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return l(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function Ye(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(u(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(u(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(u(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}Ge.prototype.cancel=function(){if(this.i=We(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var Je=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Xe(e){var t,n;this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof Xe?(this.h=e.h,et(this,e.j),this.o=e.o,this.g=e.g,tt(this,e.s),this.l=e.l,t=e.i,(n=new gt).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),nt(this,n),this.m=e.m):e&&(t=String(e).match(Je))?(this.h=!1,et(this,t[1]||"",!0),this.o=st(t[2]||""),this.g=st(t[3]||"",!0),tt(this,t[4]),this.l=st(t[5]||"",!0),nt(this,t[6]||"",!0),this.m=st(t[7]||"")):(this.h=!1,this.i=new gt(null,this.h))}function Ze(e){return new Xe(e)}function et(e,t,n){e.j=n?st(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function tt(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.s=t}else e.s=null}function nt(e,t,n){var r,i;t instanceof gt?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(mt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(pt(this,t),vt(this,n,e))},r)),r.j=i):(n||(t=at(t,dt)),e.i=new gt(t,e.h))}function rt(e,t,n){e.i.set(t,n)}function it(e){return rt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function st(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function at(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,ot),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function ot(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Xe.prototype.toString=function(){var e=[],t=this.j;t&&e.push(at(t,ct,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(at(t,ct,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.s)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(at(n,"/"==n.charAt(0)?lt:ht,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",at(n,ft)),e.join("")};var ut,ct=/[#\/\?@]/g,ht=/[#\?:]/g,lt=/[#\?]/g,dt=/[#\?@]/g,ft=/#/g;function gt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function mt(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function pt(e,t){mt(e),t=wt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function yt(e,t){return mt(e),t=wt(e,t),e.g.has(t)}function vt(e,t,n){pt(e,t),0<n.length&&(e.i=null,e.g.set(wt(e,t),l(n)),e.h+=n.length)}function wt(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function _t(e,t,n,r,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),r(n)}catch(e){}}function bt(){this.g=new oe}function It(e){this.l=e.Ub||null,this.j=e.eb||!1}function Et(e,t){J.call(this),this.D=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Tt(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function St(e){e.readyState=4,e.l=null,e.j=null,e.v=null,xt(e)}function xt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Dt(e){let n="";return m(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Ct(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Dt(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):rt(e,t,n))}function At(e){J.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(e=gt.prototype).add=function(e,t){mt(this),this.i=null,e=wt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},e.forEach=function(n,r){mt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},e.na=function(){mt(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},e.V=function(t){mt(this);let n=[];if("string"==typeof t)yt(this,t)&&(n=n.concat(this.g.get(wt(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},e.set=function(e,t){return mt(this),this.i=null,yt(this,e=wt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},e.get=function(e,t){return e&&0<(e=this.V(e)).length?String(e[0]):t},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.V(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")},t(It,ue),It.prototype.g=function(){return new Et(this.l,this.j)},It.prototype.i=(ut={},function(){return ut}),t(Et,J),(e=Et.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,xt(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||T).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,St(this)),this.readyState=0},e.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,xt(this)),this.g&&(this.readyState=3,xt(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==T.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Tt(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=function(e){var t;this.g&&(this.o&&e.value?this.response.push(e.value):this.o||(t=e.value||new Uint8Array(0),(t=this.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?St:xt)(this),3==this.readyState&&Tt(this))},e.Ra=function(e){this.g&&(this.response=this.responseText=e,St(this))},e.Qa=function(e){this.g&&(this.response=e,St(this))},e.ga=function(){this.g&&St(this)},e.setRequestHeader=function(e,t){this.u.append(e,t)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Et.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),t(At,J);var Nt=/^https?$/i,kt=["POST","PUT"];function Rt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,Mt(e),Ot(e)}function Mt(e){e.A||(e.A=!0,X(e,"complete"),X(e,"error"))}function Lt(e){if(e.h&&void 0!==o&&(!e.v[1]||4!=Pt(e)||2!=e.Z()))if(e.u&&4==Pt(e))ee(e.Ea,0,e);else if(X(e,"readystatechange"),4==Pt(e)){e.h=!1;try{var t,n,r,i=e.Z();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.D).match(Je)[1]||null)&&T.self&&T.self.location&&(r=T.self.location.protocol.slice(0,-1)),n=!Nt.test(r?r.toLowerCase():"")),t=n),t)X(e,"complete"),X(e,"success");else{e.m=6;try{var a=2<Pt(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",Mt(e)}}finally{Ot(e)}}}function Ot(e,t){if(e.g){Ft(e);const n=e.g,r=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||X(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Ft(e){e.I&&(T.clearTimeout(e.I),e.I=null)}function Pt(e){return e.g?e.g.readyState:0}function Vt(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.H){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Ut(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Bt(e){this.Aa=0,this.i=[],this.j=new Ee,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Ut("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Ut("baseRetryDelayMs",5e3,e),this.cb=Ut("retryDelaySeedMs",1e4,e),this.Wa=Ut("forwardChannelMaxRetries",2,e),this.wa=Ut("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new Ge(e&&e.concurrentRequestLimit),this.Da=new bt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function qt(e){if(Gt(e),3==e.G){var t=e.U++,n=Ze(e.I);if(rt(n,"SID",e.K),rt(n,"RID",t),rt(n,"TYPE","terminate"),$t(e,n),(t=new Ce(e,e.j,t)).L=2,t.v=it(Ze(n)),n=!1,T.navigator&&T.navigator.sendBeacon)try{n=T.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&T.Image&&((new Image).src=t.v,n=!0),n||(t.g=sn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Fe(t)}nn(e)}function jt(e){e.g&&(Yt(e),e.g.cancel(),e.g=null)}function Gt(e){jt(e),e.u&&(T.clearTimeout(e.u),e.u=null),Xt(e),e.h.cancel(),e.s&&("number"==typeof e.s&&T.clearTimeout(e.s),e.s=null)}function zt(e){var t;ze(e.h)||e.s||(e.s=!0,t=e.Ga,I||D(),E||(I(),E=!0),x.add(t,e),e.B=0)}function Kt(e,t){var n=t?t.l:e.U++,r=Ze(e.I);rt(r,"SID",e.K),rt(r,"RID",n),rt(r,"AID",e.T),$t(e,r),e.m&&e.o&&Ct(r,e.m,e.o),n=new Ce(e,e.j,n,e.B+1),null===e.m&&(n.H=e.o),t&&(e.i=t.D.concat(e.i)),t=Qt(e,n,1e3),n.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),Qe(e.h,n),Me(n,r,t)}function $t(e,n){e.H&&m(e.H,function(e,t){rt(n,t,e)}),e.l&&Ye({},function(e,t){rt(n,t,e)})}function Qt(e,t,r){r=Math.min(e.i.length,r);var i=e.l?p(e.l.Na,e.l,e):null;e:{var s=e.i;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=s[0].g,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].g,o=s[t].map;if((a-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Ye(e,function(e,t){let n=e;c(e)&&(n=se(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=u.join("&");break e}}}return e=e.i.splice(0,r),t.D=e,i}function Ht(e){var t;e.g||e.u||(e.Y=1,t=e.Fa,I||D(),E||(I(),E=!0),x.add(t,e),e.v=0)}function Wt(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=Ie(p(e.Fa,e),en(e,e.v)),e.v++,1)}function Yt(e){null!=e.A&&(T.clearTimeout(e.A),e.A=null)}function Jt(e){e.g=new Ce(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=Ze(e.qa);rt(t,"RID","rpc"),rt(t,"SID",e.K),rt(t,"AID",e.T),rt(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&rt(t,"TO",e.ja),rt(t,"TYPE","xmlhttp"),$t(e,t),e.m&&e.o&&Ct(t,e.m,e.o),e.L&&(e.g.I=e.L);var n=e.g;e=e.ia,n.L=1,n.v=it(Ze(t)),n.m=null,n.P=!0,Le(n,e)}function Xt(e){null!=e.C&&(T.clearTimeout(e.C),e.C=null)}function Zt(e,t){var n,r,i,s=null;if(e.g==t){Xt(e),Yt(e),e.g=null;var a=2}else{if(!$e(e.h,t))return;s=t.D,He(e.h,t),a=1}if(0!=e.G)if(t.o)1==a?(s=t.m?t.m.length:0,t=Date.now()-t.F,n=e.B,X(a=pe(),new be(a,s)),zt(e)):Ht(e);else if(3==(n=t.s)||0==n&&0<t.X||(1!=a||(i=t,Ke((r=e).h)>=r.h.j-(r.s?1:0)||(r.s?(r.i=i.D.concat(r.i),0):1==r.G||2==r.G||r.B>=(r.Va?0:r.Wa)||(r.s=Ie(p(r.Ga,r,i),en(r,r.B)),r.B++,0))))&&(2!=a||!Wt(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),n){case 1:tn(e,5);break;case 4:tn(e,10);break;case 3:tn(e,6);break;default:tn(e,2)}}function en(e,t){let n=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(n*=2),n*t}function tn(e,t){var n,r,i;e.j.info("Error code "+t),2==t?(n=p(e.fb,e),r=!(i=e.Xa),i=new Xe(i||"//www.google.com/images/cleardot.gif"),T.location&&"http"==T.location.protocol||et(i,"https"),it(i),(r?function(e,t){var n=new Ee;if(T.Image){const r=new Image;r.onload=h(_t,n,"TestLoadImage: loaded",!0,t,r),r.onerror=h(_t,n,"TestLoadImage: error",!1,t,r),r.onabort=h(_t,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=h(_t,n,"TestLoadImage: timeout",!1,t,r),T.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}:function(e,t){const n=new Ee,r=new AbortController,i=setTimeout(()=>{r.abort(),_t(n,0,!1,t)},1e4);fetch(e,{signal:r.signal}).then(e=>{clearTimeout(i),e.ok?_t(n,0,!0,t):_t(n,0,!1,t)}).catch(()=>{clearTimeout(i),_t(n,0,!1,t)})})(i.toString(),n)):_e(2),e.G=0,e.l&&e.l.sa(t),nn(e),Gt(e)}function nn(e){var t;e.G=0,e.ka=[],e.l&&(0==(t=We(e.h)).length&&0==e.i.length||(n(e.ka,t),n(e.ka,e.i),e.h.i.length=0,l(e.i),e.i.length=0),e.l.ra())}function rn(e,t,n){var r,i,s=n instanceof Xe?Ze(n):new Xe(n);return""!=s.g?(t&&(s.g=t+"."+s.g),tt(s,s.s)):(s=(r=T.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new Xe(null),s&&et(i,s),t&&(i.g=t),r&&tt(i,r),n&&(i.l=n),s=i),n=e.D,t=e.ya,n&&t&&rt(s,n,t),rt(s,"VER",e.la),$t(e,s),s}function sn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new At(new It({eb:n})):new At(e.pa)).Ha(e.J),t}function an(){}function on(){}function un(e,t){J.call(this),this.g=new Bt(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!S(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!S(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new ln(this)}function cn(e){de.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function hn(){fe.call(this),this.status=1}function ln(e){this.g=e}(e=At.prototype).Ha=function(e){this.J=e},e.ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=(this.o||Ne).g(),this.v=this.o?ce(this.o):ce(Ne),this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void Rt(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const o of r.keys())n.set(o,r.get(o))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=T.FormData&&e instanceof T.FormData,0<=Array.prototype.indexOf.call(kt,t,void 0)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Ft(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){Rt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,X(this,"complete"),X(this,"abort"),Ot(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Ot(this,!0)),At.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?Lt(this):this.bb())},e.bb=function(){Lt(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2<Pt(this)?this.g.status:-1}catch(e){return-1}},e.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.Oa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),ae(t)}},e.Ba=function(){return this.m},e.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=Bt.prototype).la=8,e.G=1,e.connect=function(e,t,n,r){_e(0),this.W=e,this.H=t||{},n&&void 0!==r&&(this.H.OSID=n,this.H.OAID=r),this.F=this.X,this.I=rn(this,null,this.W),zt(this)},e.Ga=function(t){if(this.s)if(this.s=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;const s=new Ce(this,this.j,t);let e=this.o;if(this.S&&(e?(e=y(e),w(e,this.S)):e=this.S),null!==this.m||this.O||(s.H=e,e=null),this.P)e:{for(var n=0,r=0;r<this.i.length;r++){var i=this.i[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.i.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Qt(this,s,n),rt(r=Ze(this.I),"RID",t),rt(r,"CVER",22),this.D&&rt(r,"X-HTTP-Session-Id",this.D),$t(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(Dt(e)))+"&"+n:this.m&&Ct(r,this.m,e)),Qe(this.h,s),this.Ua&&rt(r,"TYPE","init"),this.P?(rt(r,"$req",n),rt(r,"SID","null"),s.T=!0,Me(s,r,null)):Me(s,r,n),this.G=2}}else 3==this.G&&(t?Kt(this,t):0==this.i.length||ze(this.h)||Kt(this))},e.Fa=function(){var e;this.u=null,Jt(this),this.ba&&!(this.M||null==this.g||this.R<=0)&&(e=2*this.R,this.j.info("BP detection timer enabled: "+e),this.A=Ie(p(this.ab,this),e))},e.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,_e(10),jt(this),Jt(this))},e.Za=function(){null!=this.C&&(this.C=null,jt(this),Wt(this),_e(19))},e.fb=function(e){e?(this.j.info("Successfully pinged google.com"),_e(2)):(this.j.info("Failed to ping google.com"),_e(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=an.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},on.prototype.g=function(e,t){return new un(e,t)},t(un,J),un.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},un.prototype.close=function(){qt(this.g)},un.prototype.o=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.u&&((t={}).__data__=se(e),e=t),n.i.push(new je(n.Ya++,e)),3==n.G&&zt(n)},un.prototype.N=function(){this.g.l=null,delete this.j,qt(this.g),delete this.g,un.aa.N.call(this)},t(cn,de),t(hn,fe),t(ln,an),ln.prototype.ua=function(){X(this.g,"a")},ln.prototype.ta=function(e){X(this.g,new cn(e))},ln.prototype.sa=function(e){X(this.g,new hn)},ln.prototype.ra=function(){X(this.g,"b")},on.prototype.createWebChannel=on.prototype.g,un.prototype.send=un.prototype.o,un.prototype.open=un.prototype.m,_n=function(){return new on},wn=pe,vn=ge,yn={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Se.NO_ERROR=0,Se.TIMEOUT=8,Se.HTTP_ERROR=6,pn=Se,xe.COMPLETE="complete",mn=xe,(he.EventType=le).OPEN="a",le.CLOSE="b",le.ERROR="c",le.MESSAGE="d",J.prototype.listen=J.prototype.K,gn=he,fn=It,At.prototype.listenOnce=At.prototype.L,At.prototype.getLastError=At.prototype.Ka,At.prototype.getLastErrorCode=At.prototype.Ba,At.prototype.getStatus=At.prototype.Z,At.prototype.getResponseJson=At.prototype.Oa,At.prototype.getResponseText=At.prototype.oa,At.prototype.send=At.prototype.ea,At.prototype.setWithCredentials=At.prototype.Ha,dn=At}).apply(void 0!==bn?bn:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});const A="@firebase/firestore",N="4.6.1-dataconnect-preview.f2ddc3d7b";class k{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}k.UNAUTHENTICATED=new k(null),k.GOOGLE_CREDENTIALS=new k("google-credentials-uid"),k.FIRST_PARTY=new k("first-party-uid"),k.MOCK_USER=new k("mock-user");let R="10.11.1-dataconnect-preview.f2ddc3d7b";const M=new class{constructor(e){this.name=e,this._logLevel=_,this._logHandler=I,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in l))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?w[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,l.DEBUG,...e),this._logHandler(this,l.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,l.VERBOSE,...e),this._logHandler(this,l.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,l.INFO,...e),this._logHandler(this,l.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,l.WARN,...e),this._logHandler(this,l.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,l.ERROR,...e),this._logHandler(this,l.ERROR,...e)}}("@firebase/firestore");function L(){return M.logLevel}function O(e,...t){var n;M.logLevel<=l.DEBUG&&(n=t.map(V),M.debug(`Firestore (${R}): ${e}`,...n))}function F(e,...t){var n;M.logLevel<=l.ERROR&&(n=t.map(V),M.error(`Firestore (${R}): ${e}`,...n))}function P(e,...t){var n;M.logLevel<=l.WARN&&(n=t.map(V),M.warn(`Firestore (${R}): ${e}`,...n))}function V(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function U(e="Unexpected state"){var t=`FIRESTORE (${R}) INTERNAL ASSERTION FAILED: `+e;throw F(t),new Error(t)}function B(e){e||U()}const q={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 j extends d{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class G{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class z{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class K{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(k.UNAUTHENTICATED))}shutdown(){}}class ${constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Q{constructor(e){this.t=e,this.currentUser=k.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new G;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new G,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{O("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(O("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new G))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(O("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(B("string"==typeof e.accessToken),new z(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return B(null===e||"string"==typeof e),new k(e)}}class H{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=k.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class W{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new H(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(k.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Y{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class J{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){const r=e=>{null!=e.error&&O("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,O("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{O("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):O("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(B("string"==typeof e.token),this.R=e.token,new Y(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class X{static newId(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Z(e,t){return e<t?-1:t<e?1:0}function ee(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function te(e){return e+"\0"}class ne{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new j(q.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new j(q.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new j(q.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new j(q.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ne.fromMillis(Date.now())}static fromDate(e){return ne.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ne(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Z(this.nanoseconds,e.nanoseconds):Z(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class re{constructor(e){this.timestamp=e}static fromTimestamp(e){return new re(e)}static min(){return new re(new ne(0,0))}static max(){return new re(new ne(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class ie{constructor(e,t,n){void 0===t?t=0:t>e.length&&U(),void 0===n?n=e.length-t:n>e.length-t&&U(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ie.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ie?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class se extends ie{construct(e,t,n){return new se(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new j(q.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new se(t)}static emptyPath(){return new se([])}}const ae=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class oe extends ie{construct(e,t,n){return new oe(e,t,n)}static isValidIdentifier(e){return ae.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!oe.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new oe(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new j(q.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new j(q.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new j(q.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new j(q.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new oe(t)}static emptyPath(){return new oe([])}}class ue{constructor(e){this.path=e}static fromPath(e){return new ue(se.fromString(e))}static fromName(e){return new ue(se.fromString(e).popFirst(5))}static empty(){return new ue(se.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===se.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return se.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ue(new se(e.slice()))}}class ce{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function he(e){return e.fields.find(e=>2===e.kind)}function le(e){return e.fields.filter(e=>2!==e.kind)}ce.UNKNOWN_ID=-1;class de{constructor(e,t){this.fieldPath=e,this.kind=t}}class fe{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new fe(0,pe.min())}}function ge(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=re.fromTimestamp(1e9===r?new ne(n+1,0):new ne(n,r));return new pe(r,ue.empty(),t)}function me(e){return new pe(e.readTime,e.key,-1)}class pe{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new pe(re.min(),ue.empty(),-1)}static max(){return new pe(re.max(),ue.empty(),-1)}}function ye(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ue.comparator(e.documentKey,t.documentKey),0!==n?n:Z(e.largestBatchId,t.largestBatchId))}const ve="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class we{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function _e(e){if(e.code!==q.FAILED_PRECONDITION||e.message!==ve)throw e;O("LocalStore","Unexpectedly lost primary lease")}class be{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&U(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new be((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof be?t:be.resolve(t)}catch(e){return be.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):be.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):be.reject(t)}static resolve(n){return new be((e,t)=>{e(n)})}static reject(n){return new be((e,t)=>{t(n)})}static waitFor(e){return new be((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=be.resolve(!1);for(const n of e)t=t.next(e=>e?be.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,u){return new be((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;u(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new be((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class Ie{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.V=new G,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{e.error?this.V.reject(new xe(n,e.error)):this.V.resolve()},this.transaction.onerror=e=>{var t=ke(e.target.error);this.V.reject(new xe(n,t))}}static open(e,t,n,r){try{return new Ie(t,e.transaction(r,n))}catch(e){throw new xe(t,e)}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(O("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Ce(t)}}class Ee{constructor(e,t,n){this.name=e,this.version=t,this.p=n,12.2===Ee.S(u())&&F("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return O("SimpleDb","Removing database:",e),Ae(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(Ee.C())return!0;const e=u(),t=Ee.S(e),n=0<t&&t<10,r=Te(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static C(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.__PRIVATE_env)||void 0===e?void 0:e.v)}static F(e,t){return e.store(t)}static S(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}async M(s){return this.db||(O("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new xe(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new j(q.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new j(q.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new xe(s,t))},i.onupgradeneeded=e=>{O("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.p.O(t,i.transaction,e.oldVersion,this.version).next(()=>{O("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(t){this.N=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.M(e);const t=Ie.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.g(),e)).catch(e=>(t.abort(e),be.reject(e))).toPromise();return s.catch(()=>{}),await t.m,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(O("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function Te(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}class Se{constructor(e){this.B=e,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(e){this.B=e}done(){this.k=!0}$(e){this.q=e}delete(){return Ae(this.B.delete())}}class xe extends j{constructor(e,t){super(q.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function De(e){return"IndexedDbTransactionError"===e.name}class Ce{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(O("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(O("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),Ae(n)}add(e){return O("SimpleDb","ADD",this.store.name,e,e),Ae(this.store.add(e))}get(t){return Ae(this.store.get(t)).next(e=>(O("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return O("SimpleDb","DELETE",this.store.name,e),Ae(this.store.delete(e))}count(){return O("SimpleDb","COUNT",this.store.name),Ae(this.store.count())}U(e,n){const t=this.options(e,n),r=t.index?this.store.index(t.index):this.store;if("function"==typeof r.getAll){const e=r.getAll(t.range);return new be((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{const e=this.cursor(t),n=[];return this.W(e,(e,t)=>{n.push(t)}).next(()=>n)}}G(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new be((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}j(e,t){O("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.H=!1;var r=this.cursor(n);return this.W(r,(e,t,n)=>n.delete())}J(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.W(r,t)}Y(i){const e=this.cursor({});return new be((n,r)=>{e.onerror=e=>{var t=ke(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}W(e,s){const a=[];return new be((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new Se(t),r=s(t.primaryKey,t.value,n);if(r instanceof be){const e=r.catch(e=>(n.done(),be.reject(e)));a.push(e)}n.isDone?i():null===n.K?t.continue():t.continue(n.K)}else i()}}).next(()=>be.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.H?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Ae(e){return new be((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=ke(e.target.error);r(t)}})}let Ne=!1;function ke(e){const t=Ee.S(u());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new j("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Ne||(Ne=!0,setTimeout(()=>{throw e},0)),e}}return e}class Re{constructor(e,t){this.asyncQueue=e,this.Z=t,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){O("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{O("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){De(e)?O("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await _e(e)}await this.X(6e4)})}}class Me{constructor(e,t){this.localStore=e,this.persistence=t}async ee(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.te(e,t))}te(e,t){const n=new Set;let r=t,i=!0;return be.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(O("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ne(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.re(n,e)).next(e=>(O("IndexBackfiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}re(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=me(t);0<ye(n,r)&&(r=n)}),new pe(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Le{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.se&&this.se(e),e}}function Oe(e){return null==e}function Fe(e){return 0===e&&1/e==-1/0}function Pe(e){return"number"==typeof e&&Number.isInteger(e)&&!Fe(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Ve(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Ue(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Ue(t)}function Ue(e){return e+""}function Be(t){const n=t.length;if(B(2<=n),2===n)return B(""===t.charAt(0)&&""===t.charAt(1)),se.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&U(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:U()}a=n+2}return new se(r)}Le.oe=-1;const qe=["userId","batchId"];function je(e,t){return[e,Ve(t)]}function Ge(e,t,n){return[e,Ve(t),n]}const ze={},Ke=["prefixPath","collectionGroup","readTime","documentId"],$e=["prefixPath","collectionGroup","documentId"],Qe=["collectionGroup","readTime","prefixPath","documentId"],He=["canonicalId","targetId"],We=["targetId","path"],Ye=["path","targetId"],Je=["collectionId","parent"],Xe=["indexId","uid"],Ze=["uid","sequenceNumber"],et=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],tt=["indexId","uid","orderedDocumentKey"],nt=["userId","collectionPath","documentId"],rt=["userId","collectionPath","largestBatchId"],it=["userId","collectionGroup","largestBatchId"],st=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],at=[...st,"documentOverlays"],ot=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ut=ot,ct=[...ut,"indexConfiguration","indexState","indexEntries"],ht=ct;class lt extends we{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function dt(e,t){var n=e;return Ee.F(n._e,t)}function ft(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function gt(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function mt(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class pt{constructor(e,t){this.comparator=e,this.root=t||vt.EMPTY}insert(e,t){return new pt(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,vt.BLACK,null,null))}remove(e){return new pt(this.comparator,this.root.remove(e,this.comparator).copy(null,null,vt.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new yt(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new yt(this.root,e,this.comparator,!1)}getReverseIterator(){return new yt(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new yt(this.root,e,this.comparator,!0)}}class yt{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class vt{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:vt.RED,this.left=null!=r?r:vt.EMPTY,this.right=null!=i?i:vt.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new vt(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return vt.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return vt.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,vt.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,vt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw U();if(this.right.isRed())throw U();var e=this.left.check();if(e!==this.right.check())throw U();return e+(this.isRed()?0:1)}}vt.EMPTY=null,vt.RED=!0,vt.BLACK=!1,vt.EMPTY=new class{constructor(){this.size=0}get key(){throw U()}get value(){throw U()}get color(){throw U()}get left(){throw U()}get right(){throw U()}copy(e,t,n,r,i){return this}insert(e,t,n){return new vt(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class wt{constructor(e){this.comparator=e,this.data=new pt(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new _t(this.data.getIterator())}getIteratorFrom(e){return new _t(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof wt))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new wt(this.comparator);return t.data=e,t}}class _t{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function bt(e){return e.hasNext()?e.getNext():void 0}class It{constructor(e){(this.fields=e).sort(oe.comparator)}static empty(){return new It([])}unionWith(e){let t=new wt(oe.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new It(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return ee(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class Et extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class Tt{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new Et("Invalid base64 string: "+e):e}}(e);return new Tt(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new Tt(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Z(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}Tt.EMPTY_BYTE_STRING=new Tt("");const St=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function xt(t){if(B(!!t),"string"!=typeof t)return{seconds:Dt(t.seconds),nanos:Dt(t.nanos)};{let e=0;var n=St.exec(t);B(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Dt(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ct(e){return"string"==typeof e?Tt.fromBase64String(e):Tt.fromUint8Array(e)}function At(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Nt(e){var t=e.mapValue.fields.__previous_value__;return At(t)?Nt(t):t}function kt(e){var t=xt(e.mapValue.fields.__local_write_time__.timestampValue);return new ne(t.seconds,t.nanos)}class Rt{constructor(e,t,n,r,i,s,a,o,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=u}}class Mt{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Mt("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Mt&&e.projectId===this.projectId&&e.database===this.database}}const Lt={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Ot={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?At(e)?4:Wt(e)?9007199254740991:10:U()}function Pt(e,t){if(e===t)return!0;var n,r,i=Ft(e);if(i!==Ft(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return kt(e).isEqual(kt(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=xt(e.timestampValue),r=xt(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return r=t,Ct(e.bytesValue).isEqual(Ct(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,Dt((r=e).geoPointValue.latitude)===Dt(n.geoPointValue.latitude)&&Dt(r.geoPointValue.longitude)===Dt(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Dt(e.integerValue)===Dt(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Dt(e.doubleValue),r=Dt(t.doubleValue);return n===r?Fe(n)===Fe(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return ee(e.arrayValue.values||[],t.arrayValue.values||[],Pt);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(ft(n)!==ft(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Pt(n[e],r[e])))return!1;return!0}(e,t);default:return U()}}function Vt(e,t){return void 0!==(e.values||[]).find(e=>Pt(e,t))}function Ut(e,t){if(e===t)return 0;var n,r,i,s,a=Ft(e),o=Ft(t);if(a!==o)return Z(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Z(e.booleanValue,t.booleanValue);case 2:return r=t,i=Dt((n=e).integerValue||n.doubleValue),s=Dt(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Bt(e.timestampValue,t.timestampValue);case 4:return Bt(kt(e),kt(t));case 5:return Z(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ct(e),r=Ct(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Z(n[i],r[i]);if(0!==t)return t}return Z(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Z(Dt(n.latitude),Dt(r.latitude)))?s:Z(Dt(n.longitude),Dt(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Ut(n[i],r[i]);if(t)return t}return Z(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Lt.mapValue&&t===Lt.mapValue)return 0;if(e===Lt.mapValue)return 1;if(t===Lt.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=Z(r[o],s[o]);if(0!==t)return t;var a=Ut(n[r[o]],i[s[o]]);if(0!==a)return a}return Z(r.length,s.length)}(e.mapValue,t.mapValue);default:throw U()}}function Bt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Z(e,t);var n=xt(e),r=xt(t),i=Z(n.seconds,r.seconds);return 0!==i?i:Z(n.nanos,r.nanos)}function qt(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=xt(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Ct(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return ue.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):U()}(e)}function jt(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Gt(e){return!!e&&"integerValue"in e}function zt(e){return!!e&&"arrayValue"in e}function Kt(e){return e&&"nullValue"in e}function $t(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Qt(e){return e&&"mapValue"in e}function Ht(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return gt(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Ht(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Ht(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Wt(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Yt(e,t){var n=Ut(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Jt(e,t){var n=Ut(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Xt{constructor(e){this.value=e}static empty(){return new Xt({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!Qt(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ht(t)}setAll(e){let n=oe.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Ht(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Qt(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Pt(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];Qt(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){gt(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Xt(Ht(this.value))}}class Zt{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Zt(e,0,re.min(),re.min(),re.min(),Xt.empty(),0)}static newFoundDocument(e,t,n,r){return new Zt(e,1,t,re.min(),n,r,0)}static newNoDocument(e,t){return new Zt(e,2,t,re.min(),re.min(),Xt.empty(),0)}static newUnknownDocument(e,t){return new Zt(e,3,t,re.min(),re.min(),Xt.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(re.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Xt.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Xt.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=re.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Zt&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Zt(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class en{constructor(e,t){this.position=e,this.inclusive=t}}function tn(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?ue.comparator(ue.fromName(a.referenceValue),n.key):Ut(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function nn(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Pt(e.position[n],t.position[n]))return!1;return!0}class rn{constructor(e,t="asc"){this.field=e,this.dir=t}}class sn{}class an extends sn{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new Tn(e,t,n):"array-contains"===t?new Cn(e,n):"in"===t?new An(e,n):"not-in"===t?new Nn(e,n):"array-contains-any"===t?new kn(e,n):new an(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?Sn:xn)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Ut(t,this.value)):null!==t&&Ft(this.value)===Ft(t)&&this.matchesComparison(Ut(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return U()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class on extends sn{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new on(e,t)}matches(t){return un(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function un(e){return"and"===e.op}function cn(e){return"or"===e.op}function hn(e){return ln(e)&&un(e)}function ln(e){for(const t of e.filters)if(t instanceof on)return!1;return!0}function In(e,t){var n=e.filters.concat(t);return on.create(n,e.op)}function En(e){return e instanceof an?`${(t=e).field.canonicalString()} ${t.op} ${qt(t.value)}`:e instanceof on?(e=e).op.toString()+" {"+e.getFilters().map(En).join(" ,")+"}":"Filter";var t}class Tn extends an{constructor(e,t,n){super(e,t,n),this.key=ue.fromName(n.referenceValue)}matches(e){var t=ue.comparator(e.key,this.key);return this.matchesComparison(t)}}class Sn extends an{constructor(e,t){super(e,"in",t),this.keys=Dn(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class xn extends an{constructor(e,t){super(e,"not-in",t),this.keys=Dn(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function Dn(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ue.fromName(e.referenceValue))}class Cn extends an{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return zt(t)&&Vt(t.arrayValue,this.value)}}class An extends an{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Vt(this.value.arrayValue,t)}}class Nn extends an{constructor(e,t){super(e,"not-in",t)}matches(e){if(Vt(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Vt(this.value.arrayValue,t)}}class kn extends an{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!zt(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Vt(this.value.arrayValue,e))}}class Rn{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ue=null}}function Mn(e,t=null,n=[],r=[],i=null,s=null,a=null){return new Rn(e,t,n,r,i,s,a)}function Ln(e){const t=e;if(null===t.ue){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof an)return e.field.canonicalString()+e.op.toString()+qt(e.value);if(hn(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),Oe(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>qt(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>qt(e)).join(",")),t.ue=e}return t.ue}function On(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof an?(n=e,(s=t)instanceof an&&n.op===s.op&&n.field.isEqual(s.field)&&Pt(n.value,s.value)):e instanceof on?(i=t)instanceof on&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void U();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!nn(e.startAt,t.startAt)&&nn(e.endAt,t.endAt)}function Fn(e){return ue.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Pn(e,t){return e.filters.filter(e=>e instanceof an&&e.field.isEqual(t))}function Vn(t,n,r){let i=Ot,s=!0;for(const r of Pn(t,n)){let e=Ot,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Ot:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?jt(Mt.empty(),ue.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:U();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Ot}Yt({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Yt({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function Un(t,n,r){let i=Lt,s=!0;for(const r of Pn(t,n)){let e=Lt,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?jt(Mt.empty(),ue.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Lt:U(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Lt}0<Jt({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Jt({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class Bn{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function qn(e,t,n,r,i,s,a,o){return new Bn(e,t,n,r,i,s,a,o)}function jn(e){return new Bn(e)}function Gn(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 zn(e){return null!==e.collectionGroup}function Kn(t){const n=t;if(null===n.ce){n.ce=[];const t=new Set;for(const i of n.explicitOrderBy)n.ce.push(i),t.add(i.field.canonicalString());const r=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc",e=function(e){let t=new wt(oe.comparator);return e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t}(n);e.forEach(e=>{t.has(e.canonicalString())||e.isKeyField()||n.ce.push(new rn(e,r))}),t.has(oe.keyField().canonicalString())||n.ce.push(new rn(oe.keyField(),r))}return n.ce}function $n(e){const t=e;return t.le||(t.le=function(e,t){if("F"===e.limitType)return Mn(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new rn(e.field,t)});var n=e.endAt?new en(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new en(e.startAt.position,e.startAt.inclusive):null;return Mn(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,Kn(e))),t.le}function Qn(e,t){var n=e.filters.concat([t]);return new Bn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Hn(e,t,n){return new Bn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Wn(e,t){return On($n(e),$n(t))&&e.limitType===t.limitType}function Yn(e){return`${Ln($n(e))}|lt:${e.limitType}`}function Jn(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>En(e)).join(", ")}]`),Oe(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>qt(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>qt(e)).join(",")),`Target(${t})`}($n(e))}; limitType=${e.limitType})`}function Xn(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ue.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of Kn(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=Kn(t),r=tn(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=Kn(t),r=tn(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function Zn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function er(i){return(e,t)=>{let n=!1;for(const r of Kn(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ue.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?Ut(r,i):U()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return U()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class tr{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){gt(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return mt(this.inner)}size(){return this.innerSize}}const nr=new pt(ue.comparator);const rr=new pt(ue.comparator);function ir(...e){let t=rr;for(const n of e)t=t.insert(n.key,n);return t}function sr(e){let n=rr;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function ar(){return new tr(e=>e.toString(),(e,t)=>e.isEqual(t))}const or=new pt(ue.comparator),ur=new wt(ue.comparator);function cr(...e){let t=ur;for(const n of e)t=t.add(n);return t}const hr=new wt(Z);function lr(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Fe(t)?"-0":t}}function dr(e){return{integerValue:""+e}}function fr(e,t){return Pe(t)?dr(t):lr(e,t)}class gr{constructor(){this._=void 0}}function mr(e,t){return e instanceof br?Gt(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class pr extends gr{}class yr extends gr{constructor(e){super(),this.elements=e}}function vr(e,t){const n=Er(t);for(const t of e.elements)n.some(e=>Pt(e,t))||n.push(t);return{arrayValue:{values:n}}}class wr extends gr{constructor(e){super(),this.elements=e}}function _r(e,t){let n=Er(t);for(const t of e.elements)n=n.filter(e=>!Pt(e,t));return{arrayValue:{values:n}}}class br extends gr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function Ir(e){return Dt(e.integerValue||e.doubleValue)}function Er(e){return zt(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Tr{constructor(e,t){this.field=e,this.transform=t}}class Sr{constructor(e,t){this.version=e,this.transformResults=t}}class xr{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new xr}static exists(e){return new xr(void 0,e)}static updateTime(e){return new xr(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Dr(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Cr{}function Ar(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new Vr(e.key,xr.none()):new Mr(e.key,e.data,xr.none());{const i=e.data,s=Xt.empty();let t=new wt(oe.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new Lr(e.key,s,new It(t.toArray()),xr.none())}}function Nr(e,t,n){e instanceof Mr?function(e,t,n){const r=e.value.clone(),i=Fr(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(!Dr(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Fr(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Or(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function kr(e,t,n,r){return e instanceof Mr?function(e,t,n,r){if(!Dr(e.precondition,t))return n;const i=e.value.clone(),s=Pr(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof Lr?function(e,t,n,r){if(!Dr(e.precondition,t))return n;const i=Pr(e.fieldTransforms,r,t),s=t.data;return s.setAll(Or(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,Dr(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function Rr(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&ee(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof yr&&t instanceof yr||e instanceof wr&&t instanceof wr?ee(e.elements,t.elements,Pt):e instanceof br&&t instanceof br?Pt(e.Pe,t.Pe):e instanceof pr&&t instanceof pr)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class Mr extends Cr{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class Lr extends Cr{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Or(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function Fr(e,t,n){const r=new Map;B(e.length===n.length);for(let h=0;h<n.length;h++){var i=e[h],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,u=a,c=n[h],o instanceof yr?vr(o,u):o instanceof wr?_r(o,u):c))}var o,u,c;return r}function Pr(e,t,n){const r=new Map;for(const c of e){const e=c.transform,h=n.data.field(c.field);r.set(c.field,(i=e,s=h,a=t,u=o=void 0,i instanceof pr?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&At(t)?Nt(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof yr?vr(i,s):i instanceof wr?_r(i,s):(o=mr(i=i,s),u=Ir(o)+Ir(i.Pe),Gt(o)&&Gt(i.Pe)?dr(u):lr(i.serializer,u))))}var i,s,a,o,u;return r}class Vr extends Cr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Ur extends Cr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Br{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&Nr(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=kr(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=kr(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=ar();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=Ar(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(re.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),cr())}isEqual(e){return this.batchId===e.batchId&&ee(this.mutations,e.mutations,(e,t)=>Rr(e,t))&&ee(this.baseMutations,e.baseMutations,(e,t)=>Rr(e,t))}}class qr{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){B(e.mutations.length===n.length);let r=or;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new qr(e,t,n,r)}}class jr{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Gr{constructor(e,t){this.count=e,this.unchangedNames=t}}function zr(e){switch(e){default:return U();case q.CANCELLED:case q.UNKNOWN:case q.DEADLINE_EXCEEDED:case q.RESOURCE_EXHAUSTED:case q.INTERNAL:case q.UNAVAILABLE:case q.UNAUTHENTICATED:return!1;case q.INVALID_ARGUMENT:case q.NOT_FOUND:case q.ALREADY_EXISTS:case q.PERMISSION_DENIED:case q.FAILED_PRECONDITION:case q.ABORTED:case q.OUT_OF_RANGE:case q.UNIMPLEMENTED:case q.DATA_LOSS:return!0}}function Kr(e){if(void 0===e)return F("GRPC error has no .code"),q.UNKNOWN;switch(e){case x.OK:return q.OK;case x.CANCELLED:return q.CANCELLED;case x.UNKNOWN:return q.UNKNOWN;case x.DEADLINE_EXCEEDED:return q.DEADLINE_EXCEEDED;case x.RESOURCE_EXHAUSTED:return q.RESOURCE_EXHAUSTED;case x.INTERNAL:return q.INTERNAL;case x.UNAVAILABLE:return q.UNAVAILABLE;case x.UNAUTHENTICATED:return q.UNAUTHENTICATED;case x.INVALID_ARGUMENT:return q.INVALID_ARGUMENT;case x.NOT_FOUND:return q.NOT_FOUND;case x.ALREADY_EXISTS:return q.ALREADY_EXISTS;case x.PERMISSION_DENIED:return q.PERMISSION_DENIED;case x.FAILED_PRECONDITION:return q.FAILED_PRECONDITION;case x.ABORTED:return q.ABORTED;case x.OUT_OF_RANGE:return q.OUT_OF_RANGE;case x.UNIMPLEMENTED:return q.UNIMPLEMENTED;case x.DATA_LOSS:return q.DATA_LOSS;default:return U()}}function $r(){return new TextEncoder}(S=x=x||{})[S.OK=0]="OK",S[S.CANCELLED=1]="CANCELLED",S[S.UNKNOWN=2]="UNKNOWN",S[S.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",S[S.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",S[S.NOT_FOUND=5]="NOT_FOUND",S[S.ALREADY_EXISTS=6]="ALREADY_EXISTS",S[S.PERMISSION_DENIED=7]="PERMISSION_DENIED",S[S.UNAUTHENTICATED=16]="UNAUTHENTICATED",S[S.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",S[S.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",S[S.ABORTED=10]="ABORTED",S[S.OUT_OF_RANGE=11]="OUT_OF_RANGE",S[S.UNIMPLEMENTED=12]="UNIMPLEMENTED",S[S.INTERNAL=13]="INTERNAL",S[S.UNAVAILABLE=14]="UNAVAILABLE",S[S.DATA_LOSS=15]="DATA_LOSS";const Qr=new E([4294967295,4294967295],0);function Hr(e){const t=$r().encode(e),n=new T;return n.update(t),new Uint8Array(n.digest())}function Wr(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new E([n,r],0),new E([i,s],0)]}class Yr{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new Jr(`Invalid padding: ${t}`);if(n<0)throw new Jr(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new Jr(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Jr(`Invalid padding when bitmap length is 0: ${t}`);this.Ie=8*e.length-t,this.Te=E.fromNumber(this.Ie)}Ee(e,t,n){let r=e.add(t.multiply(E.fromNumber(n)));return 1===r.compare(Qr)&&(r=new E([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Te).toNumber()}de(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ie)return!1;const t=Hr(e),[n,r]=Wr(t);for(let i=0;i<this.hashCount;i++){const t=this.Ee(n,r,i);if(!this.de(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Yr(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ie){const n=Hr(t),[r,i]=Wr(n);for(let e=0;e<this.hashCount;e++){const n=this.Ee(r,i,e);this.Ae(n)}}}Ae(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class Jr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Xr{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,Zr.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Xr(re.min(),r,new pt(Z),nr,cr())}}class Zr{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new Zr(n,t,cr(),cr(),cr())}}class ei{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class ti{constructor(e,t){this.targetId=e,this.me=t}}class ni{constructor(e,t,n=Tt.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ri{constructor(){this.fe=0,this.ge=ai(),this.pe=Tt.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){0<e.approximateByteSize()&&(this.we=!0,this.pe=e)}Ce(){let n=cr(),r=cr(),i=cr();return this.ge.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:U()}}),new Zr(this.pe,this.ye,n,r,i)}ve(){this.we=!1,this.ge=ai()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){--this.fe,B(0<=this.fe)}Ne(){this.we=!0,this.ye=!0}}class ii{constructor(e){this.Le=e,this.Be=new Map,this.ke=nr,this.qe=si(),this.Qe=new pt(Z)}Ke(e){for(const t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.$e(t,e.Ve):this.Ue(t,e.key,e.Ve);for(const n of e.removedTargetIds)this.Ue(n,e.key,e.Ve)}We(n){this.forEachTarget(n,e=>{const t=this.Ge(e);switch(n.state){case 0:this.ze(e)&&t.De(n.resumeToken);break;case 1:t.Oe(),t.Se||t.ve(),t.De(n.resumeToken);break;case 2:t.Oe(),t.Se||this.removeTarget(e);break;case 3:this.ze(e)&&(t.Ne(),t.De(n.resumeToken));break;case 4:this.ze(e)&&(this.je(e),t.De(n.resumeToken));break;default:U()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Be.forEach((e,t)=>{this.ze(t)&&n(t)})}He(e){const t=e.targetId,n=e.me.count,r=this.Je(t);if(r){var i=r.target;if(Fn(i))if(0===n){const e=new ue(i.path);this.Ue(t,e,Zt.newNoDocument(e,re.min()))}else B(1===n);else{const r=this.Ye(t);if(r!==n){const n=this.Ze(e),s=n?this.Xe(n,e,r):1;if(0!==s){this.je(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Qe=this.Qe.insert(t,e)}}}}}Ze(e){var t=e.me.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=Ct(n).toUint8Array()}catch(e){if(e instanceof Et)return P("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new Yr(i,r,t)}catch(e){return P(e instanceof Jr?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ie?null:s}Xe(e,t,n){return t.me.count===n-this.nt(e,t.targetId)?0:2}nt(n,r){const e=this.Le.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Le.tt(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.Ue(r,e,null),i++)}),i}rt(r){const i=new Map;this.Be.forEach((e,t)=>{var n=this.Je(t);if(n){if(e.current&&Fn(n.target)){const i=new ue(n.target.path);null!==this.ke.get(i)||this.it(t,i)||this.Ue(t,i,Zt.newNoDocument(i,r))}e.be&&(i.set(t,e.Ce()),e.ve())}});let s=cr();this.qe.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Je(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.ke.forEach((e,t)=>t.setReadTime(r));var e=new Xr(r,i,this.Qe,this.ke,s);return this.ke=nr,this.qe=si(),this.Qe=new pt(Z),e}$e(e,t){var n;this.ze(e)&&(n=this.it(e,t.key)?2:0,this.Ge(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e)))}Ue(e,t,n){if(this.ze(e)){const r=this.Ge(e);this.it(e,t)?r.Fe(t,1):r.Me(t),this.qe=this.qe.insert(t,this.st(t).delete(e)),n&&(this.ke=this.ke.insert(t,n))}}removeTarget(e){this.Be.delete(e)}Ye(e){var t=this.Ge(e).Ce();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.Ge(e).xe()}Ge(e){let t=this.Be.get(e);return t||(t=new ri,this.Be.set(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new wt(Z),this.qe=this.qe.insert(e,t)),t}ze(e){var t=null!==this.Je(e);return t||O("WatchChangeAggregator","Detected inactive target",e),t}Je(e){var t=this.Be.get(e);return t&&t.Se?null:this.Le.ot(e)}je(t){this.Be.set(t,new ri),this.Le.getRemoteKeysForTarget(t).forEach(e=>{this.Ue(t,e,null)})}it(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function si(){return new pt(ue.comparator)}function ai(){return new pt(ue.comparator)}const oi={asc:"ASCENDING",desc:"DESCENDING"},ui={"<":"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"},ci={and:"AND",or:"OR"};class hi{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function li(e,t){return e.useProto3Json||Oe(t)?t:{value:t}}function di(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function fi(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function gi(e){return B(!!e),re.fromTimestamp((t=xt(e),new ne(t.seconds,t.nanos)));var t}function mi(e,t){return pi(e,t).canonicalString()}function pi(e,t){const n=(e=e,new se(["projects",e.projectId,"databases",e.database]).child("documents"));return void 0===t?n:n.child(t)}function yi(e){var t=se.fromString(e);return B(Oi(t)),t}function vi(e,t){return mi(e.databaseId,t.path)}function wi(e,t){const n=yi(t);if(n.get(1)!==e.databaseId.projectId)throw new j(q.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 j(q.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ue(Ei(n))}function _i(e,t){return mi(e.databaseId,t)}function bi(e){var t=yi(e);return 4===t.length?se.emptyPath():Ei(t)}function Ii(e){return new se(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Ei(e){return B(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function Ti(e,t,n){return{name:vi(e,t),fields:n.value.mapValue.fields}}function Si(e,t,n){const r=wi(e,t.name),i=gi(t.updateTime),s=t.createTime?gi(t.createTime):re.min(),a=new Xt({mapValue:{fields:t.fields}}),o=Zt.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function xi(e,t){let n;if(t instanceof Mr)n={update:Ti(e,t.key,t.value)};else if(t instanceof Vr)n={delete:vi(e,t.key)};else if(t instanceof Lr)n={update:Ti(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof Ur))return U();n={verify:vi(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof pr)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof yr)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof wr)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof br)return{fieldPath:e.field.canonicalString(),increment:t.Pe};throw U()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,di(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:U())),n;var r}function Di(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?xr.updateTime(gi(i.updateTime)):void 0!==i.exists?xr.exists(i.exists):xr.none():xr.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)B("REQUEST_TIME"===t.setToServerValue),n=new pr;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new yr(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new wr(e)}else"increment"in t?n=new br(e,t.increment):U();var r=oe.fromServerFormat(t.fieldPath);return new Tr(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=wi(t,e.update.name),a=new Xt({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new It(t.map(e=>oe.fromServerFormat(e)))}(e.updateMask);return new Lr(s,a,t,n,r)}return new Mr(s,a,n,r)}if(e.delete){const r=wi(t,e.delete);return new Vr(r,n)}if(e.verify){const r=wi(t,e.verify);return new Ur(r,n)}return U()}function Ci(e,t){return{documents:[_i(e,t.path)]}}function Ai(e,t){const n={structuredQuery:{}},r=t.path;let i;null!==t.collectionGroup?(i=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=_i(e,i);var s=function(e){if(0!==e.length)return function n(e){return e instanceof an?function(e){if("=="===e.op){if($t(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NAN"}};if(Kt(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NULL"}}}else if("!="===e.op){if($t(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NOT_NAN"}};if(Kt(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Mi(e.field),op:ki(e.op),value:e.value}}}(e):e instanceof on?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:Ri(e.op),filters:t}}}(e):U()}(on.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:Mi(e.field),direction:(e=e.dir,oi[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);s=li(e,t.limit);return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),{_t:n,parent:i}}function Ni(e){let t=bi(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){B(1===a);const f=s.from[0];f.allDescendants?o=f.collectionId:t=t.child(f.collectionId)}let u=[];s.where&&(u=function(e){const t=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Li(e.unaryFilter.field);return an.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Li(e.unaryFilter.field);return an.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Li(e.unaryFilter.field);return an.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=Li(e.unaryFilter.field);return an.create(i,"!=",{nullValue:"NULL_VALUE"});default:return U()}}(e):void 0!==e.fieldFilter?function(e){return an.create(Li(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 U()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return on.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return U()}}(e.compositeFilter.op))}(e):U()}(e);return t instanceof on&&hn(t)?t.getFilters():[t]}(s.where));let c=[];s.orderBy&&(c=s.orderBy.map(e=>function(e){return new rn(Li(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let h=null;s.limit&&(h=(e=s.limit,Oe(n="object"==typeof e?e.value:e)?null:n));let l=null;s.startAt&&(l=(r=s.startAt,i=!!r.before,n=r.values||[],new en(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new en(s,i))),qn(t,o,c,u,h,"F",l,d)}function ki(e){return ui[e]}function Ri(e){return ci[e]}function Mi(e){return{fieldPath:e.canonicalString()}}function Li(e){return oe.fromServerFormat(e.fieldPath)}function Oi(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class Fi{constructor(e,t,n,r,i=re.min(),s=re.min(),a=Tt.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Fi(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Fi(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Fi(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Fi(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Pi{constructor(e){this.ct=e}}function Vi(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Ui(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:vi(i=e.ct,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:di(i,e.version.toTimestamp()),createTime:di(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Bi(t.version)};else{if(!t.isUnknownDocument())return U();r.unknownDocument={path:n.path.toArray(),version:Bi(t.version)}}var i;return r}function Ui(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Bi(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function qi(e){var t=new ne(e.seconds,e.nanoseconds);return re.fromTimestamp(t)}function ji(t,e){const n=(e.baseMutations||[]).map(e=>Di(t.ct,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>Di(t.ct,e)),i=ne.fromMillis(e.localWriteTimeMs);return new Br(e.batchId,i,n,r)}function Gi(e){var t,n=qi(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?qi(e.lastLimboFreeSnapshotVersion):re.min(),i=void 0!==e.query.documents?(B(1===(t=e.query).documents.length),$n(jn(bi(t.documents[0])))):$n(Ni(e.query));return new Fi(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,Tt.fromBase64String(e.resumeToken))}function zi(e,t){var n=Bi(t.snapshotVersion),r=Bi(t.lastLimboFreeSnapshotVersion),i=Fn(t.target)?Ci(e.ct,t.target):Ai(e.ct,t.target)._t,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Ln(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Ki(e){var t=Ni({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Hn(t,t.limit,"L"):t}function $i(e,t){return new jr(t.largestBatchId,Di(e.ct,t.overlayMutation))}function Qi(e,t){var n=t.path.lastSegment();return[e,Ve(t.path.popLast()),n]}function Hi(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:Bi(r.readTime),documentKey:Ve(r.documentKey.path),largestBatchId:r.largestBatchId}}class Wi{getBundleMetadata(e,t){return Yi(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:qi(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return Yi(e).put({bundleId:(t=t).id,createTime:Bi(gi(t.createTime)),version:t.version})}getNamedQuery(e,t){return Ji(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:Ki(e.bundledQuery),readTime:qi(e.readTime)}})}saveNamedQuery(e,t){return Ji(e).put({name:(t=t).name,readTime:Bi(gi(t.readTime)),bundledQuery:t.bundledQuery})}}function Yi(e){return dt(e,"bundles")}function Ji(e){return dt(e,"namedQueries")}class Xi{constructor(e,t){this.serializer=e,this.userId=t}static lt(e,t){var n=t.uid||"";return new Xi(e,n)}getOverlay(e,t){return Zi(e).get(Qi(this.userId,t)).next(e=>e?$i(this.serializer,e):null)}getOverlays(e,t){const n=ar();return be.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new jr(i,t);s.push(this.ht(r,n))}),be.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Ve(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(Zi(n).j("collectionPathOverlayIndex",t))}),be.waitFor(i)}getOverlaysForCollection(e,t,n){const r=ar(),i=Ve(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return Zi(e).U("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=$i(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=ar();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Zi(e).J({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=$i(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}ht(e,t){return Zi(e).put(function(e,t,n){var[,r,i]=Qi(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:xi(e.ct,n.mutation)}}(this.serializer,this.userId,t))}}function Zi(e){return dt(e,"documentOverlays")}class es{constructor(){}Pt(e,t){this.It(e,t),t.Tt()}It(t,n){if("nullValue"in t)this.Et(n,5);else if("booleanValue"in t)this.Et(n,10),n.dt(t.booleanValue?1:0);else if("integerValue"in t)this.Et(n,15),n.dt(Dt(t.integerValue));else if("doubleValue"in t){var e=Dt(t.doubleValue);isNaN(e)?this.Et(n,13):(this.Et(n,15),Fe(e)?n.dt(0):n.dt(e))}else if("timestampValue"in t){let e=t.timestampValue;this.Et(n,20),"string"==typeof e&&(e=xt(e)),n.At(`${e.seconds||""}`),n.dt(e.nanos||0)}else"stringValue"in t?(this.Rt(t.stringValue,n),this.Vt(n)):"bytesValue"in t?(this.Et(n,30),n.ft(Ct(t.bytesValue)),this.Vt(n)):"referenceValue"in t?this.gt(t.referenceValue,n):"geoPointValue"in t?(e=t.geoPointValue,this.Et(n,45),n.dt(e.latitude||0),n.dt(e.longitude||0)):"mapValue"in t?Wt(t)?this.Et(n,Number.MAX_SAFE_INTEGER):(this.yt(t.mapValue,n),this.Vt(n)):"arrayValue"in t?(this.wt(t.arrayValue,n),this.Vt(n)):U()}Rt(e,t){this.Et(t,25),this.St(e,t)}St(e,t){t.At(e)}yt(e,t){var n=e.fields||{};this.Et(t,55);for(const e of Object.keys(n))this.Rt(e,t),this.It(n[e],t)}wt(e,t){var n=e.values||[];this.Et(t,50);for(const e of n)this.It(e,t)}gt(e,t){this.Et(t,37),ue.fromName(e).path.forEach(e=>{this.Et(t,60),this.St(e,t)})}Et(e,t){e.dt(t)}Vt(e){e.dt(2)}}function ts(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}es.bt=new es;class ns{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Dt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ct(n.value),n=t.next();this.vt()}Ft(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Mt(n.value),n=t.next();this.xt()}Ot(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ct(e);else if(e<2048)this.Ct(960|e>>>6),this.Ct(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ct(480|e>>>12),this.Ct(128|63&e>>>6),this.Ct(128|63&e);else{const e=t.codePointAt(0);this.Ct(240|e>>>18),this.Ct(128|63&e>>>12),this.Ct(128|63&e>>>6),this.Ct(128|63&e)}}this.vt()}Nt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Mt(e);else if(e<2048)this.Mt(960|e>>>6),this.Mt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Mt(480|e>>>12),this.Mt(128|63&e>>>6),this.Mt(128|63&e);else{const e=t.codePointAt(0);this.Mt(240|e>>>18),this.Mt(128|63&e>>>12),this.Mt(128|63&e>>>6),this.Mt(128|63&e)}}this.xt()}Lt(e){var t=this.Bt(e),n=ts(t);this.kt(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}qt(e){var t=this.Bt(e),n=ts(t);this.kt(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}Qt(){this.Kt(255),this.Kt(255)}$t(){this.Ut(255),this.Ut(255)}reset(){this.position=0}seed(e){this.kt(e.length),this.buffer.set(e,this.position),this.position+=e.length}Wt(){return this.buffer.slice(0,this.position)}Bt(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ct(e){var t=255&e;0==t?(this.Kt(0),this.Kt(255)):255==t?(this.Kt(255),this.Kt(0)):this.Kt(t)}Mt(e){var t=255&e;0==t?(this.Ut(0),this.Ut(255)):255==t?(this.Ut(255),this.Ut(0)):this.Ut(e)}vt(){this.Kt(0),this.Kt(1)}xt(){this.Ut(0),this.Ut(1)}Kt(e){this.kt(1),this.buffer[this.position++]=e}Ut(e){this.kt(1),this.buffer[this.position++]=~e}kt(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class rs{constructor(e){this.Gt=e}ft(e){this.Gt.Dt(e)}At(e){this.Gt.Ot(e)}dt(e){this.Gt.Lt(e)}Tt(){this.Gt.Qt()}}class is{constructor(e){this.Gt=e}ft(e){this.Gt.Ft(e)}At(e){this.Gt.Nt(e)}dt(e){this.Gt.qt(e)}Tt(){this.Gt.$t()}}class ss{constructor(){this.Gt=new ns,this.zt=new rs(this.Gt),this.jt=new is(this.Gt)}seed(e){this.Gt.seed(e)}Ht(e){return 0===e?this.zt:this.jt}Wt(){return this.Gt.Wt()}reset(){this.Gt.reset()}}class as{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Jt(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new as(this.indexId,this.documentKey,this.arrayValue,n)}}function os(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=us(e.arrayValue,t.arrayValue),0!==n?n:(n=us(e.directionalValue,t.directionalValue),0!==n?n:ue.comparator(e.documentKey,t.documentKey)))}function us(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class cs{constructor(e){this.Yt=new wt((e,t)=>oe.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Zt=e.orderBy,this.Xt=[];for(const t of e.filters){const e=t;e.isInequality()?this.Yt=this.Yt.add(e):this.Xt.push(e)}}get en(){return 1<this.Yt.size}tn(e){if(B(e.collectionGroup===this.collectionId),this.en)return!1;const t=he(e);if(void 0!==t&&!this.nn(t))return!1;const n=le(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.nn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(0<this.Yt.size){const e=this.Yt.getIterator().getNext();if(!r.has(e.field.canonicalString())){const t=n[i];if(!this.rn(e,t)||!this.sn(this.Zt[s++],t))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Zt.length||!this.sn(this.Zt[s++],e))return!1}return!0}on(){if(this.en)return null;let e=new wt(oe.comparator);const t=[];for(const n of this.Xt)n.field.isKeyField()||("array-contains"===n.op||"array-contains-any"===n.op?t.push(new de(n.field,2)):e.has(n.field)||(e=e.add(n.field),t.push(new de(n.field,0))));for(const r of this.Zt)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new de(r.field,"asc"===r.dir?0:1)));return new ce(ce.UNKNOWN_ID,this.collectionId,t,fe.empty())}nn(e){for(const t of this.Xt)if(this.rn(t,e))return!0;return!1}rn(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}sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function hs(e){if(0===e.getFilters().length)return[];const t=function t(e){if(B(e instanceof an||e instanceof on),e instanceof an)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=on.create(n,e.op);return r=ps(r),fs(r)?r:(B(r instanceof on),B(un(r)),B(1<r.filters.length),r.filters.reduce((e,t)=>gs(e,t)))}(function t(n){var e;if(B(n instanceof an||n instanceof on),n instanceof an){if(n instanceof An){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>an.create(n.field,"==",e)))||[];return on.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return on.create(r,n.op)}(e));return B(fs(t)),ls(t)||ds(t)?[t]:t.getFilters()}function ls(e){return e instanceof an}function ds(e){return e instanceof on&&hn(e)}function fs(e){return ls(e)||ds(e)||function(e){if(e instanceof on&&cn(e)){for(const t of e.getFilters())if(!ls(t)&&!ds(t))return!1;return!0}return!1}(e)}function gs(e,t){var n,r;return B(e instanceof an||e instanceof on),B(t instanceof an||t instanceof on),ps(e instanceof an?t instanceof an?(n=e,r=t,on.create([n,r],"and")):ms(e,t):t instanceof an?ms(t,e):function(e,t){if(B(0<e.filters.length&&0<t.filters.length),un(e)&&un(t))return In(e,t.getFilters());const n=cn(e)?e:t,r=cn(e)?t:e,i=n.filters.map(e=>gs(e,r));return on.create(i,"or")}(e,t))}function ms(t,e){if(un(e))return In(e,t.getFilters());var n=e.filters.map(e=>gs(t,e));return on.create(n,"or")}function ps(t){if(B(t instanceof an||t instanceof on),t instanceof an)return t;const e=t.getFilters();if(1===e.length)return ps(e[0]);if(ln(t))return t;const n=e.map(e=>ps(e)),r=[];return n.forEach(e=>{e instanceof an?r.push(e):e instanceof on&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:on.create(r,t.op)}class ys{constructor(){this._n=new vs}addToCollectionParentIndex(e,t){return this._n.add(t),be.resolve()}getCollectionParents(e,t){return be.resolve(this._n.getEntries(t))}addFieldIndex(e,t){return be.resolve()}deleteFieldIndex(e,t){return be.resolve()}deleteAllFieldIndexes(e){return be.resolve()}createTargetIndexes(e,t){return be.resolve()}getDocumentsMatchingTarget(e,t){return be.resolve(null)}getIndexType(e,t){return be.resolve(0)}getFieldIndexes(e,t){return be.resolve([])}getNextCollectionGroupToUpdate(e){return be.resolve(null)}getMinOffset(e,t){return be.resolve(pe.min())}getMinOffsetFromCollectionGroup(e,t){return be.resolve(pe.min())}updateCollectionGroup(e,t,n){return be.resolve()}updateIndexEntries(e,t){return be.resolve()}}class vs{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new wt(se.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new wt(se.comparator)).toArray()}}const ws=new Uint8Array(0);class _s{constructor(e,t){this.databaseId=t,this.an=new vs,this.un=new tr(e=>Ln(e),(e,t)=>On(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.an.has(t))return be.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.an.add(t)});r={collectionId:n,parent:Ve(r)};return bs(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[te(n),""],!1,!0);return bs(e).U(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Be(t.parent))}return r})}addFieldIndex(e,t){const n=Es(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=Ts(e);return i.next(e=>{n.put(Hi(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=Es(e),r=Ts(e),i=Is(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){const t=Es(e),n=Is(e),r=Ts(e);return t.j().next(()=>n.j()).next(()=>r.j())}createTargetIndexes(n,e){return be.forEach(this.cn(e),t=>this.getIndexType(n,t).next(e=>{if(0===e||1===e){const e=new cs(t).on();if(null!=e)return this.addFieldIndex(n,e)}}))}getDocumentsMatchingTarget(e,h){const l=Is(e);let d=!0;const n=new Map;return be.forEach(this.cn(h),t=>this.ln(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let c=cr();const d=[];return be.forEach(n,(e,t)=>{var n;O("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Ln(h)}`);var r=function(e,t){var n=he(t);if(void 0===n)return null;for(const t of Pn(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),i=function(e,t){const n=new Map;for(const r of le(t))for(const t of Pn(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of le(t)){const t=(0===i.kind?Vn:Un)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new en(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of le(t)){const t=(0===i.kind?Un:Vn)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new en(n,r)}(t,e),o=this.hn(e,t,s),u=this.hn(e,t,a),i=this.Pn(e,t,i),i=this.In(e.indexId,r,o,s.inclusive,u,a.inclusive,i);return be.forEach(i,e=>l.G(e,h.limit).next(e=>{e.forEach(e=>{var t=ue.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),d.push(t))})}))}).next(()=>d)}return be.resolve(null)})}cn(t){let e=this.un.get(t);return e||(e=0===t.filters.length?[t]:hs(on.create(t.filters,"and")).map(e=>Mn(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.un.set(t,e),e)}In(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;h<o;++h){const o=e?this.Tn(e[h/u]):ws,l=this.En(t,o,n[h%u],r),d=this.dn(t,o,i[h%u],s),f=a.map(e=>this.En(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}En(e,t,n,r){const i=new as(e,ue.empty(),t,n);return r?i:i.Jt()}dn(e,t,n,r){const i=new as(e,ue.empty(),t,n);return r?i.Jt():i}ln(e,t){const r=new cs(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.tn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.cn(t);return be.forEach(r,t=>this.ln(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new wt(oe.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>function(e){return null!==e.limit}(t)&&1<r.length&&2===n?1:n)}An(e,t){const n=new ss;for(const i of le(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Ht(i.kind);es.bt.Pt(e,r)}return n.Wt()}Tn(e){const t=new ss;return es.bt.Pt(e,t.Ht(0)),t.Wt()}Rn(e,t){const n=new ss;return es.bt.Pt(jt(this.databaseId,t),n.Ht(0===(r=le(e)).length?0:r[r.length-1].kind)),n.Wt();var r}Pn(e,t,n){if(null===n)return[];let r=[];r.push(new ss);let i=0;for(const s of le(e)){const e=n[i++];for(const n of r)if(this.Vn(t,s.fieldPath)&&zt(e))r=this.mn(r,s,e);else{const t=n.Ht(s.kind);es.bt.Pt(e,t)}}return this.fn(r)}hn(e,t,n){return this.Pn(e,t,n.position)}fn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Wt();return t}mn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new ss;r.seed(n.Wt()),es.bt.Pt(e,r.Ht(t.kind)),i.push(r)}return i}Vn(e,t){return!!e.filters.find(e=>e instanceof an&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=Es(e),r=Ts(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next(e=>{const s=[];return be.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new fe(e.sequenceNumber,new pe(qi(e.readTime),new ue(Be(e.documentKey)),e.largestBatchId)):fe.empty(),r=t.fields.map(([e,t])=>new de(oe.fromServerFormat(e),t)),new ce(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Z(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=Es(e),s=Ts(e);return this.gn(e).next(t=>i.U("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>be.forEach(e,e=>s.put(Hi(e.indexId,this.uid,t,r)))))}updateIndexEntries(i,e){const n=new Map;return be.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?be.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),be.forEach(e,n=>this.pn(i,t,n).next(e=>{var t=this.yn(r,n);return e.isEqual(t)?be.resolve():this.wn(i,r,n,e,t)}))))})}Sn(e,t,n,r){return Is(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Rn(n,t.key),documentKey:t.key.path.toArray()})}bn(e,t,n,r){return Is(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Rn(n,t.key),t.key.path.toArray()])}pn(e,n,r){const t=Is(e);let i=new wt(os);return t.J({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Rn(r,n)])},(e,t)=>{i=i.add(new as(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}yn(e,t){let n=new wt(os);var r=this.An(t,e);if(null==r)return n;const i=he(t);if(null!=i){var s=e.data.field(i.fieldPath);if(zt(s))for(const i of s.arrayValue.values||[])n=n.add(new as(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new as(t.indexId,e.key,ws,r));return n}wn(t,n,r,e,i){O("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=bt(s),u=bt(a);for(;o||u;){let e=!1,t=!1;if(o&&u){const r=n(o,u);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(u),u=bt(a)):t?(i(o),o=bt(s)):(o=bt(s),u=bt(a))}}(e,i,os,e=>{s.push(this.Sn(t,n,r,e))},e=>{s.push(this.bn(t,n,r,e))}),be.waitFor(s)}gn(e){let r=1;return Ts(e).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>os(e,t)).filter((e,t,n)=>!t||0!==os(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=os(i,e),s=os(i,t);if(0===n)r[0]=e.Jt();else if(0<n&&s<0)r.push(i),r.push(i.Jt());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2){if(this.Dn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,ws,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,ws,[]];i.push(IDBKeyRange.bound(t,n))}return i}Dn(e,t){return 0<os(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Ss)}getMinOffset(t,e){return be.mapArray(this.cn(e),e=>this.ln(t,e).next(e=>e||U())).next(Ss)}}function bs(e){return dt(e,"collectionParents")}function Is(e){return dt(e,"indexEntries")}function Es(e){return dt(e,"indexConfiguration")}function Ts(e){return dt(e,"indexState")}function Ss(e){B(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;ye(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new pe(t.readTime,t.documentKey,n)}const xs={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Ds{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Ds(e,Ds.DEFAULT_COLLECTION_PERCENTILE,Ds.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Cs(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.J({range:a},(e,t,n)=>(o++,n.delete()));s.push(u.next(()=>{B(1===o)}));const c=[];for(const e of n.mutations){const r=Ge(t,e.key.path,n.batchId);s.push(i.delete(r)),c.push(e.key)}return be.waitFor(s).next(()=>c)}function As(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw U();t=e.noDocument}return JSON.stringify(t).length}Ds.DEFAULT_COLLECTION_PERCENTILE=10,Ds.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ds.DEFAULT=new Ds(41943040,Ds.DEFAULT_COLLECTION_PERCENTILE,Ds.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ds.DISABLED=new Ds(-1,0,0);class Ns{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Cn={}}static lt(e,t,n,r){B(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new Ns(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Rs(e).J({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=Ms(h),m=Rs(h);return m.add({}).next(e=>{B("number"==typeof e);const t=new Br(e,l,d,f),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>xi(i.ct,e)),u=a.mutations.map(e=>xi(i.ct,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var i,s,a,o,u;let c=new wt((e,t)=>Z(e.canonicalString(),t.canonicalString()));for(const h of f){const l=Ge(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,ze))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.Cn[e]=t.keys()}),be.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Rs(e).get(t).next(e=>e?(B(e.userId===this.userId),ji(this.serializer,e)):null)}vn(e,n){return this.Cn[n]?be.resolve(this.Cn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Cn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return Rs(e).J({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(B(t.batchId>=r),i=ji(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Rs(e).J({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Rs(e).U("userMutationsIndex",t).next(e=>e.map(e=>ji(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=je(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return Ms(a).J({range:t},(e,t,n)=>{var[r,i,s]=e,i=Be(i);if(r===this.userId&&o.path.isEqual(i))return Rs(a).get(s).next(e=>{if(!e)throw U();B(e.userId===this.userId),u.push(ji(this.serializer,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new wt(Z);const n=[];return e.forEach(a=>{var e=je(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=Ms(t).J({range:e},(e,t,n)=>{var[r,i,s]=e,i=Be(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),be.waitFor(n).next(()=>this.Fn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=je(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new wt(Z);return Ms(e).J({range:r},(e,t,n)=>{var[r,i,s]=e,i=Be(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(u=u.add(s)):n.done()}).next(()=>this.Fn(e,u))}Fn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Rs(t).get(e).next(e=>{if(null===e)throw U();B(e.userId===this.userId),n.push(ji(this.serializer,e))}))}),be.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return Cs(t._e,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.Mn(n.batchId)}),be.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}Mn(e){delete this.Cn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return be.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return Ms(n).J({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Be(e[1]);r.push(t)}else n.done()}).next(()=>{B(0===r.length)})})}containsKey(e,t){return ks(e,this.userId,t)}xn(e){return Ls(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function ks(e,s,t){const n=je(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return Ms(e).J({range:r,H:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function Rs(e){return dt(e,"mutations")}function Ms(e){return dt(e,"documentMutations")}function Ls(e){return dt(e,"mutationQueues")}class Os{constructor(e){this.On=e}next(){return this.On+=2,this.On}static Nn(){return new Os(0)}static Ln(){return new Os(-1)}}class Fs{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.Bn(n).next(e=>{const t=new Os(e.highestTargetId);return e.highestTargetId=t.next(),this.kn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Bn(e).next(e=>re.fromTimestamp(new ne(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Bn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Bn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.kn(t,e)))}addTargetData(t,n){return this.qn(t,n).next(()=>this.Bn(t).next(e=>(e.targetCount+=1,this.Qn(n,e),this.kn(t,e))))}updateTargetData(e,t){return this.qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Ps(t).delete(e.targetId)).next(()=>this.Bn(t)).next(e=>(B(0<e.targetCount),--e.targetCount,this.kn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return Ps(r).J((e,t)=>{var n=Gi(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>be.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Ps(e).J((e,t)=>{var n=Gi(t);r(n)})}Bn(e){return Vs(e).get("targetGlobalKey").next(e=>(B(null!==e),e))}kn(e,t){return Vs(e).put("targetGlobalKey",t)}qn(e,t){return Ps(e).put(zi(this.serializer,t))}Qn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Bn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=Ln(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return Ps(e).J({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Gi(t);On(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=Us(n);return e.forEach(e=>{var t=Ve(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),be.waitFor(i)}removeMatchingKeys(n,e,r){const i=Us(n);return be.forEach(e,e=>{var t=Ve(e.path);return be.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=Us(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=Us(e);let i=cr();return r.J({range:n,H:!0},(e,t,n)=>{var r=Be(e[1]),r=new ue(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Ve(t.path),n=IDBKeyRange.bound([n],[te(n)],!1,!0);let r=0;return Us(e).J({index:"documentTargetsIndex",H:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}ot(e,t){return Ps(e).get(t).next(e=>e?Gi(e):null)}}function Ps(e){return dt(e,"targets")}function Vs(e){return dt(e,"targetGlobal")}function Us(e){return dt(e,"targetDocuments")}function Bs([e,t],[n,r]){var i=Z(e,n);return 0===i?Z(t,r):i}class qs{constructor(e){this.Kn=e,this.buffer=new wt(Bs),this.$n=0}Un(){return++this.$n}Wn(e){var t=[e,this.Un()];if(this.buffer.size<this.Kn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Bs(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class js{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.zn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}zn(e){O("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){De(e)?O("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await _e(e)}await this.zn(3e5)})}}class Gs{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.Hn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return be.resolve(Le.oe);const n=new qs(t);return this.jn.forEachTarget(e,e=>n.Wn(e.sequenceNumber)).next(()=>this.jn.Jn(e,e=>n.Wn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(O("LruGarbageCollector","Garbage collection skipped; disabled"),be.resolve(xs)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(O("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),xs):this.Yn(t,n))}getCacheSize(e){return this.jn.getCacheSize(e)}Yn(t,n){let r,i,s,a,o,u,c;const h=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(O("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),L()<=l.DEBUG&&O("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),be.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class zs{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Gs(e,t))}Hn(e){const n=this.Zn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Zn(e){let t=0;return this.Jn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Jn(e,n){return this.Xn(e,(e,t)=>n(t))}addReference(e,t,n){return Ks(e,n)}removeReference(e,t,n){return Ks(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Ks(e,t)}er(t,n){let r=!1;return Ls(t).Y(e=>ks(t,e,n).next(e=>(e&&(r=!0),be.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Xn(n,(t,e)=>{if(e<=r){const r=this.er(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,re.min()),Us(n).delete(function(e){return[0,Ve(e.path)]}(t))))});s.push(r)}}).next(()=>be.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Ks(e,t)}Xn(e,r){const t=Us(e);let i,s=Le.oe;return t.J({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==Le.oe&&r(new ue(Be(i)),s),s=n,i=t):s=Le.oe}).next(()=>{s!==Le.oe&&r(new ue(Be(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Ks(e,t){return Us(e).put((e=e.currentSequenceNumber,{targetId:0,path:Ve(t.path),sequenceNumber:e}))}class $s{constructor(){this.changes=new tr(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Zt.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?be.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Qs{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Js(e).put(n)}removeEntry(e,t,n){return Js(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Ui(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.tr(t,e)))}getEntry(e,n){let r=Zt.newInvalidDocument(n);return Js(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(Xs(n))},(e,t)=>{r=this.nr(n,t)}).next(()=>r)}rr(e,n){let r={size:0,document:Zt.newInvalidDocument(n)};return Js(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(Xs(n))},(e,t)=>{r={document:this.nr(n,t),size:As(t)}}).next(()=>r)}getEntries(e,t){let r=nr;return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n)}).next(()=>r)}sr(e,t){let r=nr,i=new pt(ue.comparator);return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n),i=i.insert(e,As(t))}).next(()=>({documents:r,_r:i}))}ir(e,t,i){if(t.isEmpty())return be.resolve();let n=new wt(ea);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(Xs(n.first()),Xs(n.last())),s=n.getIterator();let a=s.getNext();return Js(e).J({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ue.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&ea(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.$(Xs(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,r,i){const s=n.path,a=[s.popLast().toArray(),s.lastSegment(),Ui(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Js(e).U(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let t=nr;for(const i of e){const e=this.nr(ue.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Xn(n,e)||r.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=nr;var r=Zs(t,n),a=Zs(t,pe.max());return Js(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.nr(ue.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new Ws(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return Ys(e).get("remoteDocumentGlobalKey").next(e=>(B(!!e),e))}tr(e,t){return Ys(e).put("remoteDocumentGlobalKey",t)}nr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Si(e.ct,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ue.fromSegments(t.noDocument.path),i=qi(t.noDocument.readTime);n=Zt.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return U();{const e=ue.fromSegments(t.unknownDocument.path),s=qi(t.unknownDocument.version);n=Zt.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new ne(t[0],t[1]),re.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(re.min()))return e}return Zt.newInvalidDocument(e)}}function Hs(e){return new Qs(e)}class Ws extends $s{constructor(e,t){super(),this.ar=e,this.trackRemovals=t,this.ur=new tr(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,u=new wt((e,t)=>Z(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.ur.get(e);if(a.push(this.ar.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Vi(this.ar.serializer,t);u=u.add(e.path.popLast());var i=As(r);o+=i-n.size,a.push(this.ar.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=Vi(this.ar.serializer,t.convertToNoDocument(re.min()));a.push(this.ar.addEntry(s,e,o))}}),u.forEach(e=>{a.push(this.ar.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ar.updateMetadata(s,o)),be.waitFor(a)}getFromCache(e,t){return this.ar.rr(e,t).next(e=>(this.ur.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ar.sr(e,t).next(({documents:n,_r:e})=>(e.forEach((e,t)=>{this.ur.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function Ys(e){return dt(e,"remoteDocumentGlobal")}function Js(e){return dt(e,"remoteDocumentsV14")}function Xs(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Zs(e,t){const n=t.documentKey.path.toArray();return[e,Ui(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function ea(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Z(n[s],r[s]),i)return i;return i=Z(n.length,r.length),i||(i=Z(n[n.length-2],r[r.length-2]),i||Z(n[n.length-1],r[r.length-1]))}class ta{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class na{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&kr(r.mutation,e,It.empty(),ne.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,cr()).next(()=>e))}getLocalViewOfDocuments(e,t,n=cr()){const r=ar();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=ir();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=ar();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,cr()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=nr;const a=ar(),o=ar();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof Lr)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),kr(n.mutation,t,n.mutation.getFieldMask(),ne.now())):a.set(t.key,It.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new ta(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=ar();let u=new pt((e,t)=>e-t),c=cr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||It.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||cr()).add(e),u=u.insert(r.batchId,t))})}).next(()=>{const e=[],t=u.getReverseIterator();for(;t.hasNext();){const u=t.getNext(),n=u.key,r=u.value,i=ar();r.forEach(e=>{var t;c.has(e)||(null!==(t=Ar(a.get(e),o.get(e)))&&i.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return be.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n,r){return i=t,ue.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):zn(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):be.resolve(ar());let r=-1,i=n;return e.next(e=>be.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?be.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,cr())).next(e=>({batchId:r,changes:sr(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ue(t)).next(e=>{let t=ir();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s,a){const o=i.collectionGroup;let u=ir();return this.indexManager.getCollectionParents(r,o).next(e=>be.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new Bn(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s,a).next(e=>{e.forEach((e,t)=>{u=u.insert(e,t)})})}).next(()=>u))}getDocumentsMatchingCollectionQuery(t,s,n,r){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a,r))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Zt.newInvalidDocument(n)))});let i=ir();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&kr(n.mutation,t,It.empty(),ne.now()),Xn(s,t)&&(i=i.insert(e,t))}),i})}}class ra{constructor(e){this.serializer=e,this.cr=new Map,this.lr=new Map}getBundleMetadata(e,t){return be.resolve(this.cr.get(t))}saveBundleMetadata(e,t){return this.cr.set(t.id,{id:t.id,version:t.version,createTime:gi(t.createTime)}),be.resolve()}getNamedQuery(e,t){return be.resolve(this.lr.get(t))}saveNamedQuery(e,t){return this.lr.set(t.name,{name:(t=t).name,query:Ki(t.bundledQuery),readTime:gi(t.readTime)}),be.resolve()}}class ia{constructor(){this.overlays=new pt(ue.comparator),this.hr=new Map}getOverlay(e,t){return be.resolve(this.overlays.get(t))}getOverlays(e,t){const n=ar();return be.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.ht(n,r,t)}),be.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.hr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.hr.delete(n)),be.resolve()}getOverlaysForCollection(e,t,n){const r=ar(),i=t.length+1,s=new ue(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return be.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new pt((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=ar(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=ar(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return be.resolve(a)}ht(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.hr.get(r.largestBatchId).delete(n.key);this.hr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new jr(t,n));let i=this.hr.get(t);void 0===i&&(i=cr(),this.hr.set(t,i)),this.hr.set(t,i.add(n.key))}}class sa{constructor(){this.Pr=new wt(aa.Ir),this.Tr=new wt(aa.Er)}isEmpty(){return this.Pr.isEmpty()}addReference(e,t){var n=new aa(e,t);this.Pr=this.Pr.add(n),this.Tr=this.Tr.add(n)}dr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ar(new aa(e,t))}Rr(e,t){e.forEach(e=>this.removeReference(e,t))}Vr(e){const t=new ue(new se([])),n=new aa(t,e),r=new aa(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Ar(e),i.push(e.key)}),i}mr(){this.Pr.forEach(e=>this.Ar(e))}Ar(e){this.Pr=this.Pr.delete(e),this.Tr=this.Tr.delete(e)}gr(e){var t=new ue(new se([])),n=new aa(t,e),t=new aa(t,e+1);let r=cr();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new aa(e,0),t=this.Pr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class aa{constructor(e,t){this.key=e,this.pr=t}static Ir(e,t){return ue.comparator(e.key,t.key)||Z(e.pr,t.pr)}static Er(e,t){return Z(e.pr,t.pr)||ue.comparator(e.key,t.key)}}class oa{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.yr=1,this.wr=new wt(aa.Ir)}checkEmpty(e){return be.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.yr;this.yr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new Br(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.wr=this.wr.add(new aa(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return be.resolve(s)}lookupMutationBatch(e,t){return be.resolve(this.Sr(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.br(t+1),n=n<0?0:n;return be.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return be.resolve(0===this.mutationQueue.length?-1:this.yr-1)}getAllMutationBatches(e){return be.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new aa(t,0),r=new aa(t,Number.POSITIVE_INFINITY),i=[];return this.wr.forEachInRange([n,r],e=>{var t=this.Sr(e.pr);i.push(t)}),be.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new wt(Z);return t.forEach(e=>{var t=new aa(e,0),n=new aa(e,Number.POSITIVE_INFINITY);this.wr.forEachInRange([t,n],e=>{r=r.add(e.pr)})}),be.resolve(this.Dr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ue.isDocumentKey(i)||(i=i.child(""));var s=new aa(new ue(i),0);let a=new wt(Z);return this.wr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.pr)),!0)},s),be.resolve(this.Dr(a))}Dr(e){const n=[];return e.forEach(e=>{var t=this.Sr(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){B(0===this.Cr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.wr;return be.forEach(r.mutations,e=>{var t=new aa(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.wr=i})}Mn(e){}containsKey(e,t){var n=new aa(t,0),n=this.wr.firstAfterOrEqual(n);return be.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,be.resolve()}Cr(e,t){return this.br(e)}br(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Sr(e){var t=this.br(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class ua{constructor(e){this.vr=e,this.docs=new pt(ue.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.vr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return be.resolve(n?n.document.mutableCopy():Zt.newInvalidDocument(t))}getEntries(e,t){let n=nr;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Zt.newInvalidDocument(e))}),be.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=nr;const s=t.path,a=new ue(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||ye(me(a),n)<=0||(r.has(a.key)||Xn(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return be.resolve(i)}getAllFromCollectionGroup(e,t,n,r){U()}Fr(e,t){return be.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new ca(this)}getSize(e){return be.resolve(this.size)}}class ca extends $s{constructor(e){super(),this.ar=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ar.addEntry(n,t)):this.ar.removeEntry(e)}),be.waitFor(r)}getFromCache(e,t){return this.ar.getEntry(e,t)}getAllFromCache(e,t){return this.ar.getEntries(e,t)}}class ha{constructor(e){this.persistence=e,this.Mr=new tr(e=>Ln(e),On),this.lastRemoteSnapshotVersion=re.min(),this.highestTargetId=0,this.Or=0,this.Nr=new sa,this.targetCount=0,this.Lr=Os.Nn()}forEachTarget(e,n){return this.Mr.forEach((e,t)=>n(t)),be.resolve()}getLastRemoteSnapshotVersion(e){return be.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return be.resolve(this.Or)}allocateTargetId(e){return this.highestTargetId=this.Lr.next(),be.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Or&&(this.Or=t),be.resolve()}qn(e){this.Mr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Lr=new Os(t),this.highestTargetId=t),e.sequenceNumber>this.Or&&(this.Or=e.sequenceNumber)}addTargetData(e,t){return this.qn(t),this.targetCount+=1,be.resolve()}updateTargetData(e,t){return this.qn(t),be.resolve()}removeTargetData(e,t){return this.Mr.delete(t.target),this.Nr.Vr(t.targetId),--this.targetCount,be.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Mr.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Mr.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),be.waitFor(a).next(()=>s)}getTargetCount(e){return be.resolve(this.targetCount)}getTargetData(e,t){var n=this.Mr.get(t)||null;return be.resolve(n)}addMatchingKeys(e,t,n){return this.Nr.dr(t,n),be.resolve()}removeMatchingKeys(t,e,n){this.Nr.Rr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),be.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Nr.Vr(t),be.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Nr.gr(t);return be.resolve(n)}containsKey(e,t){return be.resolve(this.Nr.containsKey(t))}}class la{constructor(e,t){this.Br={},this.overlays={},this.kr=new Le(0),this.qr=!1,this.qr=!0,this.referenceDelegate=e(this),this.Qr=new ha(this),this.indexManager=new ys,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Kr(e),new ua(e)),this.serializer=new Pi(t),this.$r=new ra(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.qr=!1,Promise.resolve()}get started(){return this.qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new ia,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Br[e.toKey()];return n||(n=new oa(t,this.referenceDelegate),this.Br[e.toKey()]=n),n}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.$r}runTransaction(e,t,n){O("MemoryPersistence","Starting transaction:",e);const r=new da(this.kr.next());return this.referenceDelegate.Ur(),n(r).next(e=>this.referenceDelegate.Wr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gr(t,n){return be.or(Object.values(this.Br).map(e=>()=>e.containsKey(t,n)))}}class da extends we{constructor(e){super(),this.currentSequenceNumber=e}}class fa{constructor(e){this.persistence=e,this.zr=new sa,this.jr=null}static Hr(e){return new fa(e)}get Jr(){if(this.jr)return this.jr;throw U()}addReference(e,t,n){return this.zr.addReference(n,t),this.Jr.delete(n.toString()),be.resolve()}removeReference(e,t,n){return this.zr.removeReference(n,t),this.Jr.add(n.toString()),be.resolve()}markPotentiallyOrphaned(e,t){return this.Jr.add(t.toString()),be.resolve()}removeTarget(e,t){this.zr.Vr(t.targetId).forEach(e=>this.Jr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Jr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ur(){this.jr=new Set}Wr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return be.forEach(this.Jr,e=>{const t=ue.fromPath(e);return this.Yr(n,t).next(e=>{e||r.removeEntry(t,re.min())})}).next(()=>(this.jr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Yr(e,t).next(e=>{e?this.Jr.delete(t.toString()):this.Jr.add(t.toString())})}Kr(e){return 0}Yr(e,t){return be.or([()=>be.resolve(this.zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gr(e,t)])}}class ga{constructor(e){this.serializer=e}O(t,e,n,r){const i=new Ie("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",qe,{unique:!0}),s.createObjectStore("documentMutations"),ma(t),t.createObjectStore("remoteDocuments"));let a=be.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),ma(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:re.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").U().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",qe,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return be.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Xr(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ei(i)))),n<7&&7<=r&&(a=a.next(()=>this.ti(i))),n<8&&8<=r&&(a=a.next(()=>this.ni(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.ri(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:nt});t.createIndex("collectionPathOverlayIndex",rt,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",it,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:Ke});t.createIndex("documentKeyIndex",$e),t.createIndex("collectionGroupIndex",Qe)}(t)).next(()=>this.ii(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.si(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Xe}).createIndex("sequenceNumberIndex",Ze,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:et}).createIndex("documentKeyIndex",tt,{unique:!1})}(t))),n<16&&16<=r&&(a=a.next(()=>{e.objectStore("indexState").clear()}).next(()=>{e.objectStore("indexEntries").clear()})),a}ei(t){let n=0;return t.store("remoteDocuments").J((e,t)=>{n+=As(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Xr(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.U().next(e=>be.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.U("userMutationsIndex",e).next(e=>be.forEach(e,e=>{B(e.userId===n.userId);var t=ji(this.serializer,e);return Cs(r,n.userId,t).next(()=>{})}))}))}ti(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.J((e,t)=>{const n=new se(e),r=[0,Ve(n)];s.push(a.get(r).next(e=>e?be.resolve():(e=>a.put({targetId:0,path:Ve(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>be.waitFor(s))})}ni(e,t){e.createObjectStore("collectionParents",{keyPath:Je});const n=t.store("collectionParents"),r=new vs,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Ve(r)})}};return t.store("remoteDocuments").J({H:!0},(e,t)=>{const n=new se(e);return i(n.popLast())}).next(()=>t.store("documentMutations").J({H:!0},([,e],t)=>{const n=Be(e);return i(n.popLast())}))}ri(e){const r=e.store("targets");return r.J((e,t)=>{var n=Gi(t),n=zi(this.serializer,n);return r.put(n)})}ii(e,a){const t=a.store("remoteDocuments"),o=[];return t.J((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ue(se.fromString(s.document.name).popFirst(5)):s.noDocument?ue.fromSegments(s.noDocument.path):s.unknownDocument?ue.fromSegments(s.unknownDocument.path):U()).path.toArray(),i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};var s;o.push(n.put(i))}).next(()=>be.waitFor(o))}si(e,s){const t=s.store("mutations"),a=Hs(this.serializer),o=new la(fa.Hr,this.serializer.ct);return t.U().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:cr();ji(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),be.forEach(r,(e,t)=>{var n=new k(t),r=Xi.lt(this.serializer,n),i=o.getIndexManager(n),n=Ns.lt(n,this.serializer,i,o.referenceDelegate);return new na(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new lt(s,Le.oe),e).next()})})}}function ma(e){e.createObjectStore("targetDocuments",{keyPath:We}).createIndex("documentTargetsIndex",Ye,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",He,{unique:!0}),e.createObjectStore("targetGlobal")}const pa="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class ya{constructor(e,t,n,r,i,s,a,o,u,c,h=16){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.oi=i,this.window=s,this.document=a,this._i=u,this.ai=c,this.ui=h,this.kr=null,this.qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.li=null,this.hi=null,this.Pi=Number.NEGATIVE_INFINITY,this.Ii=e=>Promise.resolve(),!ya.D())throw new j(q.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new zs(this,r),this.Ti=t+"main",this.serializer=new Pi(o),this.Ei=new Ee(this.Ti,this.ui,new ga(this.serializer)),this.Qr=new Fs(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Hs(this.serializer),this.$r=new Wi,this.window&&this.window.localStorage?this.di=this.window.localStorage:(this.di=null,!1===c&&F("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Ai().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new j(q.FAILED_PRECONDITION,pa);return this.Ri(),this.Vi(),this.mi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Qr.getHighestSequenceNumber(e))}).then(e=>{this.kr=new Le(e,this._i)}).then(()=>{this.qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}fi(t){return this.Ii=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.oi.enqueueAndForget(async()=>{this.started&&await this.Ai()}))}Ai(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>wa(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.gi(t).next(e=>{e||(this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)))})}).next(()=>this.pi(t)).next(e=>this.isPrimary&&!e?this.yi(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(De(e))return O("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return O("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.oi.enqueueRetryable(()=>this.Ii(e)),this.isPrimary=e})}gi(e){return va(e).get("owner").next(e=>be.resolve(this.Si(e)))}bi(e){return wa(e).delete(this.clientId)}async Di(){if(this.isPrimary&&!this.Ci(this.Pi,18e5)){this.Pi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=dt(e,"clientMetadata");return r.U().next(e=>{const t=this.vi(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return be.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.di)for(const t of e)this.di.removeItem(this.Fi(t.clientId))}}mi(){this.hi=this.oi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ai().then(()=>this.Di()).then(()=>this.mi()))}Si(e){return!!e&&e.ownerId===this.clientId}pi(t){return this.ai?be.resolve(!0):va(t).get("owner").next(e=>{if(null!==e&&this.Ci(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)){if(this.Si(e)&&this.networkEnabled)return!0;if(!this.Si(e)){if(!e.allowTabSynchronization)throw new j(q.FAILED_PRECONDITION,pa);return!1}}return!(!this.networkEnabled||!this.inForeground)||wa(t).U().next(e=>void 0===this.vi(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&O("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.qr=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Oi(),this.Ni(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new lt(e,Le.oe);return this.yi(t).next(()=>this.bi(t))}),this.Ei.close(),this.Li()}vi(e,t){return e.filter(e=>this.Ci(e.updateTimeMs,t)&&!this.Mi(e.clientId))}Bi(){return this.runTransaction("getActiveClients","readonly",e=>wa(e).U().next(e=>this.vi(e,18e5).map(e=>e.clientId)))}get started(){return this.qr}getMutationQueue(e,t){return Ns.lt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new _s(e,this.serializer.ct.databaseId)}getDocumentOverlayCache(e){return Xi.lt(this.serializer,e)}getBundleCache(){return this.$r}runTransaction(t,n,r){O("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=16===(e=this.ui)?ht:15===e?ct:14===e?ut:13===e?ot:12===e?at:11===e?st:void U();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new lt(e,this.kr?this.kr.next():Le.oe),"readwrite-primary"===n?this.gi(a).next(e=>!!e||this.pi(a)).next(e=>{if(!e)throw F(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)),new j(q.FAILED_PRECONDITION,ve);return r(a)}).next(e=>this.wi(a).next(()=>e)):this.ki(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ki(e){return va(e).get("owner").next(e=>{if(null!==e&&this.Ci(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)&&!this.Si(e)&&!(this.ai||this.allowTabSynchronization&&e.allowTabSynchronization))throw new j(q.FAILED_PRECONDITION,pa)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return va(e).put("owner",t)}static D(){return Ee.D()}yi(e){const t=va(e);return t.get("owner").next(e=>this.Si(e)?(O("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):be.resolve())}Ci(e,t){var n=Date.now();return!(e<n-t||n<e&&(F(`Detected an update time that is in the future: ${e} > ${n}`),1))}Ri(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.li=()=>{this.oi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ai()))},this.document.addEventListener("visibilitychange",this.li),this.inForeground="visible"===this.document.visibilityState)}Oi(){this.li&&(this.document.removeEventListener("visibilitychange",this.li),this.li=null)}Vi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();var e=/(?:Version|Mobile)\/1[456]/;h()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.oi.enterRestrictedMode(!0),this.oi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}Ni(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Mi(e){var t;try{var n=null!==(null===(t=this.di)||void 0===t?void 0:t.getItem(this.Fi(e)));return O("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return F("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this.di)try{this.di.setItem(this.Fi(this.clientId),String(Date.now()))}catch(e){F("Failed to set zombie client id.",e)}}Li(){if(this.di)try{this.di.removeItem(this.Fi(this.clientId))}catch(e){}}Fi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function va(e){return dt(e,"owner")}function wa(e){return dt(e,"clientMetadata")}function _a(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class ba{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.qi=n,this.Qi=r}static Ki(e,t){let n=cr(),r=cr();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new ba(e,t.fromCache,n,r)}}class Ia{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Ea{constructor(){this.$i=!1,this.Ui=!1,this.Wi=100,this.Gi=h()?8:0<Te(u())?6:4}initialize(e,t){this.zi=e,this.indexManager=t,this.$i=!0}getDocumentsMatchingQuery(n,r,e,t){const i={result:null};return this.ji(n,r).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.Hi(n,r,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){const t=new Ia;return this.Ji(n,r,t).next(e=>{if(i.result=e,this.Ui)return this.Yi(n,r,t,e.size)})}}).next(()=>i.result)}Yi(e,t,n,r){return n.documentReadCount<this.Wi?(L()<=l.DEBUG&&O("QueryEngine","SDK will not create cache indexes for query:",Jn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Wi,"documents"),be.resolve()):(L()<=l.DEBUG&&O("QueryEngine","Query:",Jn(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Gi*r?(L()<=l.DEBUG&&O("QueryEngine","The SDK decides to create cache indexes for query:",Jn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,$n(t))):be.resolve())}ji(i,s){if(Gn(s))return be.resolve(null);let t=$n(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Hn(s,null,"F"),t=$n(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=cr(...e);return this.zi.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Zi(s,n);return this.Xi(s,t,r,e.readTime)?this.ji(i,Hn(s,null,"F")):this.es(i,t,s,e)}))})))}Hi(n,r,i,s){return Gn(r)||s.isEqual(re.min())?be.resolve(null):this.zi.getDocuments(n,i).next(e=>{var t=this.Zi(r,e);return this.Xi(r,t,i,s)?be.resolve(null):(L()<=l.DEBUG&&O("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Jn(r)),this.es(n,t,r,ge(s,-1)).next(e=>e))})}Zi(n,e){let r=new wt(er(n));return e.forEach((e,t)=>{Xn(n,t)&&(r=r.add(t))}),r}Xi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Ji(e,t,n){return L()<=l.DEBUG&&O("QueryEngine","Using full collection scan to execute query:",Jn(t)),this.zi.getDocumentsMatchingQuery(e,t,pe.min(),n)}es(e,n,t,r){return this.zi.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class Ta{constructor(e,t,n,r){this.persistence=e,this.ts=t,this.serializer=r,this.ns=new pt(Z),this.rs=new tr(e=>Ln(e),On),this.ss=new Map,this.os=e.getRemoteDocumentCache(),this.Qr=e.getTargetCache(),this.$r=e.getBundleCache(),this._s(n)}_s(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new na(this.os,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.os.setIndexManager(this.indexManager),this.ts.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ns))}}function Sa(e,t,n,r){return new Ta(e,t,n,r)}async function xa(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a._s(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=cr();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({us:e,removedBatchIds:t,addedBatchIds:n}))})})}function Da(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Qr.getLastRemoteSnapshotVersion(e))}function Ca(e,c){const h=e,l=c.snapshotVersion;let d=h.ns;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h.os.newChangeBuffer({trackRemovals:!0});d=h.ns;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Qr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Qr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==c.targetMismatches.get(n)?e=e.withResumeToken(Tt.EMPTY_BYTE_STRING,re.min()).withLastLimboFreeSnapshotVersion(re.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(h.Qr.updateTargetData(o,e))}});let t=nr,n=cr();if(c.documentUpdates.forEach(e=>{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(Aa(o,e,c.documentUpdates).next(e=>{t=e.cs,n=e.ls})),!l.isEqual(re.min())){const c=h.Qr.getLastRemoteSnapshotVersion(o).next(e=>h.Qr.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return be.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.ns=d,e))}function Aa(e,s,t){let n=cr(),a=cr();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=nr;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(re.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):O("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{cs:i,ls:a}})}function Na(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Qr.getTargetData(t,r).next(e=>e?(n=e,be.resolve(n)):i.Qr.allocateTargetId(t).next(e=>(n=new Fi(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Qr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.ns.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.ns=i.ns.insert(e.targetId,e),i.rs.set(r,e.targetId)),e})}async function ka(e,t,n){const r=e,i=r.ns.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!De(e))throw e;O("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ns=r.ns.remove(t),r.rs.delete(i.target)}function Ra(e,n,r){const i=e;let s=re.min(),a=cr();return i.persistence.runTransaction("Execute query","readwrite",t=>function(e,t,n){const r=e,i=r.rs.get(n);return void 0!==i?be.resolve(r.ns.get(i)):r.Qr.getTargetData(t,n)}(i,t,$n(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Qr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.ts.getDocumentsMatchingQuery(t,n,r?s:re.min(),r?a:cr())).next(e=>(Oa(i,Zn(n),e),{documents:e,hs:a})))}function Ma(e,t){const n=e,r=n.Qr,i=n.ns.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.ot(e,t).next(e=>e?e.target:null))}function La(e,t){const n=e,r=n.ss.get(t)||re.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.os.getAllFromCollectionGroup(e,t,ge(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Oa(n,t,e),e))}function Oa(e,t,n){let r=e.ss.get(t)||re.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.ss.set(t,r)}function Fa(e,t){return`firestore_clients_${e}_${t}`}function Pa(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Va(e,t){return`firestore_targets_${e}_${t}`}class Ua{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Es(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new j(r.error.code,r.error.message))),s?new Ua(e,t,r.state,i):(F("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}ds(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Ba{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Es(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new j(n.error.code,n.error.message))),i?new Ba(e,n.state,r):(F("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}ds(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class qa{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Es(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=hr;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Pe(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new qa(e,i):(F("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class ja{constructor(e,t){this.clientId=e,this.onlineState=t}static Es(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new ja(t.clientId,t.onlineState):(F("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Ga{constructor(){this.activeTargetIds=hr}As(e){this.activeTargetIds=this.activeTargetIds.add(e)}Rs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}ds(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class za{constructor(e,t,n,r,i){this.window=e,this.oi=t,this.persistenceKey=n,this.Vs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.fs=this.gs.bind(this),this.ps=new pt(Z),this.started=!1,this.ys=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.ws=Fa(this.persistenceKey,this.Vs),this.Ss=`firestore_sequence_number_${this.persistenceKey}`,this.ps=this.ps.insert(this.Vs,new Ga),this.bs=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Ds=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Cs=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.vs=`firestore_online_state_${this.persistenceKey}`,this.Fs=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.fs)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Bi();for(const n of e)if(n!==this.Vs){const e=this.getItem(Fa(this.persistenceKey,n));var t;!e||(t=qa.Es(n,e))&&(this.ps=this.ps.insert(t.clientId,t))}this.Ms();const n=this.storage.getItem(this.vs);if(n){const e=this.xs(n);e&&this.Os(e)}for(const e of this.ys)this.gs(e);this.ys=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ss,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ns(this.ps)}isActiveQueryTarget(n){let r=!1;return this.ps.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Ls(e,"pending")}updateMutationState(e,t,n){this.Ls(e,t,n),this.Bs(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Va(this.persistenceKey,e)))||(n=Ba.Es(e,n))&&(t=n.state)),this.ks.As(e),this.Ms(),t}removeLocalQueryTarget(e){this.ks.Rs(e),this.Ms()}isLocalQueryTarget(e){return this.ks.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Va(this.persistenceKey,e))}updateQueryState(e,t,n){this.qs(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Bs(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Qs(e)}notifyBundleLoaded(e){this.Ks(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.fs),this.removeItem(this.ws),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return O("SharedClientState","READ",e,t),t}setItem(e,t){O("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){O("SharedClientState","REMOVE",e),this.storage.removeItem(e)}gs(e){const i=e;i.storageArea===this.storage&&(O("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.ws?this.oi.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.bs.test(i.key)){if(null==i.newValue){var e=this.$s(i.key);return this.Us(e,null)}e=this.Ws(i.key,i.newValue);if(e)return this.Us(e.clientId,e)}else if(this.Ds.test(i.key)){if(null!==i.newValue){var t=this.Gs(i.key,i.newValue);if(t)return this.zs(t)}}else if(this.Cs.test(i.key)){if(null!==i.newValue){t=this.js(i.key,i.newValue);if(t)return this.Hs(t)}}else if(i.key===this.vs){if(null!==i.newValue){var n=this.xs(i.newValue);if(n)return this.Os(n)}}else if(i.key===this.Ss){n=function(e){let t=Le.oe;if(null!=e)try{var n=JSON.parse(e);B("number"==typeof n),t=n}catch(e){F("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==Le.oe&&this.sequenceNumberHandler(n)}else if(i.key===this.Fs){const r=this.Js(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Ys(e)))}}else this.ys.push(i)}):F("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get ks(){return this.ps.get(this.Vs)}Ms(){this.setItem(this.ws,this.ks.ds())}Ls(e,t,n){const r=new Ua(this.currentUser,e,t,n),i=Pa(this.persistenceKey,this.currentUser,e);this.setItem(i,r.ds())}Bs(e){var t=Pa(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Qs(e){var t={clientId:this.Vs,onlineState:e};this.storage.setItem(this.vs,JSON.stringify(t))}qs(e,t,n){const r=Va(this.persistenceKey,e),i=new Ba(e,t,n);this.setItem(r,i.ds())}Ks(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Fs,t)}$s(e){var t=this.bs.exec(e);return t?t[1]:null}Ws(e,t){var n=this.$s(e);return qa.Es(n,t)}Gs(e,t){var n=this.Ds.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Ua.Es(new k(n),r,t)}js(e,t){var n=this.Cs.exec(e),n=Number(n[1]);return Ba.Es(n,t)}xs(e){return ja.Es(e)}Js(e){return JSON.parse(e)}async zs(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Zs(e.batchId,e.state,e.error);O("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Hs(e){return this.syncEngine.Xs(e.targetId,e.state,e.error)}Us(e,t){const n=t?this.ps.insert(e,t):this.ps.remove(e),r=this.Ns(this.ps),i=this.Ns(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.eo(s,a).then(()=>{this.ps=n})}Os(e){this.ps.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ns(e){let n=hr;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Ka{constructor(){this.no=new Ga,this.ro={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.no.As(e),this.ro[e]||"not-current"}updateQueryState(e,t,n){this.ro[e]=t}removeLocalQueryTarget(e){this.no.Rs(e)}isLocalQueryTarget(e){return this.no.activeTargetIds.has(e)}clearQueryState(e){delete this.ro[e]}getAllActiveQueryTargets(){return this.no.activeTargetIds}isActiveQueryTarget(e){return this.no.activeTargetIds.has(e)}start(){return this.no=new Ga,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class $a{io(e){}shutdown(){}}class Qa{constructor(){this.so=()=>this.oo(),this._o=()=>this.ao(),this.uo=[],this.co()}io(e){this.uo.push(e)}shutdown(){window.removeEventListener("online",this.so),window.removeEventListener("offline",this._o)}co(){window.addEventListener("online",this.so),window.addEventListener("offline",this._o)}oo(){O("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.uo)e(0)}ao(){O("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.uo)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Ha=null;function Wa(){return null===Ha?Ha=268435456+Math.round(2147483648*Math.random()):Ha++,"0x"+Ha.toString(16)}const Ya={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Ja{constructor(e){this.lo=e.lo,this.ho=e.ho}Po(e){this.Io=e}To(e){this.Eo=e}Ao(e){this.Ro=e}onMessage(e){this.Vo=e}close(){this.ho()}send(e){this.lo(e)}mo(){this.Io()}fo(){this.Eo()}po(e){this.Ro(e)}yo(e){this.Vo(e)}}const Xa="WebChannelConnection";class Za extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.wo=t+"://"+e.host,this.So=`projects/${n}/databases/${r}`,this.bo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get Do(){return!1}Co(t,e,n,r,i){const s=Wa(),a=this.vo(t,e.toUriEncodedString());O("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.So,"x-goog-request-params":this.bo};return this.Fo(o,r,i),this.Mo(t,a,o,n).then(e=>(O("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw P("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}xo(e,t,n,r,i,s){return this.Co(e,t,n,r,i)}Fo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+R,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}vo(e,t){var n=Ya[e];return`${this.wo}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Mo(u,t,n,r){const c=Wa();return new Promise((s,a)=>{const o=new dn;o.setWithCredentials(!0),o.listenOnce(mn.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case pn.NO_ERROR:var e=o.getResponseJson();O(Xa,`XHR for RPC '${u}' ${c} received:`,JSON.stringify(e)),s(e);break;case pn.TIMEOUT:O(Xa,`RPC '${u}' ${c} timed out`),a(new j(q.DEADLINE_EXCEEDED,"Request time out"));break;case pn.HTTP_ERROR:var t=o.getStatus();if(O(Xa,`RPC '${u}' ${c} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const u=(r=n.status,i=r.toLowerCase().replace(/_/g,"-"),0<=Object.values(q).indexOf(i)?i:q.UNKNOWN);a(new j(u,n.message))}else a(new j(q.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new j(q.UNAVAILABLE,"Connection failed."));break;default:U()}}finally{O(Xa,`RPC '${u}' ${c} completed.`)}var r,i});var e=JSON.stringify(r);O(Xa,`RPC '${u}' ${c} sending request:`,r),o.send(t,"POST",e,n,15)})}Oo(i,e,t){const s=Wa(),n=[this.wo,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=_n(),a=wn(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(o.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(o.xmlHttpFactory=new fn({})),this.Fo(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var c=n.join("");O(Xa,`Creating RPC '${i}' stream ${s}: ${c}`,o);const h=r.createWebChannel(c,o);let l=!1,d=!1;const f=new Ja({lo:e=>{d?O(Xa,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(l||(O(Xa,`Opening RPC '${i}' stream ${s} transport.`),h.open(),l=!0),O(Xa,`RPC '${i}' stream ${s} sending:`,e),h.send(e))},ho:()=>h.close()}),g=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return g(h,gn.EventType.OPEN,()=>{d||(O(Xa,`RPC '${i}' stream ${s} transport opened.`),f.mo())}),g(h,gn.EventType.CLOSE,()=>{d||(d=!0,O(Xa,`RPC '${i}' stream ${s} transport closed`),f.po())}),g(h,gn.EventType.ERROR,e=>{d||(d=!0,P(Xa,`RPC '${i}' stream ${s} transport errored:`,e),f.po(new j(q.UNAVAILABLE,"The operation could not be completed")))}),g(h,gn.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];B(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){O(Xa,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=x[e];if(void 0!==t)return Kr(t)}(n),t=r.message;void 0===e&&(e=q.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,f.po(new j(e,t)),h.close()}else O(Xa,`RPC '${i}' stream ${s} received:`,e),f.yo(e)}}),g(a,vn.STAT_EVENT,e=>{e.stat===yn.PROXY?O(Xa,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===yn.NOPROXY&&O(Xa,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{f.fo()},0),f}}function eo(){return"undefined"!=typeof window?window:null}function to(){return"undefined"!=typeof document?document:null}function no(e){return new hi(e,!0)}class ro{constructor(e,t,n=1e3,r=1.5,i=6e4){this.oi=e,this.timerId=t,this.No=n,this.Lo=r,this.Bo=i,this.ko=0,this.qo=null,this.Qo=Date.now(),this.reset()}reset(){this.ko=0}Ko(){this.ko=this.Bo}$o(e){this.cancel();var t=Math.floor(this.ko+this.Uo()),n=Math.max(0,Date.now()-this.Qo),r=Math.max(0,t-n);0<r&&O("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.ko} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.qo=this.oi.enqueueAfterDelay(this.timerId,r,()=>(this.Qo=Date.now(),e())),this.ko*=this.Lo,this.ko<this.No&&(this.ko=this.No),this.ko>this.Bo&&(this.ko=this.Bo)}Wo(){null!==this.qo&&(this.qo.skipDelay(),this.qo=null)}cancel(){null!==this.qo&&(this.qo.cancel(),this.qo=null)}Uo(){return(Math.random()-.5)*this.ko}}class io{constructor(e,t,n,r,i,s,a,o){this.oi=e,this.Go=n,this.zo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.jo=0,this.Ho=null,this.Jo=null,this.stream=null,this.Yo=new ro(e,t)}Zo(){return 1===this.state||5===this.state||this.Xo()}Xo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.e_()}async stop(){this.Zo()&&await this.close(0)}t_(){this.state=0,this.Yo.reset()}n_(){this.Xo()&&null===this.Ho&&(this.Ho=this.oi.enqueueAfterDelay(this.Go,6e4,()=>this.r_()))}i_(e){this.s_(),this.stream.send(e)}async r_(){if(this.Xo())return this.close(0)}s_(){this.Ho&&(this.Ho.cancel(),this.Ho=null)}o_(){this.Jo&&(this.Jo.cancel(),this.Jo=null)}async close(e,t){this.s_(),this.o_(),this.Yo.cancel(),this.jo++,4!==e?this.Yo.reset():t&&t.code===q.RESOURCE_EXHAUSTED?(F(t.toString()),F("Using maximum backoff delay to prevent overloading the backend."),this.Yo.Ko()):t&&t.code===q.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.__(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ao(t)}__(){}auth(){this.state=1;const e=this.a_(this.jo),n=this.jo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.jo===n&&this.u_(e,t)},t=>{e(()=>{var e=new j(q.UNKNOWN,"Fetching auth token failed: "+t.message);return this.c_(e)})})}u_(e,t){const n=this.a_(this.jo);this.stream=this.l_(e,t),this.stream.Po(()=>{n(()=>this.listener.Po())}),this.stream.To(()=>{n(()=>(this.state=2,this.Jo=this.oi.enqueueAfterDelay(this.zo,1e4,()=>(this.Xo()&&(this.state=3),Promise.resolve())),this.listener.To()))}),this.stream.Ao(e=>{n(()=>this.c_(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}e_(){this.state=5,this.Yo.$o(async()=>{this.state=0,this.start()})}c_(e){return O("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}a_(t){return e=>{this.oi.enqueueAndForget(()=>this.jo===t?e():(O("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class so extends io{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}l_(e,t){return this.connection.Oo("Listen",e,t)}onMessage(e){this.Yo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:U(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.useProto3Json?(B(void 0===f||"string"==typeof f),Tt.fromBase64String(f||"")):(B(void 0===f||f instanceof Buffer||f instanceof Uint8Array),Tt.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?q.UNKNOWN:Kr(f.code),new j(o,f.message||""));n=new ni(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var s=wi(e,u.document.name),o=gi(u.document.updateTime),c=u.document.createTime?gi(u.document.createTime):re.min(),h=new Xt({mapValue:{fields:u.document.fields}}),c=Zt.newFoundDocument(s,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new ei(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=wi(e,h.document),c=h.readTime?gi(h.readTime):re.min(),c=Zt.newNoDocument(u,c),h=h.removedTargetIds||[];n=new ei([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=wi(e,l.document),l=l.removedTargetIds||[];n=new ei([],l,d,null)}else{if(!("filter"in t))return U();{t.filter;const e=t.filter;e.targetId;var{count:l=0,unchangedNames:d}=e,l=new Gr(l,d),d=e.targetId;n=new ti(d,l)}}var o,f;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return re.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?gi(t.readTime):re.min()}(e);return this.listener.h_(t,n)}P_(e){const t={};t.database=Ii(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=Fn(r)?{documents:Ci(e,r)}:{query:Ai(e,r)._t},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=fi(e,t.resumeToken);const r=li(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(re.min())){n.readTime=di(e,t.snapshotVersion.toTimestamp());const r=li(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,n=(this.serializer,e,null==(n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return U()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.i_(t)}I_(e){const t={};t.database=Ii(this.serializer),t.removeTarget=e,this.i_(t)}}class ao extends io{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.T_=!1}get E_(){return this.T_}start(){this.T_=!1,this.lastStreamToken=void 0,super.start()}__(){this.T_&&this.d_([])}l_(e,t){return this.connection.Oo("Write",e,t)}onMessage(e){if(B(!!e.streamToken),this.lastStreamToken=e.streamToken,this.T_){this.Yo.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(B(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?gi(e.updateTime):gi(t);return n.isEqual(re.min())&&(n=gi(t)),new Sr(n,e.transformResults||[])}(e,i))):[]),n=gi(e.commitTime);return this.listener.A_(n,t)}var r,i;return B(!e.writeResults||0===e.writeResults.length),this.T_=!0,this.listener.R_()}V_(){const e={};e.database=Ii(this.serializer),this.i_(e)}d_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>xi(this.serializer,e))};this.i_(t)}}class oo extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.m_=!1}f_(){if(this.m_)throw new j(q.FAILED_PRECONDITION,"The client has already been terminated.")}Co(n,r,i,s){return this.f_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Co(n,pi(r,i),s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===q.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new j(q.UNKNOWN,e.toString())})}xo(n,r,i,s,a){return this.f_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.xo(n,pi(r,i),s,e,t,a)).catch(e=>{throw"FirebaseError"===e.name?(e.code===q.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new j(q.UNKNOWN,e.toString())})}terminate(){this.m_=!0,this.connection.terminate()}}class uo{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.g_=0,this.p_=null,this.y_=!0}w_(){0===this.g_&&(this.S_("Unknown"),this.p_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.p_=null,this.b_("Backend didn't respond within 10 seconds."),this.S_("Offline"),Promise.resolve())))}D_(e){"Online"===this.state?this.S_("Unknown"):(this.g_++,1<=this.g_&&(this.C_(),this.b_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.S_("Offline")))}set(e){this.C_(),this.g_=0,"Online"===e&&(this.y_=!1),this.S_(e)}S_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}b_(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.y_?(F(t),this.y_=!1):O("OnlineStateTracker",t)}C_(){null!==this.p_&&(this.p_.cancel(),this.p_=null)}}class co{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.v_=[],this.F_=new Map,this.M_=new Set,this.x_=[],this.O_=i,this.O_.io(e=>{n.enqueueAndForget(async()=>{wo(this)&&(O("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.M_.add(4),await lo(t),t.N_.set("Unknown"),t.M_.delete(4),await ho(t)}(this))})}),this.N_=new uo(n,r)}}async function ho(e){if(wo(e))for(const t of e.x_)await t(!0)}async function lo(e){for(const t of e.x_)await t(!1)}function fo(e,t){const n=e;n.F_.has(t.targetId)||(n.F_.set(t.targetId,t),vo(n)?yo(n):Ao(n).Xo()&&mo(n,t))}function go(e,t){const n=e,r=Ao(n);n.F_.delete(t),r.Xo()&&po(n,t),0===n.F_.size&&(r.Xo()?r.n_():wo(n)&&n.N_.set("Unknown"))}function mo(e,t){var n;e.L_.xe(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(re.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),Ao(e).P_(t)}function po(e,t){e.L_.xe(t),Ao(e).I_(t)}function yo(t){t.L_=new ii({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),ot:e=>t.F_.get(e)||null,tt:()=>t.datastore.serializer.databaseId}),Ao(t).start(),t.N_.w_()}function vo(e){return wo(e)&&!Ao(e).Zo()&&0<e.F_.size}function wo(e){return 0===e.M_.size}function _o(e){e.L_=void 0}async function bo(e,t,n){if(!De(t))throw t;e.M_.add(1),await lo(e),e.N_.set("Offline"),n=n||(()=>Da(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{O("RemoteStore","Retrying IndexedDB access"),await n(),e.M_.delete(1),await ho(e)})}function Io(t,n){return n().catch(e=>bo(t,e,n))}async function Eo(e){const t=e,n=No(t);let r=0<t.v_.length?t.v_[t.v_.length-1].batchId:-1;for(;wo(i=t)&&i.v_.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.v_.length&&n.n_();break}r=e.batchId,function(e,t){e.v_.push(t);const n=No(e);n.Xo()&&n.E_&&n.d_(t.mutations)}(t,e)}catch(e){await bo(t,e)}var i;To(t)&&So(t)}function To(e){return wo(e)&&!No(e).Zo()&&0<e.v_.length}function So(e){No(e).start()}async function xo(e,t){t&&No(e).E_&&await async function(e,t){if(zr(n=t.code)&&n!==q.ABORTED){const r=e.v_.shift();No(e).t_(),await Io(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await Eo(e)}var n}(e,t),To(e)&&So(e)}async function Do(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),O("RemoteStore","RemoteStore received new credentials");var r=wo(n);n.M_.add(3),await lo(n),r&&n.N_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.M_.delete(3),await ho(n)}async function Co(e,t){const n=e;t?(n.M_.delete(2),await ho(n)):(n.M_.add(2),await lo(n),n.N_.set("Unknown"))}function Ao(t){return t.B_||(t.B_=function(e,t,n){const r=e;return r.f_(),new so(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Po:(async function(e){e.N_.set("Online")}).bind(null,t),To:(async function(n){n.F_.forEach((e,t)=>{mo(n,e)})}).bind(null,t),Ao:(async function(e,t){_o(e),vo(e)?(e.N_.D_(t),yo(e)):e.N_.set("Unknown")}).bind(null,t),h_:(async function(e,t,n){if(e.N_.set("Online"),t instanceof ni&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.F_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.F_.delete(r),e.L_.removeTarget(r))}(e,t)}catch(n){O("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await bo(e,n)}else if(t instanceof ei?e.L_.Ke(t):t instanceof ti?e.L_.He(t):e.L_.We(t),!n.isEqual(re.min()))try{const t=await Da(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.L_.rt(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.F_.get(t);n&&i.F_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.F_.get(e);var r;n&&(i.F_.set(e,n.withResumeToken(Tt.EMPTY_BYTE_STRING,n.snapshotVersion)),po(i,e),r=new Fi(n.target,e,t,n.sequenceNumber),mo(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){O("RemoteStore","Failed to raise snapshot:",t),await bo(e,t)}}).bind(null,t)}),t.x_.push(async e=>{e?(t.B_.t_(),vo(t)?yo(t):t.N_.set("Unknown")):(await t.B_.stop(),_o(t))})),t.B_}function No(t){return t.k_||(t.k_=function(e,t,n){const r=e;return r.f_(),new ao(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Po:()=>Promise.resolve(),To:(async function(e){No(e).V_()}).bind(null,t),Ao:xo.bind(null,t),R_:(async function(e){const t=No(e);for(const n of e.v_)t.d_(n.mutations)}).bind(null,t),A_:(async function(e,t,n){const r=e.v_.shift(),i=qr.from(r,t,n);await Io(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await Eo(e)}).bind(null,t)}),t.x_.push(async e=>{e?(t.k_.t_(),await Eo(t)):(await t.k_.stop(),0<t.v_.length&&(O("RemoteStore",`Stopping write stream with ${t.v_.length} pending writes`),t.v_=[]))})),t.k_}class ko{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new G,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new ko(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new j(q.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Ro(e,t){if(F("AsyncQueue",`${t}: ${e}`),De(e))return new j(q.UNAVAILABLE,`${t}: ${e}`);throw e}class Mo{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ue.comparator(e.key,t.key):(e,t)=>ue.comparator(e.key,t.key),this.keyedMap=ir(),this.sortedSet=new pt(this.comparator)}static emptySet(e){return new Mo(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Mo))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new Mo;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Lo{constructor(){this.q_=new pt(ue.comparator)}track(e){var t=e.doc.key,n=this.q_.get(t);!n||0!==e.type&&3===n.type?this.q_=this.q_.insert(t,e):3===e.type&&1!==n.type?this.q_=this.q_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.q_=this.q_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.q_=this.q_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.q_=this.q_.remove(t):1===e.type&&2===n.type?this.q_=this.q_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.q_=this.q_.insert(t,{type:2,doc:e.doc}):U()}Q_(){const n=[];return this.q_.inorderTraversal((e,t)=>{n.push(t)}),n}}class Oo{constructor(e,t,n,r,i,s,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new Oo(e,t,Mo.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Wn(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Fo{constructor(){this.K_=void 0,this.U_=[]}W_(){return this.U_.some(e=>e.G_())}}class Po{constructor(){this.queries=new tr(e=>Yn(e),Wn),this.onlineState="Unknown",this.z_=new Set}}async function Vo(e,t){const n=e;let r=3;var i=t.query;let s=n.queries.get(i);s?!s.W_()&&t.G_()&&(r=2):(s=new Fo,r=t.G_()?0:1);try{switch(r){case 0:s.K_=await n.onListen(i,!0);break;case 1:s.K_=await n.onListen(i,!1);break;case 2:await n.onFirstRemoteStoreListen(i)}}catch(e){const n=Ro(e,`Initialization of query '${Jn(t.query)}' failed`);return void t.onError(n)}n.queries.set(i,s),s.U_.push(t),t.j_(n.onlineState),!s.K_||t.H_(s.K_)&&Bo(n)}async function Uo(e,t){const n=e,r=t.query;let i=3;const s=n.queries.get(r);if(s){const e=s.U_.indexOf(t);0<=e&&(s.U_.splice(e,1),0===s.U_.length?i=t.G_()?0:1:!s.W_()&&t.G_()&&(i=2))}switch(i){case 0:return n.queries.delete(r),n.onUnlisten(r,!0);case 1:return n.queries.delete(r),n.onUnlisten(r,!1);case 2:return n.onLastRemoteStoreUnlisten(r);default:return}}function Bo(e){e.z_.forEach(e=>{e.next()})}(D=D||{}).J_="default",D.Cache="cache";class qo{constructor(e,t,n){this.query=e,this.Y_=t,this.Z_=!1,this.X_=null,this.onlineState="Unknown",this.options=n||{}}H_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Oo(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Z_?this.ea(e)&&(this.Y_.next(e),t=!0):this.ta(e,this.onlineState)&&(this.na(e),t=!0),this.X_=e,t}onError(e){this.Y_.error(e)}j_(e){this.onlineState=e;let t=!1;return this.X_&&!this.Z_&&this.ta(this.X_,e)&&(this.na(this.X_),t=!0),t}ta(e,t){return!e.fromCache||(!this.G_()||(!this.options.ra||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t))}ea(e){if(0<e.docChanges.length)return!0;var t=this.X_&&this.X_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}na(e){e=Oo.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Z_=!0,this.Y_.next(e)}G_(){return this.options.source!==D.Cache}}class jo{constructor(e,t){this.ia=e,this.byteLength=t}sa(){return"metadata"in this.ia}}class Go{constructor(e){this.serializer=e}Ps(e){return wi(this.serializer,e)}Is(e){return e.metadata.exists?Si(this.serializer,e.document,!1):Zt.newNoDocument(this.Ps(e.metadata.name),this.Ts(e.metadata.readTime))}Ts(e){return gi(e)}}class zo{constructor(e,t,n){this.oa=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Ko(e)}_a(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ia.namedQuery)this.queries.push(e.ia.namedQuery);else if(e.ia.documentMetadata){this.documents.push({metadata:e.ia.documentMetadata}),e.ia.documentMetadata.exists||++t;const n=se.fromString(e.ia.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ia.document&&(this.documents[this.documents.length-1].document=e.ia.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}aa(e){const t=new Map,n=new Go(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.Ps(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||cr()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=cr(),a=nr;for(const e of n){const n=t.Ps(e.metadata.name);e.document&&(s=s.add(n));const c=t.Is(e);c.setReadTime(t.Ts(e.metadata.readTime)),a=a.insert(n,c)}const o=i.os.newChangeBuffer({trackRemovals:!0}),u=await Na(i,(r=r,$n(jn(se.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>Aa(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Qr.removeMatchingKeysForTargetId(t,u.targetId).next(()=>i.Qr.addMatchingKeys(t,s,u.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.cs,e.ls)).next(()=>e.cs)))}(this.localStore,new Go(this.serializer),this.documents,this.oa.id),t=this.aa(this.documents);for(const e of this.queries)await async function(e,n,r=cr()){const i=await Na(e,$n(Ki(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=gi(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.$r.saveNamedQuery(e,n);t=i.withResumeToken(Tt.EMPTY_BYTE_STRING,t);return s.ns=s.ns.insert(t.targetId,t),s.Qr.updateTargetData(e,t).next(()=>s.Qr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Qr.addMatchingKeys(e,r,i.targetId)).next(()=>s.$r.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,ua:this.collectionGroups,ca:e}}}function Ko(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class $o{constructor(e){this.key=e}}class Qo{constructor(e){this.key=e}}class Ho{constructor(e,t){this.query=e,this.la=t,this.ha=null,this.hasCachedResults=!1,this.current=!1,this.Pa=cr(),this.mutatedKeys=cr(),this.Ia=er(e),this.Ta=new Mo(this.Ia)}get Ea(){return this.la}da(e,t){const o=t?t.Aa:new Lo,u=(t||this).Ta;let c=(t||this).mutatedKeys,h=u,l=!1;const d="F"===this.query.limitType&&u.size===this.query.limit?u.last():null,f="L"===this.query.limitType&&u.size===this.query.limit?u.first():null;if(e.inorderTraversal((e,t)=>{const n=u.get(e),r=Xn(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Ra(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Ia(r,d)||f&&this.Ia(r,f)<0)&&(l=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||f)&&(l=!0)),a&&(c=r?(h=h.add(r),s?c.add(e):c.delete(e)):(h=h.delete(e),c.delete(e)))}),null!==this.query.limit)for(;h.size>this.query.limit;){const e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),c=c.delete(e.key),o.track({type:1,doc:e})}return{Ta:h,Aa:o,Xi:l,mutatedKeys:c}}Ra(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){var i=this.Ta;this.Ta=e.Ta,this.mutatedKeys=e.mutatedKeys;const s=e.Aa.Q_();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return U()}};return n(e)-n(t)}(e.type,t.type)||this.Ia(e.doc,t.doc)),this.Va(n),r=null!=r&&r;var a=t&&!r?this.ma():[],o=0===this.Pa.size&&this.current&&!r?1:0,u=o!==this.ha;return this.ha=o,0!==s.length||u?{snapshot:new Oo(this.query,e.Ta,i,s,e.mutatedKeys,0==o,u,!1,!!n&&0<n.resumeToken.approximateByteSize()),fa:a}:{fa:a}}j_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ta:this.Ta,Aa:new Lo,mutatedKeys:this.mutatedKeys,Xi:!1},!1)):{fa:[]}}ga(e){return!this.la.has(e)&&!!this.Ta.has(e)&&!this.Ta.get(e).hasLocalMutations}Va(e){e&&(e.addedDocuments.forEach(e=>this.la=this.la.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.la=this.la.delete(e)),this.current=e.current)}ma(){if(!this.current)return[];const t=this.Pa;this.Pa=cr(),this.Ta.forEach(e=>{this.ga(e.key)&&(this.Pa=this.Pa.add(e.key))});const n=[];return t.forEach(e=>{this.Pa.has(e)||n.push(new Qo(e))}),this.Pa.forEach(e=>{t.has(e)||n.push(new $o(e))}),n}pa(e){this.la=e.hs,this.Pa=cr();var t=this.da(e.documents);return this.applyChanges(t,!0)}ya(){return Oo.fromInitialDocuments(this.query,this.Ta,this.mutatedKeys,0===this.ha,this.hasCachedResults)}}class Wo{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Yo{constructor(e){this.key=e,this.wa=!1}}class Jo{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Sa={},this.ba=new tr(e=>Yn(e),Wn),this.Da=new Map,this.Ca=new Set,this.va=new pt(ue.comparator),this.Fa=new Map,this.Ma=new sa,this.xa={},this.Oa=new Map,this.Na=Os.Ln(),this.onlineState="Unknown",this.La=void 0}get isPrimaryClient(){return!0===this.La}}async function Xo(e,t,n,r){var i=await Na(e.localStore,$n(t)),s=i.targetId,a=n?e.sharedClientState.addLocalQueryTarget(s):"not-current";let o;return r&&(o=await Zo(e,t,s,"current"===a,i.resumeToken)),e.isPrimaryClient&&n&&fo(e.remoteStore,i),o}async function Zo(r,e,t,n,i){r.Ba=(e,t,n)=>async function(e,t,n,r){let i=t.view.da(n);i.Xi&&(i=await Ra(e.localStore,t.query,!1).then(({documents:e})=>t.view.da(e,i)));var s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s,a);return uu(e,t.targetId,a.fa),a.snapshot}(r,e,t,n);const s=await Ra(r.localStore,e,!0),a=new Ho(e,s.hs),o=a.da(s.documents),u=Zr.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),c=a.applyChanges(o,r.isPrimaryClient,u);uu(r,t,c.fa);var h=new Wo(e,t,a);return r.ba.set(e,h),r.Da.has(t)?r.Da.get(t).push(e):r.Da.set(t,[e]),c.snapshot}async function eu(e,t,n){const r=mu(e);try{const e=await function(e,i){const s=e,a=ne.now(),o=i.reduce((e,t)=>e.add(t.key),cr());let u,c;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=nr,r=cr();return s.os.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=mr(r.transform,e||null);null!=i&&(null===n&&(n=Xt.empty()),n.set(r.field,i))}return n||null}(n,u.get(n.key).overlayedDocument);null!=i&&t.push(new Lr(n.key,i,function r(e){const i=[];return gt(e.fields,(e,t)=>{const n=new oe([e]);if(Qt(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new It(i)}(i.value.mapValue),xr.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:sr(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.xa[e.currentUser.toKey()];r=r||new pt(Z),r=r.insert(t,n),e.xa[e.currentUser.toKey()]=r}(r,e.batchId,n),await hu(r,e.changes),await Eo(r.remoteStore)}catch(e){const t=Ro(e,"Failed to persist write");n.reject(t)}}async function tu(e,t){const r=e;try{const e=await Ca(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Fa.get(t);n&&(B(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.wa=!0:0<e.modifiedDocuments.size?B(n.wa):0<e.removedDocuments.size&&(B(n.wa),n.wa=!1))}),await hu(r,e,t)}catch(e){await _e(e)}}function nu(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ba.forEach((e,t)=>{var n=t.view.j_(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.U_)e.j_(n)&&(r=!0)}),r&&Bo(t)}(t.eventManager,i),r.length&&t.Sa.h_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function ru(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.os.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=be.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);B(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=cr();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);su(n,r,null),iu(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await hu(n,e)}catch(e){await _e(e)}}function iu(e,t){(e.Oa.get(t)||[]).forEach(e=>{e.resolve()}),e.Oa.delete(t)}function su(e,t,n){const r=e;let i=r.xa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.xa[r.currentUser.toKey()]=i}}function au(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Da.get(e))t.ba.delete(r),n&&t.Sa.ka(r,n);t.Da.delete(e),t.isPrimaryClient&&t.Ma.Vr(e).forEach(e=>{t.Ma.containsKey(e)||ou(t,e)})}function ou(e,t){e.Ca.delete(t.path.canonicalString());var n=e.va.get(t);null!==n&&(go(e.remoteStore,n),e.va=e.va.remove(t),e.Fa.delete(n),cu(e))}function uu(e,t,n){for(const r of n)r instanceof $o?(e.Ma.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.va.get(n)||e.Ca.has(r)||(O("SyncEngine","New document in limbo: "+n),e.Ca.add(r),cu(e))}(e,r)):r instanceof Qo?(O("SyncEngine","Document no longer in limbo: "+r.key),e.Ma.removeReference(r.key,t),e.Ma.containsKey(r.key)||ou(e,r.key)):U()}function cu(e){for(;0<e.Ca.size&&e.va.size<e.maxConcurrentLimboResolutions;){var t=e.Ca.values().next().value;e.Ca.delete(t);var n=new ue(se.fromString(t)),t=e.Na.next();e.Fa.set(t,new Yo(n)),e.va=e.va.insert(n,t),fo(e.remoteStore,new Fi($n(jn(n.path)),t,"TargetPurposeLimboResolution",Le.oe))}}async function hu(e,t,r){const i=e,s=[],a=[],o=[];i.ba.isEmpty()||(i.ba.forEach((e,n)=>{o.push(i.Ba(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=ba.Ki(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.Sa.h_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>be.forEach(t,t=>be.forEach(t.qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>be.forEach(t.Qi,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!De(e))throw e;O("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ns.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.ns=r.ns.insert(t,i)}}}(i.localStore,a))}async function lu(r,e){const i=r;if(gu(i),mu(i),!0===e&&!0!==i.La){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await du(i,r.toArray());i.La=!0,await Co(i.remoteStore,!0);for(const r of e)fo(i.remoteStore,r)}else if(!1===e&&!1!==i.La){const r=[];let n=Promise.resolve();i.Da.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(au(i,t),ka(i.localStore,t,!0))),go(i.remoteStore,t)}),await n,await du(i,r),function(e){const n=e;n.Fa.forEach((e,t)=>{go(n.remoteStore,t)}),n.Ma.mr(),n.Fa=new Map,n.va=new pt(ue.comparator)}(i),i.La=!1,await Co(i.remoteStore,!1)}}async function du(t,n){const r=t,i=[],s=[];for(const t of n){let e;const h=r.Da.get(t);if(h&&0!==h.length){e=await Na(r.localStore,$n(h[0]));for(const t of h){const n=r.ba.get(t),h=(a=r,o=n,c=u=void 0,c=await Ra((u=a).localStore,o.query,!0),c=o.view.pa(c),u.isPrimaryClient&&uu(u,o.targetId,c.fa),await c);h.snapshot&&s.push(h.snapshot)}}else{const h=await Ma(r.localStore,t);e=await Na(r.localStore,h),await Zo(r,fu(h),t,!1,e.resumeToken)}i.push(e)}var a,o,u,c;return r.Sa.h_(s),i}function fu(e){return qn(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function gu(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=tu.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Fa.get(t);if(r&&r.wa)return cr().add(r.key);{let e=cr();const r=n.Da.get(t);if(!r)return e;for(const t of r){const r=n.ba.get(t);e=e.unionWith(r.view.Ea)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Fa.get(t),s=i&&i.key;if(s){let e=new pt(ue.comparator);e=e.insert(s,Zt.newNoDocument(s,re.min()));const n=cr().add(s),i=new Xr(re.min(),new Map,new pt(Z),e,n);await tu(r,i),r.va=r.va.remove(s),r.Fa.delete(t),cu(r)}else await ka(r.localStore,t,!1).then(()=>au(r,t,n)).catch(_e)}).bind(null,t),t.Sa.h_=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.U_)t.H_(e)&&(r=!0);i.K_=e}}r&&Bo(n)}).bind(null,t.eventManager),t.Sa.ka=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.U_)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function mu(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=ru.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(B(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);su(r,t,n),iu(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await hu(r,e)}catch(n){await _e(n)}}).bind(null,t),t}class pu{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=no(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return Sa(this.persistence,new Ea,e.initialUser,this.serializer)}createPersistence(e){return new la(fa.Hr,this.serializer)}createSharedClientState(e){return new Ka}async terminate(){var e;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(e=this.indexBackfillerScheduler)||void 0===e||e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class yu extends pu{constructor(e,t,n){super(),this.Qa=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Qa.initialize(this,e),await mu(this.Qa.syncEngine),await Eo(this.Qa.remoteStore),await this.persistence.fi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return Sa(this.persistence,new Ea,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new js(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Me(t,this.persistence);return new Re(e.asyncQueue,n)}createPersistence(e){var t=_a(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Ds.withCacheSize(this.cacheSizeBytes):Ds.DEFAULT;return new ya(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,eo(),to(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new Ka}}class vu extends yu{constructor(e,t){super(e,t,!1),this.Qa=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Qa.syncEngine;this.sharedClientState instanceof za&&(this.sharedClientState.syncEngine={Zs:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.vn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):be.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await Eo(i.remoteStore):"acknowledged"===n||"rejected"===n?(su(i,t,r||null),iu(i,t),i.localStore.mutationQueue.Mn(t)):U(),await hu(i,s)):O("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Xs:(async function(e,t,n,r){const i=e;if(i.La)O("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.Da.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await La(i.localStore,Zn(s[0])),r=Xr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,Tt.EMPTY_BYTE_STRING);await hu(i,e,r);break}case"rejected":await ka(i.localStore,t,!0),au(i,t,r);break;default:U()}}}).bind(null,t),eo:(async function(e,t,n){const r=gu(e);if(r.La){for(const e of t)if(r.Da.has(e)&&r.sharedClientState.isActiveQueryTarget(e))O("SyncEngine","Adding an already active target "+e);else{const t=await Ma(r.localStore,e),n=await Na(r.localStore,t);await Zo(r,fu(t),n.targetId,!1,n.resumeToken),fo(r.remoteStore,n)}for(const e of n)r.Da.has(e)&&await ka(r.localStore,e,!1).then(()=>{go(r.remoteStore,e),au(r,e)}).catch(_e)}}).bind(null,t),Bi:(function(e){return e.localStore.persistence.Bi()}).bind(null,t),Ys:(async function(e,t){const n=e;return La(n.localStore,t).then(e=>hu(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.fi(async e=>{await lu(this.Qa.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}createSharedClientState(e){var t=eo();if(!za.D(t))throw new j(q.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=_a(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new za(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class wu{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>nu(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){O("SyncEngine","User change. New user:",t.toKey());const i=await xa(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.Oa.forEach(e=>{e.forEach(e=>{e.reject(new j(q.CANCELLED,r))})}),e.Oa.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await hu(n,i.us)}var r}).bind(null,this.syncEngine),await Co(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Po}createDatastore(e){var t,n,r,i=no(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new Za(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new oo(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>nu(this.syncEngine,e,0),e=new(Qa.D()?Qa:$a),new co(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Jo(e,t,n,r,i,s);return a&&(o.La=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e;await async function(e){const t=e;O("RemoteStore","RemoteStore shutting down."),t.M_.add(5),await lo(t),t.O_.shutdown(),t.N_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate()}}function _u(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class bu{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Ka(this.observer.next,e)}error(e){this.observer.error?this.Ka(this.observer.error,e):F("Uncaught Error in snapshot listener:",e.toString())}$a(){this.muted=!0}Ka(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class Iu{constructor(e,t){this.Ua=e,this.serializer=t,this.metadata=new G,this.buffer=new Uint8Array,this.Wa=new TextDecoder("utf-8"),this.Ga().then(e=>{e&&e.sa()?this.metadata.resolve(e.ia.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ia)}`))},e=>this.metadata.reject(e))}close(){return this.Ua.cancel()}async getMetadata(){return this.metadata.promise}async qa(){return await this.getMetadata(),this.Ga()}async Ga(){var e=await this.za();if(null===e)return null;var t=this.Wa.decode(e),n=Number(t);isNaN(n)&&this.ja(`length string (${t}) is not valid number`);t=await this.Ha(n);return new jo(JSON.parse(t),e.length+n)}Ja(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async za(){for(;this.Ja()<0&&!await this.Ya(););if(0===this.buffer.length)return null;var e=this.Ja();e<0&&this.ja("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Ha(e){for(;this.buffer.length<e;)await this.Ya()&&this.ja("Reached the end of bundle when more is expected.");var t=this.Wa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}ja(e){throw this.Ua.cancel(),new Error(`Invalid bundle format: ${e}`)}async Ya(){var e=await this.Ua.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class Eu{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw this.lastTransactionError=new j(q.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const t=await async function(e,t){const r=e,n={documents:t.map(e=>vi(r.serializer,e))},i=await r.xo("BatchGetDocuments",r.serializer.databaseId,se.emptyPath(),n,t.length),s=new Map;i.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){B(!!t.found),t.found.name,t.found.updateTime;var n=wi(e,t.found.name),r=gi(t.found.updateTime),i=t.found.createTime?gi(t.found.createTime):re.min(),s=new Xt({mapValue:{fields:t.found.fields}});return Zt.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){B(!!t.missing),B(!!t.readTime);var n=wi(e,t.missing),r=gi(t.readTime);return Zt.newNoDocument(n,r)}(n,e):U());var n;s.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=s.get(e.toString());B(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Vr(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=ue.fromPath(t);this.mutations.push(new Ur(n,this.precondition(n)))}),await async function(e,t){const n=e,r={writes:t.map(e=>xi(n.serializer,e))};await n.Co("Commit",n.serializer.databaseId,se.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw U();t=re.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new j(q.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(re.min())?xr.exists(!1):xr.updateTime(t):xr.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return xr.exists(!0);if(t.isEqual(re.min()))throw new j(q.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return xr.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Tu{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Za=n.maxAttempts,this.Yo=new ro(this.asyncQueue,"transaction_retry")}Xa(){--this.Za,this.eu()}eu(){this.Yo.$o(async()=>{const t=new Eu(this.datastore),e=this.tu(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.nu(e)}))}).catch(e=>{this.nu(e)})})}tu(e){try{var t=this.updateFunction(e);return!Oe(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}}nu(e){0<this.Za&&this.ru(e)?(--this.Za,this.asyncQueue.enqueueAndForget(()=>(this.eu(),Promise.resolve()))):this.deferred.reject(e)}ru(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!zr(t)}}class Su{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=k.UNAUTHENTICATED,this.clientId=X.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{O("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(O("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new j(q.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new G;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=Ro(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function xu(e,t){e.asyncQueue.verifyOperationInProgress(),O("FirestoreClient","Initializing OfflineComponentProvider");var n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await xa(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function Du(e,n){e.asyncQueue.verifyOperationInProgress();var t=await Au(e);O("FirestoreClient","Initializing OnlineComponentProvider"),await n.initialize(t,e.configuration),e.setCredentialChangeListener(e=>Do(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>Do(n.remoteStore,t)),e._onlineComponents=n}function Cu(e){return"FirebaseError"===e.name?e.code===q.FAILED_PRECONDITION||e.code===q.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function Au(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){O("FirestoreClient","Using user provided OfflineComponentProvider");try{await xu(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!Cu(n))throw n;P("Error using user provided cache. Falling back to memory cache: "+n),await xu(t,new pu)}}else O("FirestoreClient","Using default OfflineComponentProvider"),await xu(t,new pu);return t._offlineComponents}async function Nu(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(O("FirestoreClient","Using user provided OnlineComponentProvider"),await Du(e,e._uninitializedComponentsProvider._online)):(O("FirestoreClient","Using default OnlineComponentProvider"),await Du(e,new wu))),e._onlineComponents}function ku(e){return Au(e).then(e=>e.persistence)}function Ru(e){return Au(e).then(e=>e.localStore)}function Mu(e){return Nu(e).then(e=>e.remoteStore)}function Lu(e){return Nu(e).then(e=>e.syncEngine)}async function Ou(e){const t=await Nu(e),n=t.eventManager;return n.onListen=(async function(e,t,n=!0){const r=gu(e);let i;const s=r.ba.get(t);return i=s?(r.sharedClientState.addLocalQueryTarget(s.targetId),s.view.ya()):await Xo(r,t,n,!0),i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t,n){const r=e,i=r.ba.get(t),s=r.Da.get(i.targetId);if(1<s.length)return r.Da.set(i.targetId,s.filter(e=>!Wn(e,t))),void r.ba.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(i.targetId),r.sharedClientState.isActiveQueryTarget(i.targetId)||await ka(r.localStore,i.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(i.targetId),n&&go(r.remoteStore,i.targetId),au(r,i.targetId)}).catch(_e)):(au(r,i.targetId),await ka(r.localStore,i.targetId,!0))}).bind(null,t.syncEngine),n.onFirstRemoteStoreListen=(async function(e,t){await Xo(gu(e),t,!0,!1)}).bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=(async function(e,t){const n=e,r=n.ba.get(t),i=n.Da.get(r.targetId);n.isPrimaryClient&&1===i.length&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),go(n.remoteStore,r.targetId))}).bind(null,t.syncEngine),n}function Fu(e,t,n={}){const r=new G;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new bu({next:e=>{r.enqueueAndForget(()=>Uo(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new j(q.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new j(q.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new qo(jn(i.path),e,{includeMetadataChanges:!0,ra:!0});return Vo(n,o)}(await Ou(e),e.asyncQueue,t,n,r)),r.promise}function Pu(e,t,n={}){const r=new G;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new bu({next:e=>{n.enqueueAndForget(()=>Uo(t,a)),e.fromCache&&"server"===r.source?i.reject(new j(q.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new qo(e,s,{includeMetadataChanges:!0,ra:!0});return Vo(t,a)}(await Ou(e),e.asyncQueue,t,n,r)),r.promise}function Vu(e,t,n,r){const i=(n=n,t=no(t),s="string"==typeof n?$r().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return _u(e,t);if(e instanceof ArrayBuffer)return _u(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new Iu(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=gi(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.$r.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(Ko(i));const a=new zo(i,t.localStore,n.serializer);let e=await n.qa();for(;e;){const t=await a._a(e);t&&r._updateProgress(t),e=await n.qa()}var s=await a.complete();return await hu(t,s.ca,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.$r.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.ua)}catch(t){return P("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await Lu(e),i,r)})}function Uu(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Bu=new Map;function qu(e,t,n){if(!n)throw new j(q.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function ju(e,t,n,r){if(!0===t&&!0===r)throw new j(q.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Gu(e){if(!ue.isDocumentKey(e))throw new j(q.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function zu(e){if(ue.isDocumentKey(e))throw new j(q.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ku(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":U();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function $u(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new j(q.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Ku(e);throw new j(q.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Qu(e,t){if(t<=0)throw new j(q.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Hu{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new j(q.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new j(q.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}ju("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Uu(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new j(q.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new j(q.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new j(q.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class Wu{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Hu({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new j(q.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new j(q.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 Hu(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new K;switch(e.type){case"firstParty":return new W(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new j(q.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Bu.get(e);t&&(O("ComponentProvider","Removing Datastore"),Bu.delete(e),t.terminate())}(this),Promise.resolve()}}function Yu(n,e,t,r={}){var i;const s=(n=$u(n,Wu))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&P("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=k.MOCK_USER;else{e=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e),[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(i)),""].join(".")}(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new j(q.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new k(s)}n._authCredentials=new $(new z(e,t))}}class Ju{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Ju(this.firestore,e,this._query)}}class Xu{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Zu(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Xu(this.firestore,e,this._key)}}class Zu extends Ju{constructor(e,t,n){super(e,t,jn(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Xu(this.firestore,null,new ue(e))}withConverter(e){return new Zu(this.firestore,e,this._path)}}function ec(e,t,...n){if(e=y(e),qu("collection","path",t),e instanceof Wu){var r=se.fromString(t,...n);return zu(r),new Zu(e,null,r)}if(!(e instanceof Xu||e instanceof Zu))throw new j(q.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(se.fromString(t,...n));return zu(r),new Zu(e.firestore,null,r)}function tc(e,t,...n){if(e=y(e),qu("doc","path",t=1===arguments.length?X.newId():t),e instanceof Wu){var r=se.fromString(t,...n);return Gu(r),new Xu(e,null,new ue(r))}if(!(e instanceof Xu||e instanceof Zu))throw new j(q.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(se.fromString(t,...n));return Gu(r),new Xu(e.firestore,e instanceof Zu?e.converter:null,new ue(r))}function nc(e,t){return e=y(e),t=y(t),(e instanceof Xu||e instanceof Zu)&&(t instanceof Xu||t instanceof Zu)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function rc(e,t){return e=y(e),t=y(t),e instanceof Ju&&t instanceof Ju&&e.firestore===t.firestore&&Wn(e._query,t._query)&&e.converter===t.converter}class ic{constructor(){this.iu=Promise.resolve(),this.su=[],this.ou=!1,this._u=[],this.au=null,this.uu=!1,this.cu=!1,this.lu=[],this.Yo=new ro(this,"async_queue_retry"),this.hu=()=>{var e=to();e&&O("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Yo.Wo()};const e=to();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.hu)}get isShuttingDown(){return this.ou}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Pu(),this.Iu(e)}enterRestrictedMode(e){if(!this.ou){this.ou=!0,this.cu=e||!1;const t=to();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.hu)}}enqueue(e){if(this.Pu(),this.ou)return new Promise(()=>{});const t=new G;return this.Iu(()=>this.ou&&this.cu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.su.push(e),this.Tu()))}async Tu(){if(0!==this.su.length){try{await this.su[0](),this.su.shift(),this.Yo.reset()}catch(e){if(!De(e))throw e;O("AsyncQueue","Operation failed with retryable error: "+e)}0<this.su.length&&this.Yo.$o(()=>this.Tu())}}Iu(e){var t=this.iu.then(()=>(this.uu=!0,e().catch(e=>{throw this.au=e,this.uu=!1,F("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.uu=!1,e))));return this.iu=t}enqueueAfterDelay(e,t,n){this.Pu(),-1<this.lu.indexOf(e)&&(t=0);var r=ko.createAndSchedule(this,e,t,n,e=>this.Eu(e));return this._u.push(r),r}Pu(){this.au&&U()}verifyOperationInProgress(){}async du(){for(var e;await(e=this.iu),e!==this.iu;);}Au(e){for(const t of this._u)if(t.timerId===e)return!0;return!1}Ru(t){return this.du().then(()=>{this._u.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this._u)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.du()})}Vu(e){this.lu.push(e)}Eu(e){var t=this._u.indexOf(e);this._u.splice(t,1)}}function sc(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class ac{constructor(){this._progressObserver={},this._taskCompletionResolver=new G,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var oc,uc,cc,hc,lc;class dc extends Wu{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ic,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||gc(this),this._firestoreClient.terminate()}}function fc(e){return e._firestoreClient||gc(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function gc(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new Rt(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Uu(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new Su(e._authCredentials,e._appCheckCredentials,e._queue,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function mc(e,t,n){const r=new G;return e.asyncQueue.enqueue(async()=>{try{await xu(e,n),await Du(e,t),r.resolve()}catch(e){const t=e;if(!Cu(t))throw t;P("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function pc(e){return function(e){const t=new G;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;wo(n.remoteStore)||O("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Oa.get(e)||[];r.push(t),n.Oa.set(e,r)}catch(e){const n=Ro(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await Lu(e),t)),t.promise}(fc(e=$u(e,dc)))}function yc(e){return(n=fc(e=$u(e,dc))).asyncQueue.enqueue(async()=>{const e=await ku(n),t=await Mu(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.M_.delete(0),ho(t)}(t)});var n}function vc(e){return(n=fc(e=$u(e,dc))).asyncQueue.enqueue(async()=>{const e=await ku(n),t=await Mu(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.M_.add(0),await lo(t),t.N_.set("Offline")}(t)});var n}function wc(t,e){return n=fc(t=$u(t,dc)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.$r.getNamedQuery(e,t))}(await Ru(n),r)).then(e=>e?new Ju(t,null,e.query):null);var n,r}function _c(e){if(e._initialized||e._terminated)throw new j(q.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class bc{constructor(e){this._byteString=e}static fromBase64String(e){try{return new bc(Tt.fromBase64String(e))}catch(e){throw new j(q.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new bc(Tt.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class Ic{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new j(q.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new oe(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class Ec{constructor(e){this._methodName=e}}class Tc{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new j(q.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new j(q.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Z(this._lat,e._lat)||Z(this._long,e._long)}}const Sc=/^__.*__$/;class xc{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Lr(e,this.data,this.fieldMask,t,this.fieldTransforms):new Mr(e,this.data,t,this.fieldTransforms)}}class Dc{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Lr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Cc(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw U()}}class Ac{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.mu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get fu(){return this.settings.fu}gu(e){return new Ac(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}pu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.gu({path:n,yu:!1});return r.wu(e),r}Su(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.gu({path:n,yu:!1});return r.mu(),r}bu(e){return this.gu({path:void 0,yu:!0})}Du(e){return Wc(e,this.settings.methodName,this.settings.Cu||!1,this.path,this.settings.vu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}mu(){if(this.path)for(let e=0;e<this.path.length;e++)this.wu(this.path.get(e))}wu(e){if(0===e.length)throw this.Du("Document fields must not be empty");if(Cc(this.fu)&&Sc.test(e))throw this.Du('Document fields cannot begin and end with "__"')}}class Nc{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||no(e)}Fu(e,t,n,r=!1){return new Ac({fu:e,methodName:t,vu:n,path:oe.emptyPath(),yu:!1,Cu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function kc(e){var t=e._freezeSettings(),n=no(e._databaseId);return new Nc(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Rc(e,t,n,r,i,s={}){const a=e.Fu(s.merge||s.mergeFields?2:0,t,n,i);Kc("Data must be an object, but it was:",a,r);var o=Gc(r,a);let u,c;if(s.merge)u=new It(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=$c(t,r,n);if(!a.contains(i))throw new j(q.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Yc(e,i)||e.push(i)}u=new It(e),c=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=a.fieldTransforms;return new xc(new Xt(o),u,c)}class Mc extends Ec{_toFieldTransform(e){if(2!==e.fu)throw 1===e.fu?e.Du(`${this._methodName}() can only appear at the top level of your update data`):e.Du(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Mc}}function Lc(e,t,n){return new Ac({fu:3,vu:t.settings.vu,methodName:e._methodName,yu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class Oc extends Ec{_toFieldTransform(e){return new Tr(e.path,new pr)}isEqual(e){return e instanceof Oc}}class Fc extends Ec{constructor(e,t){super(e),this.Mu=t}_toFieldTransform(e){const t=Lc(this,e,!0),n=this.Mu.map(e=>jc(e,t)),r=new yr(n);return new Tr(e.path,r)}isEqual(e){return e instanceof Fc&&m(this.Mu,e.Mu)}}class Pc extends Ec{constructor(e,t){super(e),this.Mu=t}_toFieldTransform(e){const t=Lc(this,e,!0),n=this.Mu.map(e=>jc(e,t)),r=new wr(n);return new Tr(e.path,r)}isEqual(e){return e instanceof Pc&&m(this.Mu,e.Mu)}}class Vc extends Ec{constructor(e,t){super(e),this.xu=t}_toFieldTransform(e){var t=new br(e.serializer,fr(e.serializer,this.xu));return new Tr(e.path,t)}isEqual(e){return e instanceof Vc&&this.xu===e.xu}}function Uc(e,i,s,t){const a=e.Fu(1,i,s);Kc("Data must be an object, but it was:",a,t);const o=[],u=Xt.empty();gt(t,(e,t)=>{var n=Hc(i,e,s);t=y(t);var r=a.Su(n);if(t instanceof Mc)o.push(n);else{const e=jc(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new It(o);return new Dc(u,n,a.fieldTransforms)}function Bc(e,t,n,r,i,s){const a=e.Fu(1,t,n),o=[$c(t,r,n)],u=[i];if(s.length%2!=0)throw new j(q.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)o.push($c(t,s[f])),u.push(s[f+1]);const c=[],h=Xt.empty();for(let g=o.length-1;0<=g;--g)if(!Yc(c,o[g])){const t=o[g];var l=y(l=u[g]);const r=a.Su(t);if(l instanceof Mc)c.push(t);else{const e=jc(l,r);null!=e&&(c.push(t),h.set(t,e))}}var d=new It(c);return new Dc(h,d,a.fieldTransforms)}function qc(e,t,n,r=!1){return jc(n,e.Fu(r?4:3,t))}function jc(e,t){if(zc(e=y(e)))return Kc("Unsupported field value:",t,e),Gc(e,t);if(e instanceof Ec)return function(e,t){if(!Cc(t.fu))throw t.Du(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Du(`${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.yu&&4!==t.fu)throw t.Du("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=jc(i,t.bu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=y(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return fr(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=ne.fromDate(e);return{timestampValue:di(t.serializer,n)}}if(e instanceof ne){n=new ne(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:di(t.serializer,n)}}if(e instanceof Tc)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof bc)return{bytesValue:fi(t.serializer,e._byteString)};if(e instanceof Xu){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.Du(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:mi(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Du(`Unsupported field value: ${Ku(e)}`)}(e,t)}function Gc(e,r){const i={};return mt(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):gt(e,(e,t)=>{var n=jc(t,r.pu(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function zc(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ne||e instanceof Tc||e instanceof bc||e instanceof Xu||e instanceof Ec)}function Kc(e,t,n){if(!zc(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=Ku(n);throw"an object"===r?t.Du(e+" a custom object"):t.Du(e+" "+r)}var i}function $c(e,t,n){if((t=y(t))instanceof Ic)return t._internalPath;if("string"==typeof t)return Hc(e,t);throw Wc("Field path arguments must be of type string or ",e,!1,void 0,n)}const Qc=new RegExp("[~\\*/\\[\\]]");function Hc(t,n,r){if(0<=n.search(Qc))throw Wc(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new Ic(...n.split("."))._internalPath}catch(e){throw Wc(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Wc(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(s||a)&&(u+=" (found",s&&(u+=` in field ${r}`),a&&(u+=` in document ${i}`),u+=")"),new j(q.INVALID_ARGUMENT,o+e+u)}function Yc(e,t){return e.some(e=>e.isEqual(t))}class Jc{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Xu(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Xc(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(Zc("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Xc extends Jc{data(){return super.data()}}function Zc(e,t){return"string"==typeof t?Hc(e,t):(t instanceof Ic?t:t._delegate)._internalPath}function eh(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new j(q.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class th{}class nh extends th{}function rh(e,t,...n){let r=[];t instanceof th&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof sh).length,n=e.filter(e=>e instanceof ih).length;if(1<t||0<t&&0<n)throw new j(q.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class ih extends nh{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new ih(e,t,n)}_apply(e){var t=this._parse(e);return fh(e._query,t),new Ju(e.firestore,e.converter,Qn(e._query,t))}_parse(e){var t=kc(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new j(q.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){dh(a,s);const t=[];for(const n of a)t.push(lh(r,e,n));o={arrayValue:{values:t}}}else o=lh(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||dh(a,s),o=qc(n,t,a,"in"===s||"not-in"===s);return an.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class sh extends th{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new sh(e,t)}_parse(t){var e=this._queryConstraints.map(e=>e._parse(t)).filter(e=>0<e.getFilters().length);return 1===e.length?e[0]:on.create(e,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(const e of t.getFlattenedFilters())fh(n,e),n=Qn(n,e)}(e._query,t),new Ju(e.firestore,e.converter,Qn(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class ah extends nh{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new ah(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new j(q.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new j(q.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new rn(t,n)}(e._query,this._field,this._direction);return new Ju(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Bn(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class oh extends nh{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new oh(e,t,n)}_apply(e){return new Ju(e.firestore,e.converter,Hn(e._query,this._limit,this._limitType))}}class uh extends nh{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uh(e,t,n)}_apply(e){var t,n=hh(e,this.type,this._docOrFields,this._inclusive);return new Ju(e.firestore,e.converter,(t=e._query,e=n,new Bn(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class ch extends nh{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new ch(e,t,n)}_apply(e){var t,n=hh(e,this.type,this._docOrFields,this._inclusive);return new Ju(e.firestore,e.converter,(t=e._query,e=n,new Bn(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function hh(e,t,n,r){if(n[0]=y(n[0]),n[0]instanceof Jc)return function(e,t,n,r,i){if(!r)throw new j(q.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Kn(e))if(n.field.isKeyField())s.push(jt(t,r.key));else{const e=r.data.field(n.field);if(At(e))throw new j(q.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new j(q.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new en(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=kc(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new j(q.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u<i.length;u++){const c=i[u];if(a[u].field.isKeyField()){if("string"!=typeof c)throw new j(q.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!zn(e)&&-1!==c.indexOf("/"))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(se.fromString(c));if(!ue.isDocumentKey(n))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new ue(n);o.push(jt(t,i))}else{const e=qc(n,r,c);o.push(e)}}return new en(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function lh(e,t,n){if("string"==typeof(n=y(n))){if(""===n)throw new j(q.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!zn(t)&&-1!==n.indexOf("/"))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(se.fromString(n));if(!ue.isDocumentKey(r))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return jt(e,new ue(r))}if(n instanceof Xu)return jt(e,n._key);throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ku(n)}.`)}function dh(e,t){if(!Array.isArray(e)||0===e.length)throw new j(q.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function fh(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(e){switch(e){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[]}}(t.op));if(null!==n)throw n===t.op?new j(q.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new j(q.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class gh{convertValue(e,t="none"){switch(Ft(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Dt(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(Ct(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 U()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return gt(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new Tc(Dt(e.latitude),Dt(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=Nt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(kt(e));default:return null}}convertTimestamp(e){var t=xt(e);return new ne(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=se.fromString(e);B(Oi(n));const r=new Mt(n.get(1),n.get(3)),i=new ue(n.popFirst(5));return r.isEqual(t)||F(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function mh(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class ph extends gh{constructor(e){super(),this.firestore=e}convertBytes(e){return new bc(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Xu(this.firestore,null,t)}}class yh{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class vh extends Jc{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new wh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(Zc("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class wh extends vh{data(e={}){return super.data(e)}}class _h{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new yh(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new wh(this._firestore,this._userDataWriter,e.key,e,new yh(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new j(q.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new wh(s._firestore,s._userDataWriter,e.doc.key,e.doc,new yh(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new wh(s._firestore,s._userDataWriter,e.doc.key,e.doc,new yh(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return U()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function bh(e,t){return e instanceof vh&&t instanceof vh?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 _h&&t instanceof _h&&e._firestore===t._firestore&&rc(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class Ih extends gh{constructor(e){super(),this.firestore=e}convertBytes(e){return new bc(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Xu(this.firestore,null,t)}}function Eh(t){t=$u(t,Xu);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return function(e,t){const n=new G;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new j(q.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=Ro(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await Ru(e),t,n)),n.promise}(e,t._key).then(e=>new vh(n,r,t._key,e,new yh(null!==e&&e.hasLocalMutations,!0),t.converter))}function Th(t){t=$u(t,Ju);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return function(e,t){const n=new G;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await Ra(e,t,!0),s=new Ho(t,i.hs),a=s.da(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=Ro(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await Ru(e),t,n)),n.promise}(e,t._query).then(e=>new _h(n,r,t,e))}function Sh(e,t,n){e=$u(e,Xu);var r=$u(e.firestore,dc),i=mh(e.converter,t,n);return Ah(r,[Rc(kc(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,xr.none())])}function xh(e,t,n,...r){e=$u(e,Xu);var i=$u(e.firestore,dc),s=kc(i);let a;return a="string"==typeof(t=y(t))||t instanceof Ic?Bc(s,"updateDoc",e._key,t,n,r):Uc(s,"updateDoc",e._key,t),Ah(i,[a.toMutation(e._key,xr.exists(!0))])}function Dh(t,...n){var e;t=y(t);let r={includeMetadataChanges:!1,source:"default"},i=0;"object"!=typeof n[i]||sc(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges,source:r.source};if(sc(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Xu)o=$u(t.firestore,dc),u=jn(t._key.path),a={next:e=>{n[i]&&n[i](Nh(o,t,e))},error:n[i+1],complete:n[i+2]};else{const c=$u(t,Ju);o=$u(c.firestore,dc),u=c._query;const h=new Ih(o);a={next:e=>{n[i]&&n[i](new _h(o,h,c,e))},error:n[i+1],complete:n[i+2]},eh(t._query)}return function(e,t,n,r){const i=new bu(r),s=new qo(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Vo(await Ou(e),s)),()=>{i.$a(),e.asyncQueue.enqueueAndForget(async()=>Uo(await Ou(e),s))}}(fc(o),u,s,a)}function Ch(e,t){return function(e,t){const n=new bu(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.z_.add(t),t.next()}(await Ou(e),n)),()=>{n.$a(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.z_.delete(t)}(await Ou(e),n))}}(fc(e=$u(e,dc)),sc(t)?t:{next:t})}function Ah(e,t){return function(e,t){const n=new G;return e.asyncQueue.enqueueAndForget(async()=>eu(await Lu(e),t,n)),n.promise}(fc(e),t)}function Nh(e,t,n){var r=n.docs.get(t._key),i=new Ih(e);return new vh(e,i,t._key,r,new yh(n.hasPendingWrites,n.fromCache),t.converter)}const kh={maxAttempts:5};class Rh{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=kc(e)}set(e,t,n){this._verifyNotCommitted();const r=Mh(e,this._firestore),i=mh(r.converter,t,n),s=Rc(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,xr.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=Mh(e,this._firestore);let s;return s="string"==typeof(t=y(t))||t instanceof Ic?Bc(this._dataReader,"WriteBatch.update",i._key,t,n,r):Uc(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,xr.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=Mh(e,this._firestore);return this._mutations=this._mutations.concat(new Vr(t._key,xr.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new j(q.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function Mh(e,t){if((e=y(e)).firestore!==t)throw new j(q.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class Lh extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=kc(e)}get(e){const n=Mh(e,this._firestore),r=new ph(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return U();const t=e[0];if(t.isFoundDocument())return new Jc(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Jc(this._firestore,r,n._key,null,n.converter);throw U()})}set(e,t,n){var r=Mh(e,this._firestore),i=mh(r.converter,t,n),i=Rc(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=Mh(e,this._firestore),s="string"==typeof(t=y(t))||t instanceof Ic?Bc(this._dataReader,"Transaction.update",i._key,t,n,r):Uc(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=Mh(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=Mh(e,this._firestore),n=new Ih(this._firestore);return super.get(e).then(e=>new vh(this._firestore,n,t._key,e._document,new yh(!1,!1),t.converter))}}function Oh(t,n,e){t=$u(t,dc);var r=Object.assign(Object.assign({},kh),e);return function(e){if(e.maxAttempts<1)throw new j(q.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new G;return t.asyncQueue.enqueueAndForget(async()=>{var e=await Nu(t).then(e=>e.datastore);new Tu(t.asyncQueue,e,r,n,i).Xa()}),i.promise}(fc(t),e=>n(new Lh(t,e)),r)}uc=!0,cc=ul.SDK_VERSION,R=cc,ul._registerComponent(new v("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new dc(new Q(e.getProvider("auth-internal")),new J(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new j(q.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Mt(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:uc},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),ul.registerVersion(A,N,oc),ul.registerVersion(A,N,"esm2017");function Fh(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new j("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Ph(){if("undefined"==typeof Uint8Array)throw new j("unimplemented","Uint8Arrays are not available in this environment.")}function Vh(){if("undefined"==typeof atob)throw new j("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Uh{constructor(e){this._delegate=e}static fromBase64String(e){return Vh(),new Uh(bc.fromBase64String(e))}static fromUint8Array(e){return Ph(),new Uh(bc.fromUint8Array(e))}toBase64(){return Vh(),this._delegate.toBase64()}toUint8Array(){return Ph(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Bh(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class qh{enableIndexedDbPersistence(e,t){return function(e,t){_c(e=$u(e,dc));var n=fc(e);if(n._uninitializedComponentsProvider)throw new j(q.FAILED_PRECONDITION,"SDK cache is already specified.");P("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new wu;return mc(n,i,new yu(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){_c(e=$u(e,dc));var t=fc(e);if(t._uninitializedComponentsProvider)throw new j(q.FAILED_PRECONDITION,"SDK cache is already specified.");P("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new wu;return mc(t,r,new vu(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new j(q.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new G;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Ee.D())return Promise.resolve();var t=e+"main";await Ee.delete(t)}(_a(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class jh{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Mt||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||P("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){Yu(this._delegate,e,t,n)}enableNetwork(){return yc(this._delegate)}disableNetwork(){return vc(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,ju("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return pc(this._delegate)}onSnapshotsInSync(e){return Ch(this._delegate,e)}get app(){if(!this._appCompat)throw new j("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new nl(this,ec(this._delegate,e))}catch(e){throw Hh(e,"collection()","Firestore.collection()")}}doc(e){try{return new Qh(this,tc(this._delegate,e))}catch(e){throw Hh(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Zh(this,function(e,t){if(e=$u(e,Wu),qu("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new j(q.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ju(e,null,(t=t,new Bn(se.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Hh(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Oh(this._delegate,e=>t(new zh(this,e)))}batch(){return fc(this._delegate),new Kh(new Rh(this._delegate,e=>Ah(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=fc(t=$u(t,dc)),r=new ac,Vu(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return wc(this._delegate,e).then(e=>e?new Zh(this,e):null)}}class Gh extends gh{constructor(e){super(),this.firestore=e}convertBytes(e){return new Uh(new bc(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Qh.forKey(t,this.firestore,null)}}class zh{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Gh(e)}get(e){const t=rl(e);return this._delegate.get(t).then(e=>new Jh(this._firestore,new vh(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=rl(e);return n?(Fh("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=rl(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=rl(e);return this._delegate.delete(t),this}}class Kh{constructor(e){this._delegate=e}set(e,t,n){var r=rl(e);return n?(Fh("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=rl(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=rl(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class $h{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new wh(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Xh(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=$h.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new $h(e,new Gh(e),t),r.set(t,i)),i}}$h.INSTANCES=new WeakMap;class Qh{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Gh(e)}static forPath(e,t,n){if(e.length%2!=0)throw new j("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Qh(t,new Xu(t._delegate,n,new ue(e)))}static forKey(e,t,n){return new Qh(t,new Xu(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new nl(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new nl(this.firestore,ec(this._delegate,e))}catch(e){throw Hh(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=y(e))instanceof Xu&&nc(this._delegate,e)}set(e,t){t=Fh("DocumentReference.set",t);try{return t?Sh(this._delegate,e,t):Sh(this._delegate,e)}catch(e){throw Hh(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?xh(this._delegate,e):xh(this._delegate,e,t,...n)}catch(e){throw Hh(e,"updateDoc()","DocumentReference.update()")}}delete(){return Ah($u((e=this._delegate).firestore,dc),[new Vr(e._key,xr.none())]);var e}onSnapshot(...e){var t=Wh(e),n=Yh(e,e=>new Jh(this.firestore,new vh(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return Dh(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?Eh:"server"===(null==e?void 0:e.source)?function(t){t=$u(t,Xu);const n=$u(t.firestore,dc);return Fu(fc(n),t._key,{source:"server"}).then(e=>Nh(n,t,e))}:function(t){t=$u(t,Xu);const n=$u(t.firestore,dc);return Fu(fc(n),t._key).then(e=>Nh(n,t,e))})(this._delegate),t.then(e=>new Jh(this.firestore,new vh(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Qh(this.firestore,e?this._delegate.withConverter($h.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Hh(e,t,n){return e.message=e.message.replace(t,n),e}function Wh(e){for(const t of e)if("object"==typeof t&&!Bh(t))return t;return{}}function Yh(e,t){var n;let r;return r=Bh(e[0])?e[0]:Bh(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class Jh{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Qh(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 bh(this._delegate,e._delegate)}}class Xh extends Jh{data(e){var t=this._delegate.data(e);return this._delegate._converter||void 0!==t||U(),t}}class Zh{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Gh(e)}where(e,t,n){try{return new Zh(this.firestore,rh(this._delegate,(r=n,i=t,s=Zc("where",e),ih._create(s,i,r))))}catch(e){throw Hh(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new Zh(this.firestore,rh(this._delegate,([n,r="asc"]=[e,t],i=r,s=Zc("orderBy",n),ah._create(s,i))))}catch(e){throw Hh(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new Zh(this.firestore,rh(this._delegate,(Qu("limit",t=e),oh._create("limit",t,"F"))))}catch(e){throw Hh(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Zh(this.firestore,rh(this._delegate,(Qu("limitToLast",t=e),oh._create("limitToLast",t,"L"))))}catch(e){throw Hh(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return uh._create("startAt",e,!0)}(...e)))}catch(e){throw Hh(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return uh._create("startAfter",e,!1)}(...e)))}catch(e){throw Hh(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return ch._create("endBefore",e,!1)}(...e)))}catch(e){throw Hh(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return ch._create("endAt",e,!0)}(...e)))}catch(e){throw Hh(e,"endAt()","Query.endAt()")}}isEqual(e){return rc(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?Th:"server"===(null==e?void 0:e.source)?function(t){t=$u(t,Ju);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return Pu(e,t._query,{source:"server"}).then(e=>new _h(n,r,t,e))}:function(t){t=$u(t,Ju);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return eh(t._query),Pu(e,t._query).then(e=>new _h(n,r,t,e))})(this._delegate),t.then(e=>new tl(this.firestore,new _h(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Wh(e),n=Yh(e,e=>new tl(this.firestore,new _h(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return Dh(this._delegate,t,n)}withConverter(e){return new Zh(this.firestore,e?this._delegate.withConverter($h.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class el{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Xh(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class tl{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Zh(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 Xh(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new el(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Xh(this._firestore,e))})}isEqual(e){return bh(this._delegate,e._delegate)}}class nl extends Zh{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new Qh(this.firestore,e):null}doc(e){try{return void 0===e?new Qh(this.firestore,tc(this._delegate)):new Qh(this.firestore,tc(this._delegate,e))}catch(e){throw Hh(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=$u(e.firestore,dc),r=tc(e),i=mh(e.converter,t);return Ah(n,[Rc(kc(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,xr.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Qh(this.firestore,e))}isEqual(e){return nc(this._delegate,e._delegate)}withConverter(e){return new nl(this.firestore,e?this._delegate.withConverter($h.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function rl(e){return $u(e,Xu)}const il={Firestore:jh,GeoPoint:Tc,Timestamp:ne,Blob:Uh,Transaction:zh,WriteBatch:Kh,DocumentReference:Qh,DocumentSnapshot:Jh,Query:Zh,QueryDocumentSnapshot:Xh,QuerySnapshot:tl,CollectionReference:nl,FieldPath:class sl{constructor(...e){this._delegate=new Ic(...e)}static documentId(){return new sl(oe.keyField().canonicalString())}isEqual(e){return(e=y(e))instanceof Ic&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class al{constructor(e){this._delegate=e}static serverTimestamp(){const e=new Oc("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new al(e)}static delete(){const e=new Mc("deleteField");return e._methodName="FieldValue.delete",new al(e)}static arrayUnion(...e){const t=function(...e){return new Fc("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new al(t)}static arrayRemove(...e){const t=function(...e){return new Pc("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new al(t)}static increment(e){const t=new Vc("increment",e);return t._methodName="FieldValue.increment",new al(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,M.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};hc=t.default,lc=(e,t)=>new jh(e,t,new qh),hc.INTERNAL.registerComponent(new v("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return lc(t,n)},"PUBLIC").setServiceProps(Object.assign({},il))),hc.registerVersion("@firebase/firestore-compat","0.3.30-dataconnect-preview.f2ddc3d7b")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-firestore-compat.js - be sure to load firebase-app.js first.")}});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(ol,ul){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(ol);function n(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let h=0;h<n.length;h+=3){var s=n[h],a=h+1<n.length,o=a?n[h+1]:0,u=h+2<n.length,c=u?n[h+2]:0;let e=(15&o)<<2|c>>6,t=63&c;u||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u<e.length;){var i=n[e.charAt(u++)],s=u<e.length?n[e.charAt(u)]:0;++u;var a=u<e.length?n[e.charAt(u)]:64;++u;var o=u<e.length?n[e.charAt(u)]:64;if(++u,null==i||null==s||null==a||null==o)throw new c;r.push(i<<2|s>>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const i=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,s=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},a=()=>{try{return i()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||s()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function h(){return!function(){var e=null===(e=a())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class d extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,f.prototype.create)}}class f{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(g,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new d(i,s,n)}}const g=/\{\$([^}]+)}/g;function m(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;var i=e[a],s=t[a];if(p(i)&&p(s)){if(!m(i,s))return!1}else if(i!==s)return!1}for(const o of r)if(!n.includes(o))return!1;return!0}function p(e){return null!==e&&"object"==typeof e}function y(e){return e&&e._delegate?e._delegate:e}class v{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}(cc=l=l||{})[cc.DEBUG=0]="DEBUG",cc[cc.VERBOSE=1]="VERBOSE",cc[cc.INFO=2]="INFO",cc[cc.WARN=3]="WARN",cc[cc.ERROR=4]="ERROR",cc[cc.SILENT=5]="SILENT";const w={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},_=l.INFO,b={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},I=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=b[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};var E,T,S="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!(function(){var e,t,s;function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function r(){}function a(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((a=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function c(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}t=n,r.prototype=(s=function(){this.blockSize=-1}).prototype,t.D=s.prototype,t.prototype=new r,(t.prototype.constructor=t).C=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)},n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},n.prototype.u=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.B,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)a(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){a(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){a(this,r),i=0;break}}this.h=i,this.o+=t},n.prototype.v=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.o,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.u(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var i={};function o(e){return-128<=e&&e<128?(t=e,n=function(e){return new c([0|e],e<0?-1:0)},r=i,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new c([0|e],e<0?-1:0);var t,n,r}function h(e){if(isNaN(e)||!isFinite(e))return l;if(e<0)return m(h(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=4294967296;return new c(t,0)}var l=o(0),u=o(1),d=o(16777216);function f(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function g(e){return-1==e.h}function m(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new c(n,~e.h).add(u)}function p(e,t){return e.add(m(t))}function y(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function v(e,t){this.g=e,this.h=t}function w(e,t){if(f(t))throw Error("division by zero");if(f(e))return new v(l,l);if(g(e))return t=w(m(e),t),new v(m(t.g),m(t.h));if(g(t))return t=w(e,m(t)),new v(m(t.g),t.h);if(30<e.g.length){if(g(e)||g(t))throw Error("slowDivide_ only works with positive integers.");for(var n=u,r=t;r.l(e)<=0;)n=_(n),r=_(r);for(var i=b(n,1),s=b(r,1),r=b(r,2),n=b(n,2);!f(r);){var a=s.add(r);a.l(e)<=0&&(i=i.add(n),s=a),r=b(r,1),n=b(n,1)}return t=p(e,i.j(t)),new v(i,t)}for(i=l;0<=e.l(t);){for(n=Math.max(1,Math.floor(e.m()/t.m())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=h(n)).j(t);g(a)||0<a.l(e);)a=(s=h(n-=r)).j(t);f(s)&&(s=u),i=i.add(s),e=p(e,a)}return new v(i,e)}function _(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.i(r)<<1|e.i(r-1)>>>31;return new c(n,e.h)}function b(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.i(s+n)>>>t|e.i(s+n+1)<<32-t:e.i(s+n);return new c(i,e.h)}(e=c.prototype).m=function(){if(g(this))return-m(this).m();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(f(this))return"0";if(g(this))return"-"+m(this).toString(e);for(var t=h(Math.pow(e,6)),n=this,r="";;){var i=w(n,t).g,s=((0<(n=p(n,i.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(f(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return g(e=p(this,e))?-1:f(e)?0:1},e.abs=function(){return g(this)?m(this):this},e.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.i(i))+(65535&e.i(i)),a=(s>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new c(n,-2147483648&n[n.length-1]?-1:0)},e.j=function(e){if(f(this)||f(e))return l;if(g(this))return g(e)?m(this).j(m(e)):m(m(this).j(e));if(g(e))return m(this.j(m(e)));if(this.l(d)<0&&e.l(d)<0)return h(this.m()*e.m());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.i(r)>>>16,a=65535&this.i(r),o=e.i(i)>>>16,u=65535&e.i(i);n[2*r+2*i]+=a*u,y(n,2*r+2*i),n[2*r+2*i+1]+=s*u,y(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,y(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,y(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new c(n,0)},e.A=function(e){return w(this,e).h},e.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)&e.i(r);return new c(n,this.h&e.h)},e.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)|e.i(r);return new c(n,this.h|e.h)},e.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)^e.i(r);return new c(n,this.h^e.h)},n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,T=n,c.prototype.multiply=c.prototype.j,c.prototype.modulo=c.prototype.A,c.prototype.compare=c.prototype.l,c.prototype.toNumber=c.prototype.m,c.prototype.getBits=c.prototype.i,c.fromNumber=h,c.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return m(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=h(Math.pow(n,8)),i=l,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n),i=a<8?(a=h(Math.pow(n,a)),i.j(a).add(h(o))):(i=i.j(r)).add(h(o));return i},E=c}).apply(void 0!==S?S:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var dn,fn,gn,mn,pn,yn,vn,wn,_n,x,D,C,bn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!(function(){var e,s="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};var a=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof bn&&bn];for(var t=0;t<e.length;++t){var n=e[t];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);!function(e,t){if(t)e:{var n=a;e=e.split(".");for(var r=0;r<e.length-1;r++){var i=e[r];if(!(i in n))break e;n=n[i]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&s(n,e,{configurable:!0,writable:!0,value:t})}}("Array.prototype.values",function(e){return e||function(){return function(t,n){t instanceof String&&(t+="");var r=0,i=!1,e={next:function(){if(!i&&r<t.length){var e=r++;return{value:n(e,t[e]),done:!1}}return{done:i=!0,value:void 0}}};return e[Symbol.iterator]=function(){return e},e}(this,function(e,t){return t})}});var o=o||{},T=this||self;function u(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function c(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function r(e,t,n){return e.call.apply(e.bind,arguments)}function i(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function p(e,t,n){return(p=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?r:i).apply(null,arguments)}function h(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function t(e,s){function t(){}t.prototype=s.prototype,e.aa=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Qb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function l(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function n(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(u(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function S(e){return/^[\s\xa0]*$/.test(e)}function d(){var e=T.navigator;return(e=e&&e.userAgent)?e:""}function f(e){return f[" "](e),e}f[" "]=function(){};var g=!(-1==d().indexOf("Gecko")||-1!=d().toLowerCase().indexOf("webkit")&&-1==d().indexOf("Edge")||-1!=d().indexOf("Trident")||-1!=d().indexOf("MSIE")||-1!=d().indexOf("Edge"));function m(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function y(e){const t={};for(const n in e)t[n]=e[n];return t}const v="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function w(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<v.length;e++)n=v[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}var _=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new b,e=>e.reset());class b{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let I,E=!1,x=new class{constructor(){this.h=this.g=null}add(e,t){const n=_.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},D=()=>{const e=T.Promise.resolve(void 0);I=()=>{e.then(C)}};var C=()=>{for(var e;e=function(){var e=x;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){T.setTimeout(()=>{throw e},0)}(e)}var t=_;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}E=!1};function A(){this.s=this.s,this.C=this.C}function N(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}A.prototype.s=!1,A.prototype.ma=function(){this.s||(this.s=!0,this.N())},A.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},N.prototype.h=function(){this.defaultPrevented=!0};var k=function(){if(!T.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var n=()=>{};T.addEventListener("test",n,t),T.removeEventListener("test",n,t)}catch(e){}return e}();function R(e,t){if(N.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(g){e:{try{f(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:M[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&R.aa.h.call(this)}}t(R,N);var M={2:"touch",3:"pen",4:"mouse"};R.prototype.h=function(){R.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var L="closure_listenable_"+(1e6*Math.random()|0),O=0;function F(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++O,this.da=this.fa=!1}function P(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function V(e){this.src=e,this.g={},this.h=0}function U(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Array.prototype.indexOf.call(n,t,void 0)))&&Array.prototype.splice.call(n,r,1),i&&(P(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function B(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}V.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=B(e,t,r,i);return-1<a?(t=e[a],n||(t.fa=!1)):((t=new F(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var q="closure_lm_"+(1e6*Math.random()|0),j={};function G(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Y(r);return t&&t[L]?t.L(n,r,c(i)?!!i.capture:!!i,s):z(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)G(e,t[s],n,r,i);return null}return n=Y(n),e&&e[L]?e.K(t,n,c(r)?!!r.capture:!!r,i):z(e,t,n,!1,r,i)}function z(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=c(i)?!!i.capture:!!i,o=H(e);if(o||(e[q]=o=new V(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=Q;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!k?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent($(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function K(e){var t,n,r;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[L]?U(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent($(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=H(t))?(U(n,e),0==n.h&&(n.src=null,t[q]=null)):P(e)))}function $(e){return e in j?j[e]:j[e]="on"+e}function Q(e,t){var n,r;return e=!!e.da||(t=new R(t,this),n=e.listener,r=e.ha||e.src,e.fa&&K(e),n.call(r,t))}function H(e){return(e=e[q])instanceof V?e:null}var W="__closure_events_fn_"+(1e9*Math.random()>>>0);function Y(t){return"function"==typeof t?t:(t[W]||(t[W]=function(e){return t.handleEvent(e)}),t[W])}function J(){A.call(this),this.i=new V(this),(this.M=this).F=null}function X(e,t){var n,r=e.F;if(r)for(n=[];r;r=r.F)n.push(r);if(e=e.M,r=t.type||t,"string"==typeof t?t=new N(t,e):t instanceof N?t.target=t.target||e:(a=t,w(t=new N(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Z(s,r,!0,t)&&a;if(a=Z(s=t.g=e,r,!0,t)&&a,a=Z(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Z(s=t.g=n[i],r,!1,t)&&a}function Z(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,u=t[s];u&&!u.da&&u.capture==n&&(a=u.listener,o=u.ha||u.src,u.fa&&U(e.i,u),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}function ee(e,t,n){if("function"==typeof e)n&&(e=p(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=p(e.handleEvent,e)}return 2147483647<Number(t)?-1:T.setTimeout(e,t||0)}t(J,A),J.prototype[L]=!0,J.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=c(i)?!!i.capture:!!i,r=Y(r),t&&t[L]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=B(a=t.g[n],r,i,s))&&(P(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&H(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?B(n,r,i,s):t)?n[t]:null)&&K(r))}(this,e,t,n,r)},J.prototype.N=function(){if(J.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)P(n[r]);delete t.g[e],t.h--}}this.F=null},J.prototype.K=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},J.prototype.L=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};class te extends A{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=ee(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.l);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}N(){super.N(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ne(e){A.call(this),this.h=e,this.g={}}t(ne,A);var re=[];function ie(e){m(e.g,function(e,t){this.g.hasOwnProperty(t)&&K(e)},e),e.g={}}ne.prototype.N=function(){ne.aa.N.call(this),ie(this)},ne.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var se=T.JSON.stringify,ae=T.JSON.parse,oe=class{stringify(e){return T.JSON.stringify(e,void 0)}parse(e){return T.JSON.parse(e,void 0)}};function ue(){}function ce(e){return e.h||(e.h=e.i())}function he(){}ue.prototype.h=null;var le={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function de(){N.call(this,"d")}function fe(){N.call(this,"c")}t(de,N),t(fe,N);var ge={},me=null;function pe(){return me=me||new J}function ye(e){N.call(this,ge.La,e)}function ve(){var e=pe();X(e,new ye(e))}function we(e,t){N.call(this,ge.STAT_EVENT,e),this.stat=t}function _e(e){var t=pe();X(t,new we(t,e))}function be(e,t){N.call(this,ge.Ma,e),this.size=t}function Ie(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return T.setTimeout(function(){e()},t)}function Ee(){this.g=!0}function Te(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return se(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}ge.La="serverreachability",t(ye,N),ge.STAT_EVENT="statevent",t(we,N),ge.Ma="timingevent",t(be,N),Ee.prototype.xa=function(){this.g=!1},Ee.prototype.info=function(){};var Se={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},xe={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function De(){}function Ce(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new ne(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Ae}function Ae(){this.i=null,this.g="",this.h=!1}t(De,ue),De.prototype.g=function(){return new XMLHttpRequest},De.prototype.i=function(){return{}};var Ne=new De,ke={},Re={};function Me(e,t,n){e.L=1,e.v=it(Ze(t)),e.m=n,e.P=!0,Le(e,null)}function Le(e,t){e.F=Date.now(),Fe(e),e.A=Ze(e.v);var n=e.A,r=e.R;Array.isArray(r)||(r=[String(r)]),vt(n.i,"t",r),e.C=0,n=e.j.J,e.h=new Ae,e.g=sn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new te(p(e.Y,e,e.g),e.O)),t=e.U;var n=e.g,r=e.ca,i="readystatechange";Array.isArray(i)||(i&&(re[0]=i.toString()),i=re);for(var a,o,u,c,h,l,s=0;s<i.length;s++){var d=G(n,i[s],r||t.handleEvent,!1,t.h||t);if(!d)break;t.g[d.key]=d}t=e.H?y(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),ve(),a=e.i,o=e.u,u=e.A,c=e.l,h=e.R,l=e.m,a.info(function(){if(a.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+h+"]: "+o+"\n"+u+"\n"+e})}function Oe(e){return e.g&&("GET"==e.u&&2!=e.L&&e.j.Ca)}function Fe(e){e.S=Date.now()+e.I,Pe(e,e.I)}function Pe(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Ie(p(e.ba,e),t)}function Ve(e){e.B&&(T.clearTimeout(e.B),e.B=null)}function Ue(e){0==e.j.G||e.J||Zt(e.j,e)}function Be(e){Ve(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,ie(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function qe(e,t){try{var n=e.j;if(0!=n.G&&(n.g==e||$e(n.h,e)))if(!e.K&&$e(n.h,e)&&3==n.G){try{var r=n.Da.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Xt(n),jt(n)}Wt(n),_e(18)}}else n.za=i[1],0<n.za-n.T&&i[2]<37500&&n.F&&0==n.v&&!n.C&&(n.C=Ie(p(n.Za,n),6e3));if(Ke(n.h)<=1&&n.ca){try{n.ca()}catch(e){}n.ca=void 0}}else tn(n,11)}else if(!e.K&&n.g!=e||Xt(n),!S(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.T=s[0],s=s[1],2==n.G)if("c"==s[0]){n.K=s[1],n.ia=s[2];var a=s[3];null!=a&&(n.la=a,n.j.info("VER="+n.la));var o=s[4];null!=o&&(n.Aa=o,n.j.info("SVER="+n.Aa));var u,c,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.L=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;if(g){const m=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null;m&&((u=r.h).g||-1==m.indexOf("spdy")&&-1==m.indexOf("quic")&&-1==m.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(Qe(u,u.h),u.h=null))),!r.D||(c=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.ya=c,rt(r.I,r.D,c))}n.G=3,n.l&&n.l.ua(),n.ba&&(n.R=Date.now()-e.F,n.j.info("Handshake RTT: "+n.R+"ms"));var l,d,f=e;(r=n).qa=rn(r,r.J?r.ia:null,r.W),f.K?(He(r.h,f),l=f,(d=r.L)&&(l.I=d),l.B&&(Ve(l),Fe(l)),r.g=f):Ht(r),0<n.i.length&&zt(n)}else"stop"!=s[0]&&"close"!=s[0]||tn(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?tn(n,7):qt(n):"noop"!=s[0]&&n.l&&n.l.ta(s),n.v=0)}ve()}catch(e){}}Ce.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Pt(e)?t.j():this.Y(e)},Ce.prototype.Y=function(e){try{if(e==this.g)e:{var t=Pt(this.g),n=this.g.Ba();this.g.Z();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.oa()||Vt(this.g)))){this.J||4!=t||7==n||ve(),Ve(this);var r=this.g.Z();this.X=r;t:if(Oe(this)){var i=Vt(this.g);e="";var s=i.length,a=4==Pt(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Be(this),Ue(this);var o="";break t}this.h.i=new T.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:!(a&&n==s-1)});i.length=0,this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.oa();if(this.o=200==r,y=this.i,v=this.u,w=this.A,_=this.l,b=this.R,I=t,E=r,y.info(function(){return"XMLHTTP RESP ("+_+") [ attempt "+b+"]: "+v+"\n"+w+"\n"+I+" "+E}),this.o){if(this.T&&!this.K){t:{if(this.g){var u,c=this.g;if((u=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!S(u)){var h=u;break t}}h=null}if(!(r=h)){this.o=!1,this.s=3,_e(12),Be(this),Ue(this);break e}Te(this.i,this.l,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,qe(this,r)}if(this.P){for(var l,d,r=!0;!this.J&&this.C<o.length;){if(g=o,p=m=void 0,m=(f=this).C,(l=-1==(p=g.indexOf("\n",m))?Re:(m=Number(g.substring(m,p)),isNaN(m)?ke:(p+=1)+m>g.length?Re:(g=g.slice(p,p+m),f.C=p+m,g)))==Re){4==t&&(this.s=4,_e(14),r=!1),Te(this.i,this.l,null,"[Incomplete Response]");break}if(l==ke){this.s=4,_e(15),Te(this.i,this.l,o,"[Invalid Chunk]"),r=!1;break}Te(this.i,this.l,l,null),qe(this,l)}Oe(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=o.length||this.h.h||(this.s=1,_e(16),r=!1),this.o=this.o&&r,r?0<o.length&&!this.W&&(this.W=!0,(d=this.j).g==this&&d.ba&&!d.M&&(d.j.info("Great, no buffering proxy detected. Bytes received: "+o.length),Yt(d),d.M=!0,_e(11))):(Te(this.i,this.l,o,"[Invalid Chunked Response]"),Be(this),Ue(this))}else Te(this.i,this.l,o,null),qe(this,o);4==t&&Be(this),this.o&&!this.J&&(4==t?Zt(this.j,this):(this.o=!1,Fe(this)))}else(function(e){const t={};e=(e.g&&2<=Pt(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!S(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<o.indexOf("Unknown SID")?(this.s=3,_e(12)):(this.s=0,_e(13)),Be(this),Ue(this)}}}catch(e){}var f,g,m,p,y,v,w,_,b,I,E},Ce.prototype.cancel=function(){this.J=!0,Be(this)},Ce.prototype.ba=function(){this.B=null;var e,t,n=Date.now();0<=n-this.S?(e=this.i,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(ve(),_e(17)),Be(this),this.s=2,Ue(this)):Pe(this,this.S-n)};var je=class{constructor(e,t){this.g=e,this.map=t}};function Ge(e){this.l=e||10,e=T.PerformanceNavigationTiming?0<(e=T.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(T.chrome&&T.chrome.loadTimes&&T.chrome.loadTimes()&&T.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function ze(e){return e.h||e.g&&e.g.size>=e.j}function Ke(e){return e.h?1:e.g?e.g.size:0}function $e(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Qe(e,t){e.g?e.g.add(t):e.h=t}function He(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function We(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return l(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function Ye(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(u(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(u(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(u(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}Ge.prototype.cancel=function(){if(this.i=We(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var Je=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Xe(e){var t,n;this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof Xe?(this.h=e.h,et(this,e.j),this.o=e.o,this.g=e.g,tt(this,e.s),this.l=e.l,t=e.i,(n=new gt).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),nt(this,n),this.m=e.m):e&&(t=String(e).match(Je))?(this.h=!1,et(this,t[1]||"",!0),this.o=st(t[2]||""),this.g=st(t[3]||"",!0),tt(this,t[4]),this.l=st(t[5]||"",!0),nt(this,t[6]||"",!0),this.m=st(t[7]||"")):(this.h=!1,this.i=new gt(null,this.h))}function Ze(e){return new Xe(e)}function et(e,t,n){e.j=n?st(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function tt(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.s=t}else e.s=null}function nt(e,t,n){var r,i;t instanceof gt?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(mt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(pt(this,t),vt(this,n,e))},r)),r.j=i):(n||(t=at(t,dt)),e.i=new gt(t,e.h))}function rt(e,t,n){e.i.set(t,n)}function it(e){return rt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function st(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function at(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,ot),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function ot(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Xe.prototype.toString=function(){var e=[],t=this.j;t&&e.push(at(t,ct,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(at(t,ct,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.s)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(at(n,"/"==n.charAt(0)?lt:ht,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",at(n,ft)),e.join("")};var ut,ct=/[#\/\?@]/g,ht=/[#\?:]/g,lt=/[#\?]/g,dt=/[#\?@]/g,ft=/#/g;function gt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function mt(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function pt(e,t){mt(e),t=wt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function yt(e,t){return mt(e),t=wt(e,t),e.g.has(t)}function vt(e,t,n){pt(e,t),0<n.length&&(e.i=null,e.g.set(wt(e,t),l(n)),e.h+=n.length)}function wt(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function _t(e,t,n,r,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),r(n)}catch(e){}}function bt(){this.g=new oe}function It(e){this.l=e.Ub||null,this.j=e.eb||!1}function Et(e,t){J.call(this),this.D=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Tt(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function St(e){e.readyState=4,e.l=null,e.j=null,e.v=null,xt(e)}function xt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Dt(e){let n="";return m(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Ct(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Dt(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):rt(e,t,n))}function At(e){J.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(e=gt.prototype).add=function(e,t){mt(this),this.i=null,e=wt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},e.forEach=function(n,r){mt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},e.na=function(){mt(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},e.V=function(t){mt(this);let n=[];if("string"==typeof t)yt(this,t)&&(n=n.concat(this.g.get(wt(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},e.set=function(e,t){return mt(this),this.i=null,yt(this,e=wt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},e.get=function(e,t){return e&&0<(e=this.V(e)).length?String(e[0]):t},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.V(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")},t(It,ue),It.prototype.g=function(){return new Et(this.l,this.j)},It.prototype.i=(ut={},function(){return ut}),t(Et,J),(e=Et.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,xt(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||T).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,St(this)),this.readyState=0},e.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,xt(this)),this.g&&(this.readyState=3,xt(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==T.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Tt(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=function(e){var t;this.g&&(this.o&&e.value?this.response.push(e.value):this.o||(t=e.value||new Uint8Array(0),(t=this.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?St:xt)(this),3==this.readyState&&Tt(this))},e.Ra=function(e){this.g&&(this.response=this.responseText=e,St(this))},e.Qa=function(e){this.g&&(this.response=e,St(this))},e.ga=function(){this.g&&St(this)},e.setRequestHeader=function(e,t){this.u.append(e,t)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Et.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),t(At,J);var Nt=/^https?$/i,kt=["POST","PUT"];function Rt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,Mt(e),Ot(e)}function Mt(e){e.A||(e.A=!0,X(e,"complete"),X(e,"error"))}function Lt(e){if(e.h&&void 0!==o&&(!e.v[1]||4!=Pt(e)||2!=e.Z()))if(e.u&&4==Pt(e))ee(e.Ea,0,e);else if(X(e,"readystatechange"),4==Pt(e)){e.h=!1;try{var t,n,r,i=e.Z();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.D).match(Je)[1]||null)&&T.self&&T.self.location&&(r=T.self.location.protocol.slice(0,-1)),n=!Nt.test(r?r.toLowerCase():"")),t=n),t)X(e,"complete"),X(e,"success");else{e.m=6;try{var a=2<Pt(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",Mt(e)}}finally{Ot(e)}}}function Ot(e,t){if(e.g){Ft(e);const n=e.g,r=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||X(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Ft(e){e.I&&(T.clearTimeout(e.I),e.I=null)}function Pt(e){return e.g?e.g.readyState:0}function Vt(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.H){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Ut(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Bt(e){this.Aa=0,this.i=[],this.j=new Ee,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Ut("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Ut("baseRetryDelayMs",5e3,e),this.cb=Ut("retryDelaySeedMs",1e4,e),this.Wa=Ut("forwardChannelMaxRetries",2,e),this.wa=Ut("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new Ge(e&&e.concurrentRequestLimit),this.Da=new bt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function qt(e){if(Gt(e),3==e.G){var t=e.U++,n=Ze(e.I);if(rt(n,"SID",e.K),rt(n,"RID",t),rt(n,"TYPE","terminate"),$t(e,n),(t=new Ce(e,e.j,t)).L=2,t.v=it(Ze(n)),n=!1,T.navigator&&T.navigator.sendBeacon)try{n=T.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&T.Image&&((new Image).src=t.v,n=!0),n||(t.g=sn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Fe(t)}nn(e)}function jt(e){e.g&&(Yt(e),e.g.cancel(),e.g=null)}function Gt(e){jt(e),e.u&&(T.clearTimeout(e.u),e.u=null),Xt(e),e.h.cancel(),e.s&&("number"==typeof e.s&&T.clearTimeout(e.s),e.s=null)}function zt(e){var t;ze(e.h)||e.s||(e.s=!0,t=e.Ga,I||D(),E||(I(),E=!0),x.add(t,e),e.B=0)}function Kt(e,t){var n=t?t.l:e.U++,r=Ze(e.I);rt(r,"SID",e.K),rt(r,"RID",n),rt(r,"AID",e.T),$t(e,r),e.m&&e.o&&Ct(r,e.m,e.o),n=new Ce(e,e.j,n,e.B+1),null===e.m&&(n.H=e.o),t&&(e.i=t.D.concat(e.i)),t=Qt(e,n,1e3),n.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),Qe(e.h,n),Me(n,r,t)}function $t(e,n){e.H&&m(e.H,function(e,t){rt(n,t,e)}),e.l&&Ye({},function(e,t){rt(n,t,e)})}function Qt(e,t,r){r=Math.min(e.i.length,r);var i=e.l?p(e.l.Na,e.l,e):null;e:{var s=e.i;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=s[0].g,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].g,o=s[t].map;if((a-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Ye(e,function(e,t){let n=e;c(e)&&(n=se(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=u.join("&");break e}}}return e=e.i.splice(0,r),t.D=e,i}function Ht(e){var t;e.g||e.u||(e.Y=1,t=e.Fa,I||D(),E||(I(),E=!0),x.add(t,e),e.v=0)}function Wt(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=Ie(p(e.Fa,e),en(e,e.v)),e.v++,1)}function Yt(e){null!=e.A&&(T.clearTimeout(e.A),e.A=null)}function Jt(e){e.g=new Ce(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=Ze(e.qa);rt(t,"RID","rpc"),rt(t,"SID",e.K),rt(t,"AID",e.T),rt(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&rt(t,"TO",e.ja),rt(t,"TYPE","xmlhttp"),$t(e,t),e.m&&e.o&&Ct(t,e.m,e.o),e.L&&(e.g.I=e.L);var n=e.g;e=e.ia,n.L=1,n.v=it(Ze(t)),n.m=null,n.P=!0,Le(n,e)}function Xt(e){null!=e.C&&(T.clearTimeout(e.C),e.C=null)}function Zt(e,t){var n,r,i,s=null;if(e.g==t){Xt(e),Yt(e),e.g=null;var a=2}else{if(!$e(e.h,t))return;s=t.D,He(e.h,t),a=1}if(0!=e.G)if(t.o)1==a?(s=t.m?t.m.length:0,t=Date.now()-t.F,n=e.B,X(a=pe(),new be(a,s)),zt(e)):Ht(e);else if(3==(n=t.s)||0==n&&0<t.X||(1!=a||(i=t,Ke((r=e).h)>=r.h.j-(r.s?1:0)||(r.s?(r.i=i.D.concat(r.i),0):1==r.G||2==r.G||r.B>=(r.Va?0:r.Wa)||(r.s=Ie(p(r.Ga,r,i),en(r,r.B)),r.B++,0))))&&(2!=a||!Wt(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),n){case 1:tn(e,5);break;case 4:tn(e,10);break;case 3:tn(e,6);break;default:tn(e,2)}}function en(e,t){let n=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(n*=2),n*t}function tn(e,t){var n,r,i;e.j.info("Error code "+t),2==t?(n=p(e.fb,e),r=!(i=e.Xa),i=new Xe(i||"//www.google.com/images/cleardot.gif"),T.location&&"http"==T.location.protocol||et(i,"https"),it(i),(r?function(e,t){var n=new Ee;if(T.Image){const r=new Image;r.onload=h(_t,n,"TestLoadImage: loaded",!0,t,r),r.onerror=h(_t,n,"TestLoadImage: error",!1,t,r),r.onabort=h(_t,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=h(_t,n,"TestLoadImage: timeout",!1,t,r),T.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}:function(e,t){const n=new Ee,r=new AbortController,i=setTimeout(()=>{r.abort(),_t(n,0,!1,t)},1e4);fetch(e,{signal:r.signal}).then(e=>{clearTimeout(i),e.ok?_t(n,0,!0,t):_t(n,0,!1,t)}).catch(()=>{clearTimeout(i),_t(n,0,!1,t)})})(i.toString(),n)):_e(2),e.G=0,e.l&&e.l.sa(t),nn(e),Gt(e)}function nn(e){var t;e.G=0,e.ka=[],e.l&&(0==(t=We(e.h)).length&&0==e.i.length||(n(e.ka,t),n(e.ka,e.i),e.h.i.length=0,l(e.i),e.i.length=0),e.l.ra())}function rn(e,t,n){var r,i,s=n instanceof Xe?Ze(n):new Xe(n);return""!=s.g?(t&&(s.g=t+"."+s.g),tt(s,s.s)):(s=(r=T.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new Xe(null),s&&et(i,s),t&&(i.g=t),r&&tt(i,r),n&&(i.l=n),s=i),n=e.D,t=e.ya,n&&t&&rt(s,n,t),rt(s,"VER",e.la),$t(e,s),s}function sn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new At(new It({eb:n})):new At(e.pa)).Ha(e.J),t}function an(){}function on(){}function un(e,t){J.call(this),this.g=new Bt(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!S(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!S(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new ln(this)}function cn(e){de.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function hn(){fe.call(this),this.status=1}function ln(e){this.g=e}(e=At.prototype).Ha=function(e){this.J=e},e.ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=(this.o||Ne).g(),this.v=this.o?ce(this.o):ce(Ne),this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void Rt(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const o of r.keys())n.set(o,r.get(o))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=T.FormData&&e instanceof T.FormData,0<=Array.prototype.indexOf.call(kt,t,void 0)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Ft(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){Rt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,X(this,"complete"),X(this,"abort"),Ot(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Ot(this,!0)),At.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?Lt(this):this.bb())},e.bb=function(){Lt(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2<Pt(this)?this.g.status:-1}catch(e){return-1}},e.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.Oa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),ae(t)}},e.Ba=function(){return this.m},e.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=Bt.prototype).la=8,e.G=1,e.connect=function(e,t,n,r){_e(0),this.W=e,this.H=t||{},n&&void 0!==r&&(this.H.OSID=n,this.H.OAID=r),this.F=this.X,this.I=rn(this,null,this.W),zt(this)},e.Ga=function(t){if(this.s)if(this.s=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;const s=new Ce(this,this.j,t);let e=this.o;if(this.S&&(e?(e=y(e),w(e,this.S)):e=this.S),null!==this.m||this.O||(s.H=e,e=null),this.P)e:{for(var n=0,r=0;r<this.i.length;r++){var i=this.i[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.i.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Qt(this,s,n),rt(r=Ze(this.I),"RID",t),rt(r,"CVER",22),this.D&&rt(r,"X-HTTP-Session-Id",this.D),$t(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(Dt(e)))+"&"+n:this.m&&Ct(r,this.m,e)),Qe(this.h,s),this.Ua&&rt(r,"TYPE","init"),this.P?(rt(r,"$req",n),rt(r,"SID","null"),s.T=!0,Me(s,r,null)):Me(s,r,n),this.G=2}}else 3==this.G&&(t?Kt(this,t):0==this.i.length||ze(this.h)||Kt(this))},e.Fa=function(){var e;this.u=null,Jt(this),this.ba&&!(this.M||null==this.g||this.R<=0)&&(e=2*this.R,this.j.info("BP detection timer enabled: "+e),this.A=Ie(p(this.ab,this),e))},e.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,_e(10),jt(this),Jt(this))},e.Za=function(){null!=this.C&&(this.C=null,jt(this),Wt(this),_e(19))},e.fb=function(e){e?(this.j.info("Successfully pinged google.com"),_e(2)):(this.j.info("Failed to ping google.com"),_e(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=an.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},on.prototype.g=function(e,t){return new un(e,t)},t(un,J),un.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},un.prototype.close=function(){qt(this.g)},un.prototype.o=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.u&&((t={}).__data__=se(e),e=t),n.i.push(new je(n.Ya++,e)),3==n.G&&zt(n)},un.prototype.N=function(){this.g.l=null,delete this.j,qt(this.g),delete this.g,un.aa.N.call(this)},t(cn,de),t(hn,fe),t(ln,an),ln.prototype.ua=function(){X(this.g,"a")},ln.prototype.ta=function(e){X(this.g,new cn(e))},ln.prototype.sa=function(e){X(this.g,new hn)},ln.prototype.ra=function(){X(this.g,"b")},on.prototype.createWebChannel=on.prototype.g,un.prototype.send=un.prototype.o,un.prototype.open=un.prototype.m,_n=function(){return new on},wn=pe,vn=ge,yn={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Se.NO_ERROR=0,Se.TIMEOUT=8,Se.HTTP_ERROR=6,pn=Se,xe.COMPLETE="complete",mn=xe,(he.EventType=le).OPEN="a",le.CLOSE="b",le.ERROR="c",le.MESSAGE="d",J.prototype.listen=J.prototype.K,gn=he,fn=It,At.prototype.listenOnce=At.prototype.L,At.prototype.getLastError=At.prototype.Ka,At.prototype.getLastErrorCode=At.prototype.Ba,At.prototype.getStatus=At.prototype.Z,At.prototype.getResponseJson=At.prototype.Oa,At.prototype.getResponseText=At.prototype.oa,At.prototype.send=At.prototype.ea,At.prototype.setWithCredentials=At.prototype.Ha,dn=At}).apply(void 0!==bn?bn:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});const A="@firebase/firestore",N="4.6.1-dataconnect-preview.42eb5e521";class k{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}k.UNAUTHENTICATED=new k(null),k.GOOGLE_CREDENTIALS=new k("google-credentials-uid"),k.FIRST_PARTY=new k("first-party-uid"),k.MOCK_USER=new k("mock-user");let R="10.11.1-dataconnect-preview.42eb5e521";const M=new class{constructor(e){this.name=e,this._logLevel=_,this._logHandler=I,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in l))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?w[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,l.DEBUG,...e),this._logHandler(this,l.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,l.VERBOSE,...e),this._logHandler(this,l.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,l.INFO,...e),this._logHandler(this,l.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,l.WARN,...e),this._logHandler(this,l.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,l.ERROR,...e),this._logHandler(this,l.ERROR,...e)}}("@firebase/firestore");function L(){return M.logLevel}function O(e,...t){var n;M.logLevel<=l.DEBUG&&(n=t.map(V),M.debug(`Firestore (${R}): ${e}`,...n))}function F(e,...t){var n;M.logLevel<=l.ERROR&&(n=t.map(V),M.error(`Firestore (${R}): ${e}`,...n))}function P(e,...t){var n;M.logLevel<=l.WARN&&(n=t.map(V),M.warn(`Firestore (${R}): ${e}`,...n))}function V(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function U(e="Unexpected state"){var t=`FIRESTORE (${R}) INTERNAL ASSERTION FAILED: `+e;throw F(t),new Error(t)}function B(e){e||U()}const q={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 j extends d{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class G{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class z{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class K{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(k.UNAUTHENTICATED))}shutdown(){}}class ${constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Q{constructor(e){this.t=e,this.currentUser=k.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new G;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new G,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{O("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(O("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new G))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(O("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(B("string"==typeof e.accessToken),new z(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return B(null===e||"string"==typeof e),new k(e)}}class H{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=k.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class W{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new H(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(k.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Y{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class J{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){const r=e=>{null!=e.error&&O("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,O("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{O("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):O("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(B("string"==typeof e.token),this.R=e.token,new Y(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class X{static newId(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Z(e,t){return e<t?-1:t<e?1:0}function ee(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function te(e){return e+"\0"}class ne{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new j(q.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new j(q.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new j(q.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new j(q.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ne.fromMillis(Date.now())}static fromDate(e){return ne.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ne(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Z(this.nanoseconds,e.nanoseconds):Z(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class re{constructor(e){this.timestamp=e}static fromTimestamp(e){return new re(e)}static min(){return new re(new ne(0,0))}static max(){return new re(new ne(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class ie{constructor(e,t,n){void 0===t?t=0:t>e.length&&U(),void 0===n?n=e.length-t:n>e.length-t&&U(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ie.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ie?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class se extends ie{construct(e,t,n){return new se(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new j(q.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new se(t)}static emptyPath(){return new se([])}}const ae=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class oe extends ie{construct(e,t,n){return new oe(e,t,n)}static isValidIdentifier(e){return ae.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!oe.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new oe(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new j(q.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new j(q.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new j(q.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new j(q.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new oe(t)}static emptyPath(){return new oe([])}}class ue{constructor(e){this.path=e}static fromPath(e){return new ue(se.fromString(e))}static fromName(e){return new ue(se.fromString(e).popFirst(5))}static empty(){return new ue(se.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===se.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return se.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ue(new se(e.slice()))}}class ce{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function he(e){return e.fields.find(e=>2===e.kind)}function le(e){return e.fields.filter(e=>2!==e.kind)}ce.UNKNOWN_ID=-1;class de{constructor(e,t){this.fieldPath=e,this.kind=t}}class fe{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new fe(0,pe.min())}}function ge(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=re.fromTimestamp(1e9===r?new ne(n+1,0):new ne(n,r));return new pe(r,ue.empty(),t)}function me(e){return new pe(e.readTime,e.key,-1)}class pe{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new pe(re.min(),ue.empty(),-1)}static max(){return new pe(re.max(),ue.empty(),-1)}}function ye(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ue.comparator(e.documentKey,t.documentKey),0!==n?n:Z(e.largestBatchId,t.largestBatchId))}const ve="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class we{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function _e(e){if(e.code!==q.FAILED_PRECONDITION||e.message!==ve)throw e;O("LocalStore","Unexpectedly lost primary lease")}class be{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&U(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new be((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof be?t:be.resolve(t)}catch(e){return be.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):be.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):be.reject(t)}static resolve(n){return new be((e,t)=>{e(n)})}static reject(n){return new be((e,t)=>{t(n)})}static waitFor(e){return new be((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=be.resolve(!1);for(const n of e)t=t.next(e=>e?be.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,u){return new be((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;u(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new be((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class Ie{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.V=new G,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{e.error?this.V.reject(new xe(n,e.error)):this.V.resolve()},this.transaction.onerror=e=>{var t=ke(e.target.error);this.V.reject(new xe(n,t))}}static open(e,t,n,r){try{return new Ie(t,e.transaction(r,n))}catch(e){throw new xe(t,e)}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(O("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Ce(t)}}class Ee{constructor(e,t,n){this.name=e,this.version=t,this.p=n,12.2===Ee.S(u())&&F("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return O("SimpleDb","Removing database:",e),Ae(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(Ee.C())return!0;const e=u(),t=Ee.S(e),n=0<t&&t<10,r=Te(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static C(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.__PRIVATE_env)||void 0===e?void 0:e.v)}static F(e,t){return e.store(t)}static S(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}async M(s){return this.db||(O("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new xe(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new j(q.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new j(q.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new xe(s,t))},i.onupgradeneeded=e=>{O("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.p.O(t,i.transaction,e.oldVersion,this.version).next(()=>{O("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(t){this.N=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.M(e);const t=Ie.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.g(),e)).catch(e=>(t.abort(e),be.reject(e))).toPromise();return s.catch(()=>{}),await t.m,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(O("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function Te(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}class Se{constructor(e){this.B=e,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(e){this.B=e}done(){this.k=!0}$(e){this.q=e}delete(){return Ae(this.B.delete())}}class xe extends j{constructor(e,t){super(q.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function De(e){return"IndexedDbTransactionError"===e.name}class Ce{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(O("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(O("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),Ae(n)}add(e){return O("SimpleDb","ADD",this.store.name,e,e),Ae(this.store.add(e))}get(t){return Ae(this.store.get(t)).next(e=>(O("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return O("SimpleDb","DELETE",this.store.name,e),Ae(this.store.delete(e))}count(){return O("SimpleDb","COUNT",this.store.name),Ae(this.store.count())}U(e,n){const t=this.options(e,n),r=t.index?this.store.index(t.index):this.store;if("function"==typeof r.getAll){const e=r.getAll(t.range);return new be((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{const e=this.cursor(t),n=[];return this.W(e,(e,t)=>{n.push(t)}).next(()=>n)}}G(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new be((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}j(e,t){O("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.H=!1;var r=this.cursor(n);return this.W(r,(e,t,n)=>n.delete())}J(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.W(r,t)}Y(i){const e=this.cursor({});return new be((n,r)=>{e.onerror=e=>{var t=ke(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}W(e,s){const a=[];return new be((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new Se(t),r=s(t.primaryKey,t.value,n);if(r instanceof be){const e=r.catch(e=>(n.done(),be.reject(e)));a.push(e)}n.isDone?i():null===n.K?t.continue():t.continue(n.K)}else i()}}).next(()=>be.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.H?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Ae(e){return new be((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=ke(e.target.error);r(t)}})}let Ne=!1;function ke(e){const t=Ee.S(u());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new j("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Ne||(Ne=!0,setTimeout(()=>{throw e},0)),e}}return e}class Re{constructor(e,t){this.asyncQueue=e,this.Z=t,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){O("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{O("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){De(e)?O("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await _e(e)}await this.X(6e4)})}}class Me{constructor(e,t){this.localStore=e,this.persistence=t}async ee(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.te(e,t))}te(e,t){const n=new Set;let r=t,i=!0;return be.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(O("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ne(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.re(n,e)).next(e=>(O("IndexBackfiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}re(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=me(t);0<ye(n,r)&&(r=n)}),new pe(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Le{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.se&&this.se(e),e}}function Oe(e){return null==e}function Fe(e){return 0===e&&1/e==-1/0}function Pe(e){return"number"==typeof e&&Number.isInteger(e)&&!Fe(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Ve(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Ue(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Ue(t)}function Ue(e){return e+""}function Be(t){const n=t.length;if(B(2<=n),2===n)return B(""===t.charAt(0)&&""===t.charAt(1)),se.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&U(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:U()}a=n+2}return new se(r)}Le.oe=-1;const qe=["userId","batchId"];function je(e,t){return[e,Ve(t)]}function Ge(e,t,n){return[e,Ve(t),n]}const ze={},Ke=["prefixPath","collectionGroup","readTime","documentId"],$e=["prefixPath","collectionGroup","documentId"],Qe=["collectionGroup","readTime","prefixPath","documentId"],He=["canonicalId","targetId"],We=["targetId","path"],Ye=["path","targetId"],Je=["collectionId","parent"],Xe=["indexId","uid"],Ze=["uid","sequenceNumber"],et=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],tt=["indexId","uid","orderedDocumentKey"],nt=["userId","collectionPath","documentId"],rt=["userId","collectionPath","largestBatchId"],it=["userId","collectionGroup","largestBatchId"],st=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],at=[...st,"documentOverlays"],ot=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ut=ot,ct=[...ut,"indexConfiguration","indexState","indexEntries"],ht=ct;class lt extends we{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function dt(e,t){var n=e;return Ee.F(n._e,t)}function ft(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function gt(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function mt(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class pt{constructor(e,t){this.comparator=e,this.root=t||vt.EMPTY}insert(e,t){return new pt(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,vt.BLACK,null,null))}remove(e){return new pt(this.comparator,this.root.remove(e,this.comparator).copy(null,null,vt.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new yt(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new yt(this.root,e,this.comparator,!1)}getReverseIterator(){return new yt(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new yt(this.root,e,this.comparator,!0)}}class yt{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class vt{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:vt.RED,this.left=null!=r?r:vt.EMPTY,this.right=null!=i?i:vt.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new vt(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return vt.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return vt.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,vt.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,vt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw U();if(this.right.isRed())throw U();var e=this.left.check();if(e!==this.right.check())throw U();return e+(this.isRed()?0:1)}}vt.EMPTY=null,vt.RED=!0,vt.BLACK=!1,vt.EMPTY=new class{constructor(){this.size=0}get key(){throw U()}get value(){throw U()}get color(){throw U()}get left(){throw U()}get right(){throw U()}copy(e,t,n,r,i){return this}insert(e,t,n){return new vt(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class wt{constructor(e){this.comparator=e,this.data=new pt(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new _t(this.data.getIterator())}getIteratorFrom(e){return new _t(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof wt))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new wt(this.comparator);return t.data=e,t}}class _t{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function bt(e){return e.hasNext()?e.getNext():void 0}class It{constructor(e){(this.fields=e).sort(oe.comparator)}static empty(){return new It([])}unionWith(e){let t=new wt(oe.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new It(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return ee(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class Et extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class Tt{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new Et("Invalid base64 string: "+e):e}}(e);return new Tt(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new Tt(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Z(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}Tt.EMPTY_BYTE_STRING=new Tt("");const St=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function xt(t){if(B(!!t),"string"!=typeof t)return{seconds:Dt(t.seconds),nanos:Dt(t.nanos)};{let e=0;var n=St.exec(t);B(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Dt(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ct(e){return"string"==typeof e?Tt.fromBase64String(e):Tt.fromUint8Array(e)}function At(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Nt(e){var t=e.mapValue.fields.__previous_value__;return At(t)?Nt(t):t}function kt(e){var t=xt(e.mapValue.fields.__local_write_time__.timestampValue);return new ne(t.seconds,t.nanos)}class Rt{constructor(e,t,n,r,i,s,a,o,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=u}}class Mt{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Mt("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Mt&&e.projectId===this.projectId&&e.database===this.database}}const Lt={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Ot={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?At(e)?4:Wt(e)?9007199254740991:10:U()}function Pt(e,t){if(e===t)return!0;var n,r,i=Ft(e);if(i!==Ft(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return kt(e).isEqual(kt(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=xt(e.timestampValue),r=xt(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return r=t,Ct(e.bytesValue).isEqual(Ct(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,Dt((r=e).geoPointValue.latitude)===Dt(n.geoPointValue.latitude)&&Dt(r.geoPointValue.longitude)===Dt(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Dt(e.integerValue)===Dt(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Dt(e.doubleValue),r=Dt(t.doubleValue);return n===r?Fe(n)===Fe(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return ee(e.arrayValue.values||[],t.arrayValue.values||[],Pt);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(ft(n)!==ft(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Pt(n[e],r[e])))return!1;return!0}(e,t);default:return U()}}function Vt(e,t){return void 0!==(e.values||[]).find(e=>Pt(e,t))}function Ut(e,t){if(e===t)return 0;var n,r,i,s,a=Ft(e),o=Ft(t);if(a!==o)return Z(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Z(e.booleanValue,t.booleanValue);case 2:return r=t,i=Dt((n=e).integerValue||n.doubleValue),s=Dt(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Bt(e.timestampValue,t.timestampValue);case 4:return Bt(kt(e),kt(t));case 5:return Z(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ct(e),r=Ct(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Z(n[i],r[i]);if(0!==t)return t}return Z(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Z(Dt(n.latitude),Dt(r.latitude)))?s:Z(Dt(n.longitude),Dt(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Ut(n[i],r[i]);if(t)return t}return Z(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Lt.mapValue&&t===Lt.mapValue)return 0;if(e===Lt.mapValue)return 1;if(t===Lt.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=Z(r[o],s[o]);if(0!==t)return t;var a=Ut(n[r[o]],i[s[o]]);if(0!==a)return a}return Z(r.length,s.length)}(e.mapValue,t.mapValue);default:throw U()}}function Bt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Z(e,t);var n=xt(e),r=xt(t),i=Z(n.seconds,r.seconds);return 0!==i?i:Z(n.nanos,r.nanos)}function qt(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=xt(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Ct(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return ue.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):U()}(e)}function jt(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Gt(e){return!!e&&"integerValue"in e}function zt(e){return!!e&&"arrayValue"in e}function Kt(e){return e&&"nullValue"in e}function $t(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Qt(e){return e&&"mapValue"in e}function Ht(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return gt(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Ht(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Ht(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Wt(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Yt(e,t){var n=Ut(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Jt(e,t){var n=Ut(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Xt{constructor(e){this.value=e}static empty(){return new Xt({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!Qt(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ht(t)}setAll(e){let n=oe.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Ht(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Qt(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Pt(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];Qt(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){gt(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Xt(Ht(this.value))}}class Zt{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Zt(e,0,re.min(),re.min(),re.min(),Xt.empty(),0)}static newFoundDocument(e,t,n,r){return new Zt(e,1,t,re.min(),n,r,0)}static newNoDocument(e,t){return new Zt(e,2,t,re.min(),re.min(),Xt.empty(),0)}static newUnknownDocument(e,t){return new Zt(e,3,t,re.min(),re.min(),Xt.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(re.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Xt.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Xt.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=re.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Zt&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Zt(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class en{constructor(e,t){this.position=e,this.inclusive=t}}function tn(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?ue.comparator(ue.fromName(a.referenceValue),n.key):Ut(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function nn(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Pt(e.position[n],t.position[n]))return!1;return!0}class rn{constructor(e,t="asc"){this.field=e,this.dir=t}}class sn{}class an extends sn{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new Tn(e,t,n):"array-contains"===t?new Cn(e,n):"in"===t?new An(e,n):"not-in"===t?new Nn(e,n):"array-contains-any"===t?new kn(e,n):new an(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?Sn:xn)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Ut(t,this.value)):null!==t&&Ft(this.value)===Ft(t)&&this.matchesComparison(Ut(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return U()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class on extends sn{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new on(e,t)}matches(t){return un(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function un(e){return"and"===e.op}function cn(e){return"or"===e.op}function hn(e){return ln(e)&&un(e)}function ln(e){for(const t of e.filters)if(t instanceof on)return!1;return!0}function In(e,t){var n=e.filters.concat(t);return on.create(n,e.op)}function En(e){return e instanceof an?`${(t=e).field.canonicalString()} ${t.op} ${qt(t.value)}`:e instanceof on?(e=e).op.toString()+" {"+e.getFilters().map(En).join(" ,")+"}":"Filter";var t}class Tn extends an{constructor(e,t,n){super(e,t,n),this.key=ue.fromName(n.referenceValue)}matches(e){var t=ue.comparator(e.key,this.key);return this.matchesComparison(t)}}class Sn extends an{constructor(e,t){super(e,"in",t),this.keys=Dn(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class xn extends an{constructor(e,t){super(e,"not-in",t),this.keys=Dn(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function Dn(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ue.fromName(e.referenceValue))}class Cn extends an{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return zt(t)&&Vt(t.arrayValue,this.value)}}class An extends an{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Vt(this.value.arrayValue,t)}}class Nn extends an{constructor(e,t){super(e,"not-in",t)}matches(e){if(Vt(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Vt(this.value.arrayValue,t)}}class kn extends an{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!zt(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Vt(this.value.arrayValue,e))}}class Rn{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ue=null}}function Mn(e,t=null,n=[],r=[],i=null,s=null,a=null){return new Rn(e,t,n,r,i,s,a)}function Ln(e){const t=e;if(null===t.ue){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof an)return e.field.canonicalString()+e.op.toString()+qt(e.value);if(hn(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),Oe(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>qt(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>qt(e)).join(",")),t.ue=e}return t.ue}function On(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof an?(n=e,(s=t)instanceof an&&n.op===s.op&&n.field.isEqual(s.field)&&Pt(n.value,s.value)):e instanceof on?(i=t)instanceof on&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void U();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!nn(e.startAt,t.startAt)&&nn(e.endAt,t.endAt)}function Fn(e){return ue.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Pn(e,t){return e.filters.filter(e=>e instanceof an&&e.field.isEqual(t))}function Vn(t,n,r){let i=Ot,s=!0;for(const r of Pn(t,n)){let e=Ot,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Ot:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?jt(Mt.empty(),ue.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:U();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Ot}Yt({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Yt({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function Un(t,n,r){let i=Lt,s=!0;for(const r of Pn(t,n)){let e=Lt,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?jt(Mt.empty(),ue.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Lt:U(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Lt}0<Jt({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Jt({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class Bn{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function qn(e,t,n,r,i,s,a,o){return new Bn(e,t,n,r,i,s,a,o)}function jn(e){return new Bn(e)}function Gn(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 zn(e){return null!==e.collectionGroup}function Kn(t){const n=t;if(null===n.ce){n.ce=[];const t=new Set;for(const i of n.explicitOrderBy)n.ce.push(i),t.add(i.field.canonicalString());const r=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc",e=function(e){let t=new wt(oe.comparator);return e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t}(n);e.forEach(e=>{t.has(e.canonicalString())||e.isKeyField()||n.ce.push(new rn(e,r))}),t.has(oe.keyField().canonicalString())||n.ce.push(new rn(oe.keyField(),r))}return n.ce}function $n(e){const t=e;return t.le||(t.le=function(e,t){if("F"===e.limitType)return Mn(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new rn(e.field,t)});var n=e.endAt?new en(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new en(e.startAt.position,e.startAt.inclusive):null;return Mn(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,Kn(e))),t.le}function Qn(e,t){var n=e.filters.concat([t]);return new Bn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Hn(e,t,n){return new Bn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Wn(e,t){return On($n(e),$n(t))&&e.limitType===t.limitType}function Yn(e){return`${Ln($n(e))}|lt:${e.limitType}`}function Jn(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>En(e)).join(", ")}]`),Oe(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>qt(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>qt(e)).join(",")),`Target(${t})`}($n(e))}; limitType=${e.limitType})`}function Xn(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ue.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of Kn(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=Kn(t),r=tn(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=Kn(t),r=tn(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function Zn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function er(i){return(e,t)=>{let n=!1;for(const r of Kn(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ue.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?Ut(r,i):U()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return U()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class tr{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){gt(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return mt(this.inner)}size(){return this.innerSize}}const nr=new pt(ue.comparator);const rr=new pt(ue.comparator);function ir(...e){let t=rr;for(const n of e)t=t.insert(n.key,n);return t}function sr(e){let n=rr;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function ar(){return new tr(e=>e.toString(),(e,t)=>e.isEqual(t))}const or=new pt(ue.comparator),ur=new wt(ue.comparator);function cr(...e){let t=ur;for(const n of e)t=t.add(n);return t}const hr=new wt(Z);function lr(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Fe(t)?"-0":t}}function dr(e){return{integerValue:""+e}}function fr(e,t){return Pe(t)?dr(t):lr(e,t)}class gr{constructor(){this._=void 0}}function mr(e,t){return e instanceof br?Gt(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class pr extends gr{}class yr extends gr{constructor(e){super(),this.elements=e}}function vr(e,t){const n=Er(t);for(const t of e.elements)n.some(e=>Pt(e,t))||n.push(t);return{arrayValue:{values:n}}}class wr extends gr{constructor(e){super(),this.elements=e}}function _r(e,t){let n=Er(t);for(const t of e.elements)n=n.filter(e=>!Pt(e,t));return{arrayValue:{values:n}}}class br extends gr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function Ir(e){return Dt(e.integerValue||e.doubleValue)}function Er(e){return zt(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Tr{constructor(e,t){this.field=e,this.transform=t}}class Sr{constructor(e,t){this.version=e,this.transformResults=t}}class xr{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new xr}static exists(e){return new xr(void 0,e)}static updateTime(e){return new xr(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Dr(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Cr{}function Ar(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new Vr(e.key,xr.none()):new Mr(e.key,e.data,xr.none());{const i=e.data,s=Xt.empty();let t=new wt(oe.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new Lr(e.key,s,new It(t.toArray()),xr.none())}}function Nr(e,t,n){e instanceof Mr?function(e,t,n){const r=e.value.clone(),i=Fr(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(!Dr(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Fr(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Or(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function kr(e,t,n,r){return e instanceof Mr?function(e,t,n,r){if(!Dr(e.precondition,t))return n;const i=e.value.clone(),s=Pr(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof Lr?function(e,t,n,r){if(!Dr(e.precondition,t))return n;const i=Pr(e.fieldTransforms,r,t),s=t.data;return s.setAll(Or(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,Dr(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function Rr(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&ee(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof yr&&t instanceof yr||e instanceof wr&&t instanceof wr?ee(e.elements,t.elements,Pt):e instanceof br&&t instanceof br?Pt(e.Pe,t.Pe):e instanceof pr&&t instanceof pr)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class Mr extends Cr{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class Lr extends Cr{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Or(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function Fr(e,t,n){const r=new Map;B(e.length===n.length);for(let h=0;h<n.length;h++){var i=e[h],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,u=a,c=n[h],o instanceof yr?vr(o,u):o instanceof wr?_r(o,u):c))}var o,u,c;return r}function Pr(e,t,n){const r=new Map;for(const c of e){const e=c.transform,h=n.data.field(c.field);r.set(c.field,(i=e,s=h,a=t,u=o=void 0,i instanceof pr?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&At(t)?Nt(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof yr?vr(i,s):i instanceof wr?_r(i,s):(o=mr(i=i,s),u=Ir(o)+Ir(i.Pe),Gt(o)&&Gt(i.Pe)?dr(u):lr(i.serializer,u))))}var i,s,a,o,u;return r}class Vr extends Cr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Ur extends Cr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Br{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&Nr(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=kr(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=kr(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=ar();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=Ar(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(re.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),cr())}isEqual(e){return this.batchId===e.batchId&&ee(this.mutations,e.mutations,(e,t)=>Rr(e,t))&&ee(this.baseMutations,e.baseMutations,(e,t)=>Rr(e,t))}}class qr{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){B(e.mutations.length===n.length);let r=or;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new qr(e,t,n,r)}}class jr{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Gr{constructor(e,t){this.count=e,this.unchangedNames=t}}function zr(e){switch(e){default:return U();case q.CANCELLED:case q.UNKNOWN:case q.DEADLINE_EXCEEDED:case q.RESOURCE_EXHAUSTED:case q.INTERNAL:case q.UNAVAILABLE:case q.UNAUTHENTICATED:return!1;case q.INVALID_ARGUMENT:case q.NOT_FOUND:case q.ALREADY_EXISTS:case q.PERMISSION_DENIED:case q.FAILED_PRECONDITION:case q.ABORTED:case q.OUT_OF_RANGE:case q.UNIMPLEMENTED:case q.DATA_LOSS:return!0}}function Kr(e){if(void 0===e)return F("GRPC error has no .code"),q.UNKNOWN;switch(e){case x.OK:return q.OK;case x.CANCELLED:return q.CANCELLED;case x.UNKNOWN:return q.UNKNOWN;case x.DEADLINE_EXCEEDED:return q.DEADLINE_EXCEEDED;case x.RESOURCE_EXHAUSTED:return q.RESOURCE_EXHAUSTED;case x.INTERNAL:return q.INTERNAL;case x.UNAVAILABLE:return q.UNAVAILABLE;case x.UNAUTHENTICATED:return q.UNAUTHENTICATED;case x.INVALID_ARGUMENT:return q.INVALID_ARGUMENT;case x.NOT_FOUND:return q.NOT_FOUND;case x.ALREADY_EXISTS:return q.ALREADY_EXISTS;case x.PERMISSION_DENIED:return q.PERMISSION_DENIED;case x.FAILED_PRECONDITION:return q.FAILED_PRECONDITION;case x.ABORTED:return q.ABORTED;case x.OUT_OF_RANGE:return q.OUT_OF_RANGE;case x.UNIMPLEMENTED:return q.UNIMPLEMENTED;case x.DATA_LOSS:return q.DATA_LOSS;default:return U()}}function $r(){return new TextEncoder}(S=x=x||{})[S.OK=0]="OK",S[S.CANCELLED=1]="CANCELLED",S[S.UNKNOWN=2]="UNKNOWN",S[S.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",S[S.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",S[S.NOT_FOUND=5]="NOT_FOUND",S[S.ALREADY_EXISTS=6]="ALREADY_EXISTS",S[S.PERMISSION_DENIED=7]="PERMISSION_DENIED",S[S.UNAUTHENTICATED=16]="UNAUTHENTICATED",S[S.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",S[S.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",S[S.ABORTED=10]="ABORTED",S[S.OUT_OF_RANGE=11]="OUT_OF_RANGE",S[S.UNIMPLEMENTED=12]="UNIMPLEMENTED",S[S.INTERNAL=13]="INTERNAL",S[S.UNAVAILABLE=14]="UNAVAILABLE",S[S.DATA_LOSS=15]="DATA_LOSS";const Qr=new E([4294967295,4294967295],0);function Hr(e){const t=$r().encode(e),n=new T;return n.update(t),new Uint8Array(n.digest())}function Wr(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new E([n,r],0),new E([i,s],0)]}class Yr{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new Jr(`Invalid padding: ${t}`);if(n<0)throw new Jr(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new Jr(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Jr(`Invalid padding when bitmap length is 0: ${t}`);this.Ie=8*e.length-t,this.Te=E.fromNumber(this.Ie)}Ee(e,t,n){let r=e.add(t.multiply(E.fromNumber(n)));return 1===r.compare(Qr)&&(r=new E([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Te).toNumber()}de(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ie)return!1;const t=Hr(e),[n,r]=Wr(t);for(let i=0;i<this.hashCount;i++){const t=this.Ee(n,r,i);if(!this.de(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Yr(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ie){const n=Hr(t),[r,i]=Wr(n);for(let e=0;e<this.hashCount;e++){const n=this.Ee(r,i,e);this.Ae(n)}}}Ae(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class Jr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Xr{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,Zr.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Xr(re.min(),r,new pt(Z),nr,cr())}}class Zr{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new Zr(n,t,cr(),cr(),cr())}}class ei{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class ti{constructor(e,t){this.targetId=e,this.me=t}}class ni{constructor(e,t,n=Tt.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ri{constructor(){this.fe=0,this.ge=ai(),this.pe=Tt.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){0<e.approximateByteSize()&&(this.we=!0,this.pe=e)}Ce(){let n=cr(),r=cr(),i=cr();return this.ge.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:U()}}),new Zr(this.pe,this.ye,n,r,i)}ve(){this.we=!1,this.ge=ai()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){--this.fe,B(0<=this.fe)}Ne(){this.we=!0,this.ye=!0}}class ii{constructor(e){this.Le=e,this.Be=new Map,this.ke=nr,this.qe=si(),this.Qe=new pt(Z)}Ke(e){for(const t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.$e(t,e.Ve):this.Ue(t,e.key,e.Ve);for(const n of e.removedTargetIds)this.Ue(n,e.key,e.Ve)}We(n){this.forEachTarget(n,e=>{const t=this.Ge(e);switch(n.state){case 0:this.ze(e)&&t.De(n.resumeToken);break;case 1:t.Oe(),t.Se||t.ve(),t.De(n.resumeToken);break;case 2:t.Oe(),t.Se||this.removeTarget(e);break;case 3:this.ze(e)&&(t.Ne(),t.De(n.resumeToken));break;case 4:this.ze(e)&&(this.je(e),t.De(n.resumeToken));break;default:U()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Be.forEach((e,t)=>{this.ze(t)&&n(t)})}He(e){const t=e.targetId,n=e.me.count,r=this.Je(t);if(r){var i=r.target;if(Fn(i))if(0===n){const e=new ue(i.path);this.Ue(t,e,Zt.newNoDocument(e,re.min()))}else B(1===n);else{const r=this.Ye(t);if(r!==n){const n=this.Ze(e),s=n?this.Xe(n,e,r):1;if(0!==s){this.je(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Qe=this.Qe.insert(t,e)}}}}}Ze(e){var t=e.me.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=Ct(n).toUint8Array()}catch(e){if(e instanceof Et)return P("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new Yr(i,r,t)}catch(e){return P(e instanceof Jr?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ie?null:s}Xe(e,t,n){return t.me.count===n-this.nt(e,t.targetId)?0:2}nt(n,r){const e=this.Le.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Le.tt(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.Ue(r,e,null),i++)}),i}rt(r){const i=new Map;this.Be.forEach((e,t)=>{var n=this.Je(t);if(n){if(e.current&&Fn(n.target)){const i=new ue(n.target.path);null!==this.ke.get(i)||this.it(t,i)||this.Ue(t,i,Zt.newNoDocument(i,r))}e.be&&(i.set(t,e.Ce()),e.ve())}});let s=cr();this.qe.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Je(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.ke.forEach((e,t)=>t.setReadTime(r));var e=new Xr(r,i,this.Qe,this.ke,s);return this.ke=nr,this.qe=si(),this.Qe=new pt(Z),e}$e(e,t){var n;this.ze(e)&&(n=this.it(e,t.key)?2:0,this.Ge(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e)))}Ue(e,t,n){if(this.ze(e)){const r=this.Ge(e);this.it(e,t)?r.Fe(t,1):r.Me(t),this.qe=this.qe.insert(t,this.st(t).delete(e)),n&&(this.ke=this.ke.insert(t,n))}}removeTarget(e){this.Be.delete(e)}Ye(e){var t=this.Ge(e).Ce();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.Ge(e).xe()}Ge(e){let t=this.Be.get(e);return t||(t=new ri,this.Be.set(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new wt(Z),this.qe=this.qe.insert(e,t)),t}ze(e){var t=null!==this.Je(e);return t||O("WatchChangeAggregator","Detected inactive target",e),t}Je(e){var t=this.Be.get(e);return t&&t.Se?null:this.Le.ot(e)}je(t){this.Be.set(t,new ri),this.Le.getRemoteKeysForTarget(t).forEach(e=>{this.Ue(t,e,null)})}it(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function si(){return new pt(ue.comparator)}function ai(){return new pt(ue.comparator)}const oi={asc:"ASCENDING",desc:"DESCENDING"},ui={"<":"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"},ci={and:"AND",or:"OR"};class hi{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function li(e,t){return e.useProto3Json||Oe(t)?t:{value:t}}function di(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function fi(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function gi(e){return B(!!e),re.fromTimestamp((t=xt(e),new ne(t.seconds,t.nanos)));var t}function mi(e,t){return pi(e,t).canonicalString()}function pi(e,t){const n=(e=e,new se(["projects",e.projectId,"databases",e.database]).child("documents"));return void 0===t?n:n.child(t)}function yi(e){var t=se.fromString(e);return B(Oi(t)),t}function vi(e,t){return mi(e.databaseId,t.path)}function wi(e,t){const n=yi(t);if(n.get(1)!==e.databaseId.projectId)throw new j(q.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 j(q.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ue(Ei(n))}function _i(e,t){return mi(e.databaseId,t)}function bi(e){var t=yi(e);return 4===t.length?se.emptyPath():Ei(t)}function Ii(e){return new se(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Ei(e){return B(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function Ti(e,t,n){return{name:vi(e,t),fields:n.value.mapValue.fields}}function Si(e,t,n){const r=wi(e,t.name),i=gi(t.updateTime),s=t.createTime?gi(t.createTime):re.min(),a=new Xt({mapValue:{fields:t.fields}}),o=Zt.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function xi(e,t){let n;if(t instanceof Mr)n={update:Ti(e,t.key,t.value)};else if(t instanceof Vr)n={delete:vi(e,t.key)};else if(t instanceof Lr)n={update:Ti(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof Ur))return U();n={verify:vi(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof pr)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof yr)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof wr)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof br)return{fieldPath:e.field.canonicalString(),increment:t.Pe};throw U()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,di(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:U())),n;var r}function Di(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?xr.updateTime(gi(i.updateTime)):void 0!==i.exists?xr.exists(i.exists):xr.none():xr.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)B("REQUEST_TIME"===t.setToServerValue),n=new pr;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new yr(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new wr(e)}else"increment"in t?n=new br(e,t.increment):U();var r=oe.fromServerFormat(t.fieldPath);return new Tr(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=wi(t,e.update.name),a=new Xt({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new It(t.map(e=>oe.fromServerFormat(e)))}(e.updateMask);return new Lr(s,a,t,n,r)}return new Mr(s,a,n,r)}if(e.delete){const r=wi(t,e.delete);return new Vr(r,n)}if(e.verify){const r=wi(t,e.verify);return new Ur(r,n)}return U()}function Ci(e,t){return{documents:[_i(e,t.path)]}}function Ai(e,t){const n={structuredQuery:{}},r=t.path;let i;null!==t.collectionGroup?(i=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=_i(e,i);var s=function(e){if(0!==e.length)return function n(e){return e instanceof an?function(e){if("=="===e.op){if($t(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NAN"}};if(Kt(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NULL"}}}else if("!="===e.op){if($t(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NOT_NAN"}};if(Kt(e.value))return{unaryFilter:{field:Mi(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Mi(e.field),op:ki(e.op),value:e.value}}}(e):e instanceof on?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:Ri(e.op),filters:t}}}(e):U()}(on.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:Mi(e.field),direction:(e=e.dir,oi[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);s=li(e,t.limit);return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),{_t:n,parent:i}}function Ni(e){let t=bi(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){B(1===a);const f=s.from[0];f.allDescendants?o=f.collectionId:t=t.child(f.collectionId)}let u=[];s.where&&(u=function(e){const t=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Li(e.unaryFilter.field);return an.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Li(e.unaryFilter.field);return an.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Li(e.unaryFilter.field);return an.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=Li(e.unaryFilter.field);return an.create(i,"!=",{nullValue:"NULL_VALUE"});default:return U()}}(e):void 0!==e.fieldFilter?function(e){return an.create(Li(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 U()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return on.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return U()}}(e.compositeFilter.op))}(e):U()}(e);return t instanceof on&&hn(t)?t.getFilters():[t]}(s.where));let c=[];s.orderBy&&(c=s.orderBy.map(e=>function(e){return new rn(Li(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let h=null;s.limit&&(h=(e=s.limit,Oe(n="object"==typeof e?e.value:e)?null:n));let l=null;s.startAt&&(l=(r=s.startAt,i=!!r.before,n=r.values||[],new en(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new en(s,i))),qn(t,o,c,u,h,"F",l,d)}function ki(e){return ui[e]}function Ri(e){return ci[e]}function Mi(e){return{fieldPath:e.canonicalString()}}function Li(e){return oe.fromServerFormat(e.fieldPath)}function Oi(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class Fi{constructor(e,t,n,r,i=re.min(),s=re.min(),a=Tt.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Fi(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Fi(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Fi(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Fi(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Pi{constructor(e){this.ct=e}}function Vi(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Ui(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:vi(i=e.ct,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:di(i,e.version.toTimestamp()),createTime:di(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Bi(t.version)};else{if(!t.isUnknownDocument())return U();r.unknownDocument={path:n.path.toArray(),version:Bi(t.version)}}var i;return r}function Ui(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Bi(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function qi(e){var t=new ne(e.seconds,e.nanoseconds);return re.fromTimestamp(t)}function ji(t,e){const n=(e.baseMutations||[]).map(e=>Di(t.ct,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>Di(t.ct,e)),i=ne.fromMillis(e.localWriteTimeMs);return new Br(e.batchId,i,n,r)}function Gi(e){var t,n=qi(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?qi(e.lastLimboFreeSnapshotVersion):re.min(),i=void 0!==e.query.documents?(B(1===(t=e.query).documents.length),$n(jn(bi(t.documents[0])))):$n(Ni(e.query));return new Fi(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,Tt.fromBase64String(e.resumeToken))}function zi(e,t){var n=Bi(t.snapshotVersion),r=Bi(t.lastLimboFreeSnapshotVersion),i=Fn(t.target)?Ci(e.ct,t.target):Ai(e.ct,t.target)._t,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Ln(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Ki(e){var t=Ni({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Hn(t,t.limit,"L"):t}function $i(e,t){return new jr(t.largestBatchId,Di(e.ct,t.overlayMutation))}function Qi(e,t){var n=t.path.lastSegment();return[e,Ve(t.path.popLast()),n]}function Hi(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:Bi(r.readTime),documentKey:Ve(r.documentKey.path),largestBatchId:r.largestBatchId}}class Wi{getBundleMetadata(e,t){return Yi(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:qi(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return Yi(e).put({bundleId:(t=t).id,createTime:Bi(gi(t.createTime)),version:t.version})}getNamedQuery(e,t){return Ji(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:Ki(e.bundledQuery),readTime:qi(e.readTime)}})}saveNamedQuery(e,t){return Ji(e).put({name:(t=t).name,readTime:Bi(gi(t.readTime)),bundledQuery:t.bundledQuery})}}function Yi(e){return dt(e,"bundles")}function Ji(e){return dt(e,"namedQueries")}class Xi{constructor(e,t){this.serializer=e,this.userId=t}static lt(e,t){var n=t.uid||"";return new Xi(e,n)}getOverlay(e,t){return Zi(e).get(Qi(this.userId,t)).next(e=>e?$i(this.serializer,e):null)}getOverlays(e,t){const n=ar();return be.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new jr(i,t);s.push(this.ht(r,n))}),be.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Ve(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(Zi(n).j("collectionPathOverlayIndex",t))}),be.waitFor(i)}getOverlaysForCollection(e,t,n){const r=ar(),i=Ve(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return Zi(e).U("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=$i(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=ar();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Zi(e).J({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=$i(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}ht(e,t){return Zi(e).put(function(e,t,n){var[,r,i]=Qi(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:xi(e.ct,n.mutation)}}(this.serializer,this.userId,t))}}function Zi(e){return dt(e,"documentOverlays")}class es{constructor(){}Pt(e,t){this.It(e,t),t.Tt()}It(t,n){if("nullValue"in t)this.Et(n,5);else if("booleanValue"in t)this.Et(n,10),n.dt(t.booleanValue?1:0);else if("integerValue"in t)this.Et(n,15),n.dt(Dt(t.integerValue));else if("doubleValue"in t){var e=Dt(t.doubleValue);isNaN(e)?this.Et(n,13):(this.Et(n,15),Fe(e)?n.dt(0):n.dt(e))}else if("timestampValue"in t){let e=t.timestampValue;this.Et(n,20),"string"==typeof e&&(e=xt(e)),n.At(`${e.seconds||""}`),n.dt(e.nanos||0)}else"stringValue"in t?(this.Rt(t.stringValue,n),this.Vt(n)):"bytesValue"in t?(this.Et(n,30),n.ft(Ct(t.bytesValue)),this.Vt(n)):"referenceValue"in t?this.gt(t.referenceValue,n):"geoPointValue"in t?(e=t.geoPointValue,this.Et(n,45),n.dt(e.latitude||0),n.dt(e.longitude||0)):"mapValue"in t?Wt(t)?this.Et(n,Number.MAX_SAFE_INTEGER):(this.yt(t.mapValue,n),this.Vt(n)):"arrayValue"in t?(this.wt(t.arrayValue,n),this.Vt(n)):U()}Rt(e,t){this.Et(t,25),this.St(e,t)}St(e,t){t.At(e)}yt(e,t){var n=e.fields||{};this.Et(t,55);for(const e of Object.keys(n))this.Rt(e,t),this.It(n[e],t)}wt(e,t){var n=e.values||[];this.Et(t,50);for(const e of n)this.It(e,t)}gt(e,t){this.Et(t,37),ue.fromName(e).path.forEach(e=>{this.Et(t,60),this.St(e,t)})}Et(e,t){e.dt(t)}Vt(e){e.dt(2)}}function ts(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}es.bt=new es;class ns{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Dt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ct(n.value),n=t.next();this.vt()}Ft(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Mt(n.value),n=t.next();this.xt()}Ot(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ct(e);else if(e<2048)this.Ct(960|e>>>6),this.Ct(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ct(480|e>>>12),this.Ct(128|63&e>>>6),this.Ct(128|63&e);else{const e=t.codePointAt(0);this.Ct(240|e>>>18),this.Ct(128|63&e>>>12),this.Ct(128|63&e>>>6),this.Ct(128|63&e)}}this.vt()}Nt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Mt(e);else if(e<2048)this.Mt(960|e>>>6),this.Mt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Mt(480|e>>>12),this.Mt(128|63&e>>>6),this.Mt(128|63&e);else{const e=t.codePointAt(0);this.Mt(240|e>>>18),this.Mt(128|63&e>>>12),this.Mt(128|63&e>>>6),this.Mt(128|63&e)}}this.xt()}Lt(e){var t=this.Bt(e),n=ts(t);this.kt(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}qt(e){var t=this.Bt(e),n=ts(t);this.kt(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}Qt(){this.Kt(255),this.Kt(255)}$t(){this.Ut(255),this.Ut(255)}reset(){this.position=0}seed(e){this.kt(e.length),this.buffer.set(e,this.position),this.position+=e.length}Wt(){return this.buffer.slice(0,this.position)}Bt(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ct(e){var t=255&e;0==t?(this.Kt(0),this.Kt(255)):255==t?(this.Kt(255),this.Kt(0)):this.Kt(t)}Mt(e){var t=255&e;0==t?(this.Ut(0),this.Ut(255)):255==t?(this.Ut(255),this.Ut(0)):this.Ut(e)}vt(){this.Kt(0),this.Kt(1)}xt(){this.Ut(0),this.Ut(1)}Kt(e){this.kt(1),this.buffer[this.position++]=e}Ut(e){this.kt(1),this.buffer[this.position++]=~e}kt(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class rs{constructor(e){this.Gt=e}ft(e){this.Gt.Dt(e)}At(e){this.Gt.Ot(e)}dt(e){this.Gt.Lt(e)}Tt(){this.Gt.Qt()}}class is{constructor(e){this.Gt=e}ft(e){this.Gt.Ft(e)}At(e){this.Gt.Nt(e)}dt(e){this.Gt.qt(e)}Tt(){this.Gt.$t()}}class ss{constructor(){this.Gt=new ns,this.zt=new rs(this.Gt),this.jt=new is(this.Gt)}seed(e){this.Gt.seed(e)}Ht(e){return 0===e?this.zt:this.jt}Wt(){return this.Gt.Wt()}reset(){this.Gt.reset()}}class as{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Jt(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new as(this.indexId,this.documentKey,this.arrayValue,n)}}function os(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=us(e.arrayValue,t.arrayValue),0!==n?n:(n=us(e.directionalValue,t.directionalValue),0!==n?n:ue.comparator(e.documentKey,t.documentKey)))}function us(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class cs{constructor(e){this.Yt=new wt((e,t)=>oe.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Zt=e.orderBy,this.Xt=[];for(const t of e.filters){const e=t;e.isInequality()?this.Yt=this.Yt.add(e):this.Xt.push(e)}}get en(){return 1<this.Yt.size}tn(e){if(B(e.collectionGroup===this.collectionId),this.en)return!1;const t=he(e);if(void 0!==t&&!this.nn(t))return!1;const n=le(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.nn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(0<this.Yt.size){const e=this.Yt.getIterator().getNext();if(!r.has(e.field.canonicalString())){const t=n[i];if(!this.rn(e,t)||!this.sn(this.Zt[s++],t))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Zt.length||!this.sn(this.Zt[s++],e))return!1}return!0}on(){if(this.en)return null;let e=new wt(oe.comparator);const t=[];for(const n of this.Xt)n.field.isKeyField()||("array-contains"===n.op||"array-contains-any"===n.op?t.push(new de(n.field,2)):e.has(n.field)||(e=e.add(n.field),t.push(new de(n.field,0))));for(const r of this.Zt)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new de(r.field,"asc"===r.dir?0:1)));return new ce(ce.UNKNOWN_ID,this.collectionId,t,fe.empty())}nn(e){for(const t of this.Xt)if(this.rn(t,e))return!0;return!1}rn(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}sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function hs(e){if(0===e.getFilters().length)return[];const t=function t(e){if(B(e instanceof an||e instanceof on),e instanceof an)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=on.create(n,e.op);return r=ps(r),fs(r)?r:(B(r instanceof on),B(un(r)),B(1<r.filters.length),r.filters.reduce((e,t)=>gs(e,t)))}(function t(n){var e;if(B(n instanceof an||n instanceof on),n instanceof an){if(n instanceof An){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>an.create(n.field,"==",e)))||[];return on.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return on.create(r,n.op)}(e));return B(fs(t)),ls(t)||ds(t)?[t]:t.getFilters()}function ls(e){return e instanceof an}function ds(e){return e instanceof on&&hn(e)}function fs(e){return ls(e)||ds(e)||function(e){if(e instanceof on&&cn(e)){for(const t of e.getFilters())if(!ls(t)&&!ds(t))return!1;return!0}return!1}(e)}function gs(e,t){var n,r;return B(e instanceof an||e instanceof on),B(t instanceof an||t instanceof on),ps(e instanceof an?t instanceof an?(n=e,r=t,on.create([n,r],"and")):ms(e,t):t instanceof an?ms(t,e):function(e,t){if(B(0<e.filters.length&&0<t.filters.length),un(e)&&un(t))return In(e,t.getFilters());const n=cn(e)?e:t,r=cn(e)?t:e,i=n.filters.map(e=>gs(e,r));return on.create(i,"or")}(e,t))}function ms(t,e){if(un(e))return In(e,t.getFilters());var n=e.filters.map(e=>gs(t,e));return on.create(n,"or")}function ps(t){if(B(t instanceof an||t instanceof on),t instanceof an)return t;const e=t.getFilters();if(1===e.length)return ps(e[0]);if(ln(t))return t;const n=e.map(e=>ps(e)),r=[];return n.forEach(e=>{e instanceof an?r.push(e):e instanceof on&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:on.create(r,t.op)}class ys{constructor(){this._n=new vs}addToCollectionParentIndex(e,t){return this._n.add(t),be.resolve()}getCollectionParents(e,t){return be.resolve(this._n.getEntries(t))}addFieldIndex(e,t){return be.resolve()}deleteFieldIndex(e,t){return be.resolve()}deleteAllFieldIndexes(e){return be.resolve()}createTargetIndexes(e,t){return be.resolve()}getDocumentsMatchingTarget(e,t){return be.resolve(null)}getIndexType(e,t){return be.resolve(0)}getFieldIndexes(e,t){return be.resolve([])}getNextCollectionGroupToUpdate(e){return be.resolve(null)}getMinOffset(e,t){return be.resolve(pe.min())}getMinOffsetFromCollectionGroup(e,t){return be.resolve(pe.min())}updateCollectionGroup(e,t,n){return be.resolve()}updateIndexEntries(e,t){return be.resolve()}}class vs{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new wt(se.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new wt(se.comparator)).toArray()}}const ws=new Uint8Array(0);class _s{constructor(e,t){this.databaseId=t,this.an=new vs,this.un=new tr(e=>Ln(e),(e,t)=>On(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.an.has(t))return be.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.an.add(t)});r={collectionId:n,parent:Ve(r)};return bs(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[te(n),""],!1,!0);return bs(e).U(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Be(t.parent))}return r})}addFieldIndex(e,t){const n=Es(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=Ts(e);return i.next(e=>{n.put(Hi(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=Es(e),r=Ts(e),i=Is(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){const t=Es(e),n=Is(e),r=Ts(e);return t.j().next(()=>n.j()).next(()=>r.j())}createTargetIndexes(n,e){return be.forEach(this.cn(e),t=>this.getIndexType(n,t).next(e=>{if(0===e||1===e){const e=new cs(t).on();if(null!=e)return this.addFieldIndex(n,e)}}))}getDocumentsMatchingTarget(e,h){const l=Is(e);let d=!0;const n=new Map;return be.forEach(this.cn(h),t=>this.ln(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let c=cr();const d=[];return be.forEach(n,(e,t)=>{var n;O("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Ln(h)}`);var r=function(e,t){var n=he(t);if(void 0===n)return null;for(const t of Pn(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),i=function(e,t){const n=new Map;for(const r of le(t))for(const t of Pn(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of le(t)){const t=(0===i.kind?Vn:Un)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new en(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of le(t)){const t=(0===i.kind?Un:Vn)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new en(n,r)}(t,e),o=this.hn(e,t,s),u=this.hn(e,t,a),i=this.Pn(e,t,i),i=this.In(e.indexId,r,o,s.inclusive,u,a.inclusive,i);return be.forEach(i,e=>l.G(e,h.limit).next(e=>{e.forEach(e=>{var t=ue.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),d.push(t))})}))}).next(()=>d)}return be.resolve(null)})}cn(t){let e=this.un.get(t);return e||(e=0===t.filters.length?[t]:hs(on.create(t.filters,"and")).map(e=>Mn(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.un.set(t,e),e)}In(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;h<o;++h){const o=e?this.Tn(e[h/u]):ws,l=this.En(t,o,n[h%u],r),d=this.dn(t,o,i[h%u],s),f=a.map(e=>this.En(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}En(e,t,n,r){const i=new as(e,ue.empty(),t,n);return r?i:i.Jt()}dn(e,t,n,r){const i=new as(e,ue.empty(),t,n);return r?i.Jt():i}ln(e,t){const r=new cs(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.tn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.cn(t);return be.forEach(r,t=>this.ln(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new wt(oe.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>function(e){return null!==e.limit}(t)&&1<r.length&&2===n?1:n)}An(e,t){const n=new ss;for(const i of le(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Ht(i.kind);es.bt.Pt(e,r)}return n.Wt()}Tn(e){const t=new ss;return es.bt.Pt(e,t.Ht(0)),t.Wt()}Rn(e,t){const n=new ss;return es.bt.Pt(jt(this.databaseId,t),n.Ht(0===(r=le(e)).length?0:r[r.length-1].kind)),n.Wt();var r}Pn(e,t,n){if(null===n)return[];let r=[];r.push(new ss);let i=0;for(const s of le(e)){const e=n[i++];for(const n of r)if(this.Vn(t,s.fieldPath)&&zt(e))r=this.mn(r,s,e);else{const t=n.Ht(s.kind);es.bt.Pt(e,t)}}return this.fn(r)}hn(e,t,n){return this.Pn(e,t,n.position)}fn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Wt();return t}mn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new ss;r.seed(n.Wt()),es.bt.Pt(e,r.Ht(t.kind)),i.push(r)}return i}Vn(e,t){return!!e.filters.find(e=>e instanceof an&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=Es(e),r=Ts(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next(e=>{const s=[];return be.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new fe(e.sequenceNumber,new pe(qi(e.readTime),new ue(Be(e.documentKey)),e.largestBatchId)):fe.empty(),r=t.fields.map(([e,t])=>new de(oe.fromServerFormat(e),t)),new ce(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Z(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=Es(e),s=Ts(e);return this.gn(e).next(t=>i.U("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>be.forEach(e,e=>s.put(Hi(e.indexId,this.uid,t,r)))))}updateIndexEntries(i,e){const n=new Map;return be.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?be.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),be.forEach(e,n=>this.pn(i,t,n).next(e=>{var t=this.yn(r,n);return e.isEqual(t)?be.resolve():this.wn(i,r,n,e,t)}))))})}Sn(e,t,n,r){return Is(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Rn(n,t.key),documentKey:t.key.path.toArray()})}bn(e,t,n,r){return Is(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Rn(n,t.key),t.key.path.toArray()])}pn(e,n,r){const t=Is(e);let i=new wt(os);return t.J({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Rn(r,n)])},(e,t)=>{i=i.add(new as(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}yn(e,t){let n=new wt(os);var r=this.An(t,e);if(null==r)return n;const i=he(t);if(null!=i){var s=e.data.field(i.fieldPath);if(zt(s))for(const i of s.arrayValue.values||[])n=n.add(new as(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new as(t.indexId,e.key,ws,r));return n}wn(t,n,r,e,i){O("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=bt(s),u=bt(a);for(;o||u;){let e=!1,t=!1;if(o&&u){const r=n(o,u);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(u),u=bt(a)):t?(i(o),o=bt(s)):(o=bt(s),u=bt(a))}}(e,i,os,e=>{s.push(this.Sn(t,n,r,e))},e=>{s.push(this.bn(t,n,r,e))}),be.waitFor(s)}gn(e){let r=1;return Ts(e).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>os(e,t)).filter((e,t,n)=>!t||0!==os(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=os(i,e),s=os(i,t);if(0===n)r[0]=e.Jt();else if(0<n&&s<0)r.push(i),r.push(i.Jt());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2){if(this.Dn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,ws,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,ws,[]];i.push(IDBKeyRange.bound(t,n))}return i}Dn(e,t){return 0<os(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Ss)}getMinOffset(t,e){return be.mapArray(this.cn(e),e=>this.ln(t,e).next(e=>e||U())).next(Ss)}}function bs(e){return dt(e,"collectionParents")}function Is(e){return dt(e,"indexEntries")}function Es(e){return dt(e,"indexConfiguration")}function Ts(e){return dt(e,"indexState")}function Ss(e){B(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;ye(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new pe(t.readTime,t.documentKey,n)}const xs={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Ds{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Ds(e,Ds.DEFAULT_COLLECTION_PERCENTILE,Ds.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Cs(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.J({range:a},(e,t,n)=>(o++,n.delete()));s.push(u.next(()=>{B(1===o)}));const c=[];for(const e of n.mutations){const r=Ge(t,e.key.path,n.batchId);s.push(i.delete(r)),c.push(e.key)}return be.waitFor(s).next(()=>c)}function As(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw U();t=e.noDocument}return JSON.stringify(t).length}Ds.DEFAULT_COLLECTION_PERCENTILE=10,Ds.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ds.DEFAULT=new Ds(41943040,Ds.DEFAULT_COLLECTION_PERCENTILE,Ds.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ds.DISABLED=new Ds(-1,0,0);class Ns{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Cn={}}static lt(e,t,n,r){B(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new Ns(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Rs(e).J({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=Ms(h),m=Rs(h);return m.add({}).next(e=>{B("number"==typeof e);const t=new Br(e,l,d,f),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>xi(i.ct,e)),u=a.mutations.map(e=>xi(i.ct,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var i,s,a,o,u;let c=new wt((e,t)=>Z(e.canonicalString(),t.canonicalString()));for(const h of f){const l=Ge(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,ze))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.Cn[e]=t.keys()}),be.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Rs(e).get(t).next(e=>e?(B(e.userId===this.userId),ji(this.serializer,e)):null)}vn(e,n){return this.Cn[n]?be.resolve(this.Cn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Cn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return Rs(e).J({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(B(t.batchId>=r),i=ji(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Rs(e).J({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Rs(e).U("userMutationsIndex",t).next(e=>e.map(e=>ji(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=je(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return Ms(a).J({range:t},(e,t,n)=>{var[r,i,s]=e,i=Be(i);if(r===this.userId&&o.path.isEqual(i))return Rs(a).get(s).next(e=>{if(!e)throw U();B(e.userId===this.userId),u.push(ji(this.serializer,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new wt(Z);const n=[];return e.forEach(a=>{var e=je(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=Ms(t).J({range:e},(e,t,n)=>{var[r,i,s]=e,i=Be(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),be.waitFor(n).next(()=>this.Fn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=je(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new wt(Z);return Ms(e).J({range:r},(e,t,n)=>{var[r,i,s]=e,i=Be(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(u=u.add(s)):n.done()}).next(()=>this.Fn(e,u))}Fn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Rs(t).get(e).next(e=>{if(null===e)throw U();B(e.userId===this.userId),n.push(ji(this.serializer,e))}))}),be.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return Cs(t._e,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.Mn(n.batchId)}),be.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}Mn(e){delete this.Cn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return be.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return Ms(n).J({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Be(e[1]);r.push(t)}else n.done()}).next(()=>{B(0===r.length)})})}containsKey(e,t){return ks(e,this.userId,t)}xn(e){return Ls(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function ks(e,s,t){const n=je(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return Ms(e).J({range:r,H:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function Rs(e){return dt(e,"mutations")}function Ms(e){return dt(e,"documentMutations")}function Ls(e){return dt(e,"mutationQueues")}class Os{constructor(e){this.On=e}next(){return this.On+=2,this.On}static Nn(){return new Os(0)}static Ln(){return new Os(-1)}}class Fs{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.Bn(n).next(e=>{const t=new Os(e.highestTargetId);return e.highestTargetId=t.next(),this.kn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Bn(e).next(e=>re.fromTimestamp(new ne(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Bn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Bn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.kn(t,e)))}addTargetData(t,n){return this.qn(t,n).next(()=>this.Bn(t).next(e=>(e.targetCount+=1,this.Qn(n,e),this.kn(t,e))))}updateTargetData(e,t){return this.qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Ps(t).delete(e.targetId)).next(()=>this.Bn(t)).next(e=>(B(0<e.targetCount),--e.targetCount,this.kn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return Ps(r).J((e,t)=>{var n=Gi(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>be.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Ps(e).J((e,t)=>{var n=Gi(t);r(n)})}Bn(e){return Vs(e).get("targetGlobalKey").next(e=>(B(null!==e),e))}kn(e,t){return Vs(e).put("targetGlobalKey",t)}qn(e,t){return Ps(e).put(zi(this.serializer,t))}Qn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Bn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=Ln(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return Ps(e).J({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Gi(t);On(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=Us(n);return e.forEach(e=>{var t=Ve(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),be.waitFor(i)}removeMatchingKeys(n,e,r){const i=Us(n);return be.forEach(e,e=>{var t=Ve(e.path);return be.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=Us(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=Us(e);let i=cr();return r.J({range:n,H:!0},(e,t,n)=>{var r=Be(e[1]),r=new ue(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Ve(t.path),n=IDBKeyRange.bound([n],[te(n)],!1,!0);let r=0;return Us(e).J({index:"documentTargetsIndex",H:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}ot(e,t){return Ps(e).get(t).next(e=>e?Gi(e):null)}}function Ps(e){return dt(e,"targets")}function Vs(e){return dt(e,"targetGlobal")}function Us(e){return dt(e,"targetDocuments")}function Bs([e,t],[n,r]){var i=Z(e,n);return 0===i?Z(t,r):i}class qs{constructor(e){this.Kn=e,this.buffer=new wt(Bs),this.$n=0}Un(){return++this.$n}Wn(e){var t=[e,this.Un()];if(this.buffer.size<this.Kn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Bs(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class js{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.zn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}zn(e){O("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){De(e)?O("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await _e(e)}await this.zn(3e5)})}}class Gs{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.Hn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return be.resolve(Le.oe);const n=new qs(t);return this.jn.forEachTarget(e,e=>n.Wn(e.sequenceNumber)).next(()=>this.jn.Jn(e,e=>n.Wn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(O("LruGarbageCollector","Garbage collection skipped; disabled"),be.resolve(xs)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(O("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),xs):this.Yn(t,n))}getCacheSize(e){return this.jn.getCacheSize(e)}Yn(t,n){let r,i,s,a,o,u,c;const h=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(O("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),L()<=l.DEBUG&&O("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),be.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class zs{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Gs(e,t))}Hn(e){const n=this.Zn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Zn(e){let t=0;return this.Jn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Jn(e,n){return this.Xn(e,(e,t)=>n(t))}addReference(e,t,n){return Ks(e,n)}removeReference(e,t,n){return Ks(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Ks(e,t)}er(t,n){let r=!1;return Ls(t).Y(e=>ks(t,e,n).next(e=>(e&&(r=!0),be.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Xn(n,(t,e)=>{if(e<=r){const r=this.er(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,re.min()),Us(n).delete(function(e){return[0,Ve(e.path)]}(t))))});s.push(r)}}).next(()=>be.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Ks(e,t)}Xn(e,r){const t=Us(e);let i,s=Le.oe;return t.J({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==Le.oe&&r(new ue(Be(i)),s),s=n,i=t):s=Le.oe}).next(()=>{s!==Le.oe&&r(new ue(Be(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Ks(e,t){return Us(e).put((e=e.currentSequenceNumber,{targetId:0,path:Ve(t.path),sequenceNumber:e}))}class $s{constructor(){this.changes=new tr(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Zt.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?be.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Qs{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Js(e).put(n)}removeEntry(e,t,n){return Js(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Ui(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.tr(t,e)))}getEntry(e,n){let r=Zt.newInvalidDocument(n);return Js(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(Xs(n))},(e,t)=>{r=this.nr(n,t)}).next(()=>r)}rr(e,n){let r={size:0,document:Zt.newInvalidDocument(n)};return Js(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(Xs(n))},(e,t)=>{r={document:this.nr(n,t),size:As(t)}}).next(()=>r)}getEntries(e,t){let r=nr;return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n)}).next(()=>r)}sr(e,t){let r=nr,i=new pt(ue.comparator);return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n),i=i.insert(e,As(t))}).next(()=>({documents:r,_r:i}))}ir(e,t,i){if(t.isEmpty())return be.resolve();let n=new wt(ea);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(Xs(n.first()),Xs(n.last())),s=n.getIterator();let a=s.getNext();return Js(e).J({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ue.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&ea(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.$(Xs(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,r,i){const s=n.path,a=[s.popLast().toArray(),s.lastSegment(),Ui(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Js(e).U(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let t=nr;for(const i of e){const e=this.nr(ue.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Xn(n,e)||r.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=nr;var r=Zs(t,n),a=Zs(t,pe.max());return Js(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.nr(ue.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new Ws(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return Ys(e).get("remoteDocumentGlobalKey").next(e=>(B(!!e),e))}tr(e,t){return Ys(e).put("remoteDocumentGlobalKey",t)}nr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Si(e.ct,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ue.fromSegments(t.noDocument.path),i=qi(t.noDocument.readTime);n=Zt.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return U();{const e=ue.fromSegments(t.unknownDocument.path),s=qi(t.unknownDocument.version);n=Zt.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new ne(t[0],t[1]),re.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(re.min()))return e}return Zt.newInvalidDocument(e)}}function Hs(e){return new Qs(e)}class Ws extends $s{constructor(e,t){super(),this.ar=e,this.trackRemovals=t,this.ur=new tr(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,u=new wt((e,t)=>Z(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.ur.get(e);if(a.push(this.ar.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Vi(this.ar.serializer,t);u=u.add(e.path.popLast());var i=As(r);o+=i-n.size,a.push(this.ar.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=Vi(this.ar.serializer,t.convertToNoDocument(re.min()));a.push(this.ar.addEntry(s,e,o))}}),u.forEach(e=>{a.push(this.ar.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ar.updateMetadata(s,o)),be.waitFor(a)}getFromCache(e,t){return this.ar.rr(e,t).next(e=>(this.ur.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ar.sr(e,t).next(({documents:n,_r:e})=>(e.forEach((e,t)=>{this.ur.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function Ys(e){return dt(e,"remoteDocumentGlobal")}function Js(e){return dt(e,"remoteDocumentsV14")}function Xs(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Zs(e,t){const n=t.documentKey.path.toArray();return[e,Ui(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function ea(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Z(n[s],r[s]),i)return i;return i=Z(n.length,r.length),i||(i=Z(n[n.length-2],r[r.length-2]),i||Z(n[n.length-1],r[r.length-1]))}class ta{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class na{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&kr(r.mutation,e,It.empty(),ne.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,cr()).next(()=>e))}getLocalViewOfDocuments(e,t,n=cr()){const r=ar();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=ir();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=ar();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,cr()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=nr;const a=ar(),o=ar();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof Lr)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),kr(n.mutation,t,n.mutation.getFieldMask(),ne.now())):a.set(t.key,It.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new ta(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=ar();let u=new pt((e,t)=>e-t),c=cr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||It.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||cr()).add(e),u=u.insert(r.batchId,t))})}).next(()=>{const e=[],t=u.getReverseIterator();for(;t.hasNext();){const u=t.getNext(),n=u.key,r=u.value,i=ar();r.forEach(e=>{var t;c.has(e)||(null!==(t=Ar(a.get(e),o.get(e)))&&i.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return be.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n,r){return i=t,ue.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):zn(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):be.resolve(ar());let r=-1,i=n;return e.next(e=>be.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?be.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,cr())).next(e=>({batchId:r,changes:sr(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ue(t)).next(e=>{let t=ir();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s,a){const o=i.collectionGroup;let u=ir();return this.indexManager.getCollectionParents(r,o).next(e=>be.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new Bn(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s,a).next(e=>{e.forEach((e,t)=>{u=u.insert(e,t)})})}).next(()=>u))}getDocumentsMatchingCollectionQuery(t,s,n,r){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a,r))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Zt.newInvalidDocument(n)))});let i=ir();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&kr(n.mutation,t,It.empty(),ne.now()),Xn(s,t)&&(i=i.insert(e,t))}),i})}}class ra{constructor(e){this.serializer=e,this.cr=new Map,this.lr=new Map}getBundleMetadata(e,t){return be.resolve(this.cr.get(t))}saveBundleMetadata(e,t){return this.cr.set(t.id,{id:t.id,version:t.version,createTime:gi(t.createTime)}),be.resolve()}getNamedQuery(e,t){return be.resolve(this.lr.get(t))}saveNamedQuery(e,t){return this.lr.set(t.name,{name:(t=t).name,query:Ki(t.bundledQuery),readTime:gi(t.readTime)}),be.resolve()}}class ia{constructor(){this.overlays=new pt(ue.comparator),this.hr=new Map}getOverlay(e,t){return be.resolve(this.overlays.get(t))}getOverlays(e,t){const n=ar();return be.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.ht(n,r,t)}),be.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.hr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.hr.delete(n)),be.resolve()}getOverlaysForCollection(e,t,n){const r=ar(),i=t.length+1,s=new ue(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return be.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new pt((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=ar(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=ar(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return be.resolve(a)}ht(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.hr.get(r.largestBatchId).delete(n.key);this.hr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new jr(t,n));let i=this.hr.get(t);void 0===i&&(i=cr(),this.hr.set(t,i)),this.hr.set(t,i.add(n.key))}}class sa{constructor(){this.Pr=new wt(aa.Ir),this.Tr=new wt(aa.Er)}isEmpty(){return this.Pr.isEmpty()}addReference(e,t){var n=new aa(e,t);this.Pr=this.Pr.add(n),this.Tr=this.Tr.add(n)}dr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ar(new aa(e,t))}Rr(e,t){e.forEach(e=>this.removeReference(e,t))}Vr(e){const t=new ue(new se([])),n=new aa(t,e),r=new aa(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Ar(e),i.push(e.key)}),i}mr(){this.Pr.forEach(e=>this.Ar(e))}Ar(e){this.Pr=this.Pr.delete(e),this.Tr=this.Tr.delete(e)}gr(e){var t=new ue(new se([])),n=new aa(t,e),t=new aa(t,e+1);let r=cr();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new aa(e,0),t=this.Pr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class aa{constructor(e,t){this.key=e,this.pr=t}static Ir(e,t){return ue.comparator(e.key,t.key)||Z(e.pr,t.pr)}static Er(e,t){return Z(e.pr,t.pr)||ue.comparator(e.key,t.key)}}class oa{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.yr=1,this.wr=new wt(aa.Ir)}checkEmpty(e){return be.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.yr;this.yr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new Br(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.wr=this.wr.add(new aa(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return be.resolve(s)}lookupMutationBatch(e,t){return be.resolve(this.Sr(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.br(t+1),n=n<0?0:n;return be.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return be.resolve(0===this.mutationQueue.length?-1:this.yr-1)}getAllMutationBatches(e){return be.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new aa(t,0),r=new aa(t,Number.POSITIVE_INFINITY),i=[];return this.wr.forEachInRange([n,r],e=>{var t=this.Sr(e.pr);i.push(t)}),be.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new wt(Z);return t.forEach(e=>{var t=new aa(e,0),n=new aa(e,Number.POSITIVE_INFINITY);this.wr.forEachInRange([t,n],e=>{r=r.add(e.pr)})}),be.resolve(this.Dr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ue.isDocumentKey(i)||(i=i.child(""));var s=new aa(new ue(i),0);let a=new wt(Z);return this.wr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.pr)),!0)},s),be.resolve(this.Dr(a))}Dr(e){const n=[];return e.forEach(e=>{var t=this.Sr(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){B(0===this.Cr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.wr;return be.forEach(r.mutations,e=>{var t=new aa(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.wr=i})}Mn(e){}containsKey(e,t){var n=new aa(t,0),n=this.wr.firstAfterOrEqual(n);return be.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,be.resolve()}Cr(e,t){return this.br(e)}br(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Sr(e){var t=this.br(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class ua{constructor(e){this.vr=e,this.docs=new pt(ue.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.vr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return be.resolve(n?n.document.mutableCopy():Zt.newInvalidDocument(t))}getEntries(e,t){let n=nr;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Zt.newInvalidDocument(e))}),be.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=nr;const s=t.path,a=new ue(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||ye(me(a),n)<=0||(r.has(a.key)||Xn(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return be.resolve(i)}getAllFromCollectionGroup(e,t,n,r){U()}Fr(e,t){return be.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new ca(this)}getSize(e){return be.resolve(this.size)}}class ca extends $s{constructor(e){super(),this.ar=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ar.addEntry(n,t)):this.ar.removeEntry(e)}),be.waitFor(r)}getFromCache(e,t){return this.ar.getEntry(e,t)}getAllFromCache(e,t){return this.ar.getEntries(e,t)}}class ha{constructor(e){this.persistence=e,this.Mr=new tr(e=>Ln(e),On),this.lastRemoteSnapshotVersion=re.min(),this.highestTargetId=0,this.Or=0,this.Nr=new sa,this.targetCount=0,this.Lr=Os.Nn()}forEachTarget(e,n){return this.Mr.forEach((e,t)=>n(t)),be.resolve()}getLastRemoteSnapshotVersion(e){return be.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return be.resolve(this.Or)}allocateTargetId(e){return this.highestTargetId=this.Lr.next(),be.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Or&&(this.Or=t),be.resolve()}qn(e){this.Mr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Lr=new Os(t),this.highestTargetId=t),e.sequenceNumber>this.Or&&(this.Or=e.sequenceNumber)}addTargetData(e,t){return this.qn(t),this.targetCount+=1,be.resolve()}updateTargetData(e,t){return this.qn(t),be.resolve()}removeTargetData(e,t){return this.Mr.delete(t.target),this.Nr.Vr(t.targetId),--this.targetCount,be.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Mr.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Mr.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),be.waitFor(a).next(()=>s)}getTargetCount(e){return be.resolve(this.targetCount)}getTargetData(e,t){var n=this.Mr.get(t)||null;return be.resolve(n)}addMatchingKeys(e,t,n){return this.Nr.dr(t,n),be.resolve()}removeMatchingKeys(t,e,n){this.Nr.Rr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),be.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Nr.Vr(t),be.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Nr.gr(t);return be.resolve(n)}containsKey(e,t){return be.resolve(this.Nr.containsKey(t))}}class la{constructor(e,t){this.Br={},this.overlays={},this.kr=new Le(0),this.qr=!1,this.qr=!0,this.referenceDelegate=e(this),this.Qr=new ha(this),this.indexManager=new ys,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Kr(e),new ua(e)),this.serializer=new Pi(t),this.$r=new ra(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.qr=!1,Promise.resolve()}get started(){return this.qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new ia,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Br[e.toKey()];return n||(n=new oa(t,this.referenceDelegate),this.Br[e.toKey()]=n),n}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.$r}runTransaction(e,t,n){O("MemoryPersistence","Starting transaction:",e);const r=new da(this.kr.next());return this.referenceDelegate.Ur(),n(r).next(e=>this.referenceDelegate.Wr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gr(t,n){return be.or(Object.values(this.Br).map(e=>()=>e.containsKey(t,n)))}}class da extends we{constructor(e){super(),this.currentSequenceNumber=e}}class fa{constructor(e){this.persistence=e,this.zr=new sa,this.jr=null}static Hr(e){return new fa(e)}get Jr(){if(this.jr)return this.jr;throw U()}addReference(e,t,n){return this.zr.addReference(n,t),this.Jr.delete(n.toString()),be.resolve()}removeReference(e,t,n){return this.zr.removeReference(n,t),this.Jr.add(n.toString()),be.resolve()}markPotentiallyOrphaned(e,t){return this.Jr.add(t.toString()),be.resolve()}removeTarget(e,t){this.zr.Vr(t.targetId).forEach(e=>this.Jr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Jr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ur(){this.jr=new Set}Wr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return be.forEach(this.Jr,e=>{const t=ue.fromPath(e);return this.Yr(n,t).next(e=>{e||r.removeEntry(t,re.min())})}).next(()=>(this.jr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Yr(e,t).next(e=>{e?this.Jr.delete(t.toString()):this.Jr.add(t.toString())})}Kr(e){return 0}Yr(e,t){return be.or([()=>be.resolve(this.zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gr(e,t)])}}class ga{constructor(e){this.serializer=e}O(t,e,n,r){const i=new Ie("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",qe,{unique:!0}),s.createObjectStore("documentMutations"),ma(t),t.createObjectStore("remoteDocuments"));let a=be.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),ma(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:re.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").U().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",qe,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return be.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Xr(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ei(i)))),n<7&&7<=r&&(a=a.next(()=>this.ti(i))),n<8&&8<=r&&(a=a.next(()=>this.ni(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.ri(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:nt});t.createIndex("collectionPathOverlayIndex",rt,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",it,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:Ke});t.createIndex("documentKeyIndex",$e),t.createIndex("collectionGroupIndex",Qe)}(t)).next(()=>this.ii(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.si(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Xe}).createIndex("sequenceNumberIndex",Ze,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:et}).createIndex("documentKeyIndex",tt,{unique:!1})}(t))),n<16&&16<=r&&(a=a.next(()=>{e.objectStore("indexState").clear()}).next(()=>{e.objectStore("indexEntries").clear()})),a}ei(t){let n=0;return t.store("remoteDocuments").J((e,t)=>{n+=As(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Xr(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.U().next(e=>be.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.U("userMutationsIndex",e).next(e=>be.forEach(e,e=>{B(e.userId===n.userId);var t=ji(this.serializer,e);return Cs(r,n.userId,t).next(()=>{})}))}))}ti(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.J((e,t)=>{const n=new se(e),r=[0,Ve(n)];s.push(a.get(r).next(e=>e?be.resolve():(e=>a.put({targetId:0,path:Ve(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>be.waitFor(s))})}ni(e,t){e.createObjectStore("collectionParents",{keyPath:Je});const n=t.store("collectionParents"),r=new vs,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Ve(r)})}};return t.store("remoteDocuments").J({H:!0},(e,t)=>{const n=new se(e);return i(n.popLast())}).next(()=>t.store("documentMutations").J({H:!0},([,e],t)=>{const n=Be(e);return i(n.popLast())}))}ri(e){const r=e.store("targets");return r.J((e,t)=>{var n=Gi(t),n=zi(this.serializer,n);return r.put(n)})}ii(e,a){const t=a.store("remoteDocuments"),o=[];return t.J((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ue(se.fromString(s.document.name).popFirst(5)):s.noDocument?ue.fromSegments(s.noDocument.path):s.unknownDocument?ue.fromSegments(s.unknownDocument.path):U()).path.toArray(),i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};var s;o.push(n.put(i))}).next(()=>be.waitFor(o))}si(e,s){const t=s.store("mutations"),a=Hs(this.serializer),o=new la(fa.Hr,this.serializer.ct);return t.U().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:cr();ji(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),be.forEach(r,(e,t)=>{var n=new k(t),r=Xi.lt(this.serializer,n),i=o.getIndexManager(n),n=Ns.lt(n,this.serializer,i,o.referenceDelegate);return new na(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new lt(s,Le.oe),e).next()})})}}function ma(e){e.createObjectStore("targetDocuments",{keyPath:We}).createIndex("documentTargetsIndex",Ye,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",He,{unique:!0}),e.createObjectStore("targetGlobal")}const pa="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class ya{constructor(e,t,n,r,i,s,a,o,u,c,h=16){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.oi=i,this.window=s,this.document=a,this._i=u,this.ai=c,this.ui=h,this.kr=null,this.qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.li=null,this.hi=null,this.Pi=Number.NEGATIVE_INFINITY,this.Ii=e=>Promise.resolve(),!ya.D())throw new j(q.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new zs(this,r),this.Ti=t+"main",this.serializer=new Pi(o),this.Ei=new Ee(this.Ti,this.ui,new ga(this.serializer)),this.Qr=new Fs(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Hs(this.serializer),this.$r=new Wi,this.window&&this.window.localStorage?this.di=this.window.localStorage:(this.di=null,!1===c&&F("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Ai().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new j(q.FAILED_PRECONDITION,pa);return this.Ri(),this.Vi(),this.mi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Qr.getHighestSequenceNumber(e))}).then(e=>{this.kr=new Le(e,this._i)}).then(()=>{this.qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}fi(t){return this.Ii=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.oi.enqueueAndForget(async()=>{this.started&&await this.Ai()}))}Ai(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>wa(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.gi(t).next(e=>{e||(this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)))})}).next(()=>this.pi(t)).next(e=>this.isPrimary&&!e?this.yi(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(De(e))return O("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return O("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.oi.enqueueRetryable(()=>this.Ii(e)),this.isPrimary=e})}gi(e){return va(e).get("owner").next(e=>be.resolve(this.Si(e)))}bi(e){return wa(e).delete(this.clientId)}async Di(){if(this.isPrimary&&!this.Ci(this.Pi,18e5)){this.Pi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=dt(e,"clientMetadata");return r.U().next(e=>{const t=this.vi(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return be.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.di)for(const t of e)this.di.removeItem(this.Fi(t.clientId))}}mi(){this.hi=this.oi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ai().then(()=>this.Di()).then(()=>this.mi()))}Si(e){return!!e&&e.ownerId===this.clientId}pi(t){return this.ai?be.resolve(!0):va(t).get("owner").next(e=>{if(null!==e&&this.Ci(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)){if(this.Si(e)&&this.networkEnabled)return!0;if(!this.Si(e)){if(!e.allowTabSynchronization)throw new j(q.FAILED_PRECONDITION,pa);return!1}}return!(!this.networkEnabled||!this.inForeground)||wa(t).U().next(e=>void 0===this.vi(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&O("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.qr=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Oi(),this.Ni(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new lt(e,Le.oe);return this.yi(t).next(()=>this.bi(t))}),this.Ei.close(),this.Li()}vi(e,t){return e.filter(e=>this.Ci(e.updateTimeMs,t)&&!this.Mi(e.clientId))}Bi(){return this.runTransaction("getActiveClients","readonly",e=>wa(e).U().next(e=>this.vi(e,18e5).map(e=>e.clientId)))}get started(){return this.qr}getMutationQueue(e,t){return Ns.lt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new _s(e,this.serializer.ct.databaseId)}getDocumentOverlayCache(e){return Xi.lt(this.serializer,e)}getBundleCache(){return this.$r}runTransaction(t,n,r){O("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=16===(e=this.ui)?ht:15===e?ct:14===e?ut:13===e?ot:12===e?at:11===e?st:void U();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new lt(e,this.kr?this.kr.next():Le.oe),"readwrite-primary"===n?this.gi(a).next(e=>!!e||this.pi(a)).next(e=>{if(!e)throw F(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)),new j(q.FAILED_PRECONDITION,ve);return r(a)}).next(e=>this.wi(a).next(()=>e)):this.ki(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ki(e){return va(e).get("owner").next(e=>{if(null!==e&&this.Ci(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)&&!this.Si(e)&&!(this.ai||this.allowTabSynchronization&&e.allowTabSynchronization))throw new j(q.FAILED_PRECONDITION,pa)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return va(e).put("owner",t)}static D(){return Ee.D()}yi(e){const t=va(e);return t.get("owner").next(e=>this.Si(e)?(O("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):be.resolve())}Ci(e,t){var n=Date.now();return!(e<n-t||n<e&&(F(`Detected an update time that is in the future: ${e} > ${n}`),1))}Ri(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.li=()=>{this.oi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ai()))},this.document.addEventListener("visibilitychange",this.li),this.inForeground="visible"===this.document.visibilityState)}Oi(){this.li&&(this.document.removeEventListener("visibilitychange",this.li),this.li=null)}Vi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();var e=/(?:Version|Mobile)\/1[456]/;h()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.oi.enterRestrictedMode(!0),this.oi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}Ni(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Mi(e){var t;try{var n=null!==(null===(t=this.di)||void 0===t?void 0:t.getItem(this.Fi(e)));return O("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return F("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this.di)try{this.di.setItem(this.Fi(this.clientId),String(Date.now()))}catch(e){F("Failed to set zombie client id.",e)}}Li(){if(this.di)try{this.di.removeItem(this.Fi(this.clientId))}catch(e){}}Fi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function va(e){return dt(e,"owner")}function wa(e){return dt(e,"clientMetadata")}function _a(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class ba{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.qi=n,this.Qi=r}static Ki(e,t){let n=cr(),r=cr();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new ba(e,t.fromCache,n,r)}}class Ia{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Ea{constructor(){this.$i=!1,this.Ui=!1,this.Wi=100,this.Gi=h()?8:0<Te(u())?6:4}initialize(e,t){this.zi=e,this.indexManager=t,this.$i=!0}getDocumentsMatchingQuery(n,r,e,t){const i={result:null};return this.ji(n,r).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.Hi(n,r,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){const t=new Ia;return this.Ji(n,r,t).next(e=>{if(i.result=e,this.Ui)return this.Yi(n,r,t,e.size)})}}).next(()=>i.result)}Yi(e,t,n,r){return n.documentReadCount<this.Wi?(L()<=l.DEBUG&&O("QueryEngine","SDK will not create cache indexes for query:",Jn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Wi,"documents"),be.resolve()):(L()<=l.DEBUG&&O("QueryEngine","Query:",Jn(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Gi*r?(L()<=l.DEBUG&&O("QueryEngine","The SDK decides to create cache indexes for query:",Jn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,$n(t))):be.resolve())}ji(i,s){if(Gn(s))return be.resolve(null);let t=$n(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Hn(s,null,"F"),t=$n(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=cr(...e);return this.zi.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Zi(s,n);return this.Xi(s,t,r,e.readTime)?this.ji(i,Hn(s,null,"F")):this.es(i,t,s,e)}))})))}Hi(n,r,i,s){return Gn(r)||s.isEqual(re.min())?be.resolve(null):this.zi.getDocuments(n,i).next(e=>{var t=this.Zi(r,e);return this.Xi(r,t,i,s)?be.resolve(null):(L()<=l.DEBUG&&O("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Jn(r)),this.es(n,t,r,ge(s,-1)).next(e=>e))})}Zi(n,e){let r=new wt(er(n));return e.forEach((e,t)=>{Xn(n,t)&&(r=r.add(t))}),r}Xi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Ji(e,t,n){return L()<=l.DEBUG&&O("QueryEngine","Using full collection scan to execute query:",Jn(t)),this.zi.getDocumentsMatchingQuery(e,t,pe.min(),n)}es(e,n,t,r){return this.zi.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class Ta{constructor(e,t,n,r){this.persistence=e,this.ts=t,this.serializer=r,this.ns=new pt(Z),this.rs=new tr(e=>Ln(e),On),this.ss=new Map,this.os=e.getRemoteDocumentCache(),this.Qr=e.getTargetCache(),this.$r=e.getBundleCache(),this._s(n)}_s(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new na(this.os,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.os.setIndexManager(this.indexManager),this.ts.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ns))}}function Sa(e,t,n,r){return new Ta(e,t,n,r)}async function xa(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a._s(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=cr();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({us:e,removedBatchIds:t,addedBatchIds:n}))})})}function Da(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Qr.getLastRemoteSnapshotVersion(e))}function Ca(e,c){const h=e,l=c.snapshotVersion;let d=h.ns;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h.os.newChangeBuffer({trackRemovals:!0});d=h.ns;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Qr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Qr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==c.targetMismatches.get(n)?e=e.withResumeToken(Tt.EMPTY_BYTE_STRING,re.min()).withLastLimboFreeSnapshotVersion(re.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(h.Qr.updateTargetData(o,e))}});let t=nr,n=cr();if(c.documentUpdates.forEach(e=>{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(Aa(o,e,c.documentUpdates).next(e=>{t=e.cs,n=e.ls})),!l.isEqual(re.min())){const c=h.Qr.getLastRemoteSnapshotVersion(o).next(e=>h.Qr.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return be.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.ns=d,e))}function Aa(e,s,t){let n=cr(),a=cr();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=nr;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(re.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):O("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{cs:i,ls:a}})}function Na(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Qr.getTargetData(t,r).next(e=>e?(n=e,be.resolve(n)):i.Qr.allocateTargetId(t).next(e=>(n=new Fi(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Qr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.ns.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.ns=i.ns.insert(e.targetId,e),i.rs.set(r,e.targetId)),e})}async function ka(e,t,n){const r=e,i=r.ns.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!De(e))throw e;O("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ns=r.ns.remove(t),r.rs.delete(i.target)}function Ra(e,n,r){const i=e;let s=re.min(),a=cr();return i.persistence.runTransaction("Execute query","readwrite",t=>function(e,t,n){const r=e,i=r.rs.get(n);return void 0!==i?be.resolve(r.ns.get(i)):r.Qr.getTargetData(t,n)}(i,t,$n(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Qr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.ts.getDocumentsMatchingQuery(t,n,r?s:re.min(),r?a:cr())).next(e=>(Oa(i,Zn(n),e),{documents:e,hs:a})))}function Ma(e,t){const n=e,r=n.Qr,i=n.ns.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.ot(e,t).next(e=>e?e.target:null))}function La(e,t){const n=e,r=n.ss.get(t)||re.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.os.getAllFromCollectionGroup(e,t,ge(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Oa(n,t,e),e))}function Oa(e,t,n){let r=e.ss.get(t)||re.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.ss.set(t,r)}function Fa(e,t){return`firestore_clients_${e}_${t}`}function Pa(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Va(e,t){return`firestore_targets_${e}_${t}`}class Ua{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Es(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new j(r.error.code,r.error.message))),s?new Ua(e,t,r.state,i):(F("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}ds(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Ba{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Es(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new j(n.error.code,n.error.message))),i?new Ba(e,n.state,r):(F("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}ds(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class qa{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Es(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=hr;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Pe(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new qa(e,i):(F("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class ja{constructor(e,t){this.clientId=e,this.onlineState=t}static Es(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new ja(t.clientId,t.onlineState):(F("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Ga{constructor(){this.activeTargetIds=hr}As(e){this.activeTargetIds=this.activeTargetIds.add(e)}Rs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}ds(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class za{constructor(e,t,n,r,i){this.window=e,this.oi=t,this.persistenceKey=n,this.Vs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.fs=this.gs.bind(this),this.ps=new pt(Z),this.started=!1,this.ys=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.ws=Fa(this.persistenceKey,this.Vs),this.Ss=`firestore_sequence_number_${this.persistenceKey}`,this.ps=this.ps.insert(this.Vs,new Ga),this.bs=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Ds=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Cs=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.vs=`firestore_online_state_${this.persistenceKey}`,this.Fs=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.fs)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Bi();for(const n of e)if(n!==this.Vs){const e=this.getItem(Fa(this.persistenceKey,n));var t;!e||(t=qa.Es(n,e))&&(this.ps=this.ps.insert(t.clientId,t))}this.Ms();const n=this.storage.getItem(this.vs);if(n){const e=this.xs(n);e&&this.Os(e)}for(const e of this.ys)this.gs(e);this.ys=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ss,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ns(this.ps)}isActiveQueryTarget(n){let r=!1;return this.ps.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Ls(e,"pending")}updateMutationState(e,t,n){this.Ls(e,t,n),this.Bs(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Va(this.persistenceKey,e)))||(n=Ba.Es(e,n))&&(t=n.state)),this.ks.As(e),this.Ms(),t}removeLocalQueryTarget(e){this.ks.Rs(e),this.Ms()}isLocalQueryTarget(e){return this.ks.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Va(this.persistenceKey,e))}updateQueryState(e,t,n){this.qs(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Bs(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Qs(e)}notifyBundleLoaded(e){this.Ks(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.fs),this.removeItem(this.ws),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return O("SharedClientState","READ",e,t),t}setItem(e,t){O("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){O("SharedClientState","REMOVE",e),this.storage.removeItem(e)}gs(e){const i=e;i.storageArea===this.storage&&(O("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.ws?this.oi.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.bs.test(i.key)){if(null==i.newValue){var e=this.$s(i.key);return this.Us(e,null)}e=this.Ws(i.key,i.newValue);if(e)return this.Us(e.clientId,e)}else if(this.Ds.test(i.key)){if(null!==i.newValue){var t=this.Gs(i.key,i.newValue);if(t)return this.zs(t)}}else if(this.Cs.test(i.key)){if(null!==i.newValue){t=this.js(i.key,i.newValue);if(t)return this.Hs(t)}}else if(i.key===this.vs){if(null!==i.newValue){var n=this.xs(i.newValue);if(n)return this.Os(n)}}else if(i.key===this.Ss){n=function(e){let t=Le.oe;if(null!=e)try{var n=JSON.parse(e);B("number"==typeof n),t=n}catch(e){F("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==Le.oe&&this.sequenceNumberHandler(n)}else if(i.key===this.Fs){const r=this.Js(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Ys(e)))}}else this.ys.push(i)}):F("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get ks(){return this.ps.get(this.Vs)}Ms(){this.setItem(this.ws,this.ks.ds())}Ls(e,t,n){const r=new Ua(this.currentUser,e,t,n),i=Pa(this.persistenceKey,this.currentUser,e);this.setItem(i,r.ds())}Bs(e){var t=Pa(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Qs(e){var t={clientId:this.Vs,onlineState:e};this.storage.setItem(this.vs,JSON.stringify(t))}qs(e,t,n){const r=Va(this.persistenceKey,e),i=new Ba(e,t,n);this.setItem(r,i.ds())}Ks(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Fs,t)}$s(e){var t=this.bs.exec(e);return t?t[1]:null}Ws(e,t){var n=this.$s(e);return qa.Es(n,t)}Gs(e,t){var n=this.Ds.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Ua.Es(new k(n),r,t)}js(e,t){var n=this.Cs.exec(e),n=Number(n[1]);return Ba.Es(n,t)}xs(e){return ja.Es(e)}Js(e){return JSON.parse(e)}async zs(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Zs(e.batchId,e.state,e.error);O("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Hs(e){return this.syncEngine.Xs(e.targetId,e.state,e.error)}Us(e,t){const n=t?this.ps.insert(e,t):this.ps.remove(e),r=this.Ns(this.ps),i=this.Ns(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.eo(s,a).then(()=>{this.ps=n})}Os(e){this.ps.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ns(e){let n=hr;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Ka{constructor(){this.no=new Ga,this.ro={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.no.As(e),this.ro[e]||"not-current"}updateQueryState(e,t,n){this.ro[e]=t}removeLocalQueryTarget(e){this.no.Rs(e)}isLocalQueryTarget(e){return this.no.activeTargetIds.has(e)}clearQueryState(e){delete this.ro[e]}getAllActiveQueryTargets(){return this.no.activeTargetIds}isActiveQueryTarget(e){return this.no.activeTargetIds.has(e)}start(){return this.no=new Ga,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class $a{io(e){}shutdown(){}}class Qa{constructor(){this.so=()=>this.oo(),this._o=()=>this.ao(),this.uo=[],this.co()}io(e){this.uo.push(e)}shutdown(){window.removeEventListener("online",this.so),window.removeEventListener("offline",this._o)}co(){window.addEventListener("online",this.so),window.addEventListener("offline",this._o)}oo(){O("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.uo)e(0)}ao(){O("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.uo)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Ha=null;function Wa(){return null===Ha?Ha=268435456+Math.round(2147483648*Math.random()):Ha++,"0x"+Ha.toString(16)}const Ya={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Ja{constructor(e){this.lo=e.lo,this.ho=e.ho}Po(e){this.Io=e}To(e){this.Eo=e}Ao(e){this.Ro=e}onMessage(e){this.Vo=e}close(){this.ho()}send(e){this.lo(e)}mo(){this.Io()}fo(){this.Eo()}po(e){this.Ro(e)}yo(e){this.Vo(e)}}const Xa="WebChannelConnection";class Za extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.wo=t+"://"+e.host,this.So=`projects/${n}/databases/${r}`,this.bo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get Do(){return!1}Co(t,e,n,r,i){const s=Wa(),a=this.vo(t,e.toUriEncodedString());O("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.So,"x-goog-request-params":this.bo};return this.Fo(o,r,i),this.Mo(t,a,o,n).then(e=>(O("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw P("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}xo(e,t,n,r,i,s){return this.Co(e,t,n,r,i)}Fo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+R,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}vo(e,t){var n=Ya[e];return`${this.wo}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Mo(u,t,n,r){const c=Wa();return new Promise((s,a)=>{const o=new dn;o.setWithCredentials(!0),o.listenOnce(mn.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case pn.NO_ERROR:var e=o.getResponseJson();O(Xa,`XHR for RPC '${u}' ${c} received:`,JSON.stringify(e)),s(e);break;case pn.TIMEOUT:O(Xa,`RPC '${u}' ${c} timed out`),a(new j(q.DEADLINE_EXCEEDED,"Request time out"));break;case pn.HTTP_ERROR:var t=o.getStatus();if(O(Xa,`RPC '${u}' ${c} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const u=(r=n.status,i=r.toLowerCase().replace(/_/g,"-"),0<=Object.values(q).indexOf(i)?i:q.UNKNOWN);a(new j(u,n.message))}else a(new j(q.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new j(q.UNAVAILABLE,"Connection failed."));break;default:U()}}finally{O(Xa,`RPC '${u}' ${c} completed.`)}var r,i});var e=JSON.stringify(r);O(Xa,`RPC '${u}' ${c} sending request:`,r),o.send(t,"POST",e,n,15)})}Oo(i,e,t){const s=Wa(),n=[this.wo,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=_n(),a=wn(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(o.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(o.xmlHttpFactory=new fn({})),this.Fo(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var c=n.join("");O(Xa,`Creating RPC '${i}' stream ${s}: ${c}`,o);const h=r.createWebChannel(c,o);let l=!1,d=!1;const f=new Ja({lo:e=>{d?O(Xa,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(l||(O(Xa,`Opening RPC '${i}' stream ${s} transport.`),h.open(),l=!0),O(Xa,`RPC '${i}' stream ${s} sending:`,e),h.send(e))},ho:()=>h.close()}),g=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return g(h,gn.EventType.OPEN,()=>{d||(O(Xa,`RPC '${i}' stream ${s} transport opened.`),f.mo())}),g(h,gn.EventType.CLOSE,()=>{d||(d=!0,O(Xa,`RPC '${i}' stream ${s} transport closed`),f.po())}),g(h,gn.EventType.ERROR,e=>{d||(d=!0,P(Xa,`RPC '${i}' stream ${s} transport errored:`,e),f.po(new j(q.UNAVAILABLE,"The operation could not be completed")))}),g(h,gn.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];B(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){O(Xa,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=x[e];if(void 0!==t)return Kr(t)}(n),t=r.message;void 0===e&&(e=q.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,f.po(new j(e,t)),h.close()}else O(Xa,`RPC '${i}' stream ${s} received:`,e),f.yo(e)}}),g(a,vn.STAT_EVENT,e=>{e.stat===yn.PROXY?O(Xa,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===yn.NOPROXY&&O(Xa,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{f.fo()},0),f}}function eo(){return"undefined"!=typeof window?window:null}function to(){return"undefined"!=typeof document?document:null}function no(e){return new hi(e,!0)}class ro{constructor(e,t,n=1e3,r=1.5,i=6e4){this.oi=e,this.timerId=t,this.No=n,this.Lo=r,this.Bo=i,this.ko=0,this.qo=null,this.Qo=Date.now(),this.reset()}reset(){this.ko=0}Ko(){this.ko=this.Bo}$o(e){this.cancel();var t=Math.floor(this.ko+this.Uo()),n=Math.max(0,Date.now()-this.Qo),r=Math.max(0,t-n);0<r&&O("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.ko} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.qo=this.oi.enqueueAfterDelay(this.timerId,r,()=>(this.Qo=Date.now(),e())),this.ko*=this.Lo,this.ko<this.No&&(this.ko=this.No),this.ko>this.Bo&&(this.ko=this.Bo)}Wo(){null!==this.qo&&(this.qo.skipDelay(),this.qo=null)}cancel(){null!==this.qo&&(this.qo.cancel(),this.qo=null)}Uo(){return(Math.random()-.5)*this.ko}}class io{constructor(e,t,n,r,i,s,a,o){this.oi=e,this.Go=n,this.zo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.jo=0,this.Ho=null,this.Jo=null,this.stream=null,this.Yo=new ro(e,t)}Zo(){return 1===this.state||5===this.state||this.Xo()}Xo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.e_()}async stop(){this.Zo()&&await this.close(0)}t_(){this.state=0,this.Yo.reset()}n_(){this.Xo()&&null===this.Ho&&(this.Ho=this.oi.enqueueAfterDelay(this.Go,6e4,()=>this.r_()))}i_(e){this.s_(),this.stream.send(e)}async r_(){if(this.Xo())return this.close(0)}s_(){this.Ho&&(this.Ho.cancel(),this.Ho=null)}o_(){this.Jo&&(this.Jo.cancel(),this.Jo=null)}async close(e,t){this.s_(),this.o_(),this.Yo.cancel(),this.jo++,4!==e?this.Yo.reset():t&&t.code===q.RESOURCE_EXHAUSTED?(F(t.toString()),F("Using maximum backoff delay to prevent overloading the backend."),this.Yo.Ko()):t&&t.code===q.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.__(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ao(t)}__(){}auth(){this.state=1;const e=this.a_(this.jo),n=this.jo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.jo===n&&this.u_(e,t)},t=>{e(()=>{var e=new j(q.UNKNOWN,"Fetching auth token failed: "+t.message);return this.c_(e)})})}u_(e,t){const n=this.a_(this.jo);this.stream=this.l_(e,t),this.stream.Po(()=>{n(()=>this.listener.Po())}),this.stream.To(()=>{n(()=>(this.state=2,this.Jo=this.oi.enqueueAfterDelay(this.zo,1e4,()=>(this.Xo()&&(this.state=3),Promise.resolve())),this.listener.To()))}),this.stream.Ao(e=>{n(()=>this.c_(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}e_(){this.state=5,this.Yo.$o(async()=>{this.state=0,this.start()})}c_(e){return O("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}a_(t){return e=>{this.oi.enqueueAndForget(()=>this.jo===t?e():(O("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class so extends io{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}l_(e,t){return this.connection.Oo("Listen",e,t)}onMessage(e){this.Yo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:U(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.useProto3Json?(B(void 0===f||"string"==typeof f),Tt.fromBase64String(f||"")):(B(void 0===f||f instanceof Buffer||f instanceof Uint8Array),Tt.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?q.UNKNOWN:Kr(f.code),new j(o,f.message||""));n=new ni(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var s=wi(e,u.document.name),o=gi(u.document.updateTime),c=u.document.createTime?gi(u.document.createTime):re.min(),h=new Xt({mapValue:{fields:u.document.fields}}),c=Zt.newFoundDocument(s,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new ei(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=wi(e,h.document),c=h.readTime?gi(h.readTime):re.min(),c=Zt.newNoDocument(u,c),h=h.removedTargetIds||[];n=new ei([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=wi(e,l.document),l=l.removedTargetIds||[];n=new ei([],l,d,null)}else{if(!("filter"in t))return U();{t.filter;const e=t.filter;e.targetId;var{count:l=0,unchangedNames:d}=e,l=new Gr(l,d),d=e.targetId;n=new ti(d,l)}}var o,f;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return re.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?gi(t.readTime):re.min()}(e);return this.listener.h_(t,n)}P_(e){const t={};t.database=Ii(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=Fn(r)?{documents:Ci(e,r)}:{query:Ai(e,r)._t},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=fi(e,t.resumeToken);const r=li(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(re.min())){n.readTime=di(e,t.snapshotVersion.toTimestamp());const r=li(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,n=(this.serializer,e,null==(n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return U()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.i_(t)}I_(e){const t={};t.database=Ii(this.serializer),t.removeTarget=e,this.i_(t)}}class ao extends io{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.T_=!1}get E_(){return this.T_}start(){this.T_=!1,this.lastStreamToken=void 0,super.start()}__(){this.T_&&this.d_([])}l_(e,t){return this.connection.Oo("Write",e,t)}onMessage(e){if(B(!!e.streamToken),this.lastStreamToken=e.streamToken,this.T_){this.Yo.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(B(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?gi(e.updateTime):gi(t);return n.isEqual(re.min())&&(n=gi(t)),new Sr(n,e.transformResults||[])}(e,i))):[]),n=gi(e.commitTime);return this.listener.A_(n,t)}var r,i;return B(!e.writeResults||0===e.writeResults.length),this.T_=!0,this.listener.R_()}V_(){const e={};e.database=Ii(this.serializer),this.i_(e)}d_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>xi(this.serializer,e))};this.i_(t)}}class oo extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.m_=!1}f_(){if(this.m_)throw new j(q.FAILED_PRECONDITION,"The client has already been terminated.")}Co(n,r,i,s){return this.f_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Co(n,pi(r,i),s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===q.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new j(q.UNKNOWN,e.toString())})}xo(n,r,i,s,a){return this.f_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.xo(n,pi(r,i),s,e,t,a)).catch(e=>{throw"FirebaseError"===e.name?(e.code===q.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new j(q.UNKNOWN,e.toString())})}terminate(){this.m_=!0,this.connection.terminate()}}class uo{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.g_=0,this.p_=null,this.y_=!0}w_(){0===this.g_&&(this.S_("Unknown"),this.p_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.p_=null,this.b_("Backend didn't respond within 10 seconds."),this.S_("Offline"),Promise.resolve())))}D_(e){"Online"===this.state?this.S_("Unknown"):(this.g_++,1<=this.g_&&(this.C_(),this.b_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.S_("Offline")))}set(e){this.C_(),this.g_=0,"Online"===e&&(this.y_=!1),this.S_(e)}S_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}b_(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.y_?(F(t),this.y_=!1):O("OnlineStateTracker",t)}C_(){null!==this.p_&&(this.p_.cancel(),this.p_=null)}}class co{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.v_=[],this.F_=new Map,this.M_=new Set,this.x_=[],this.O_=i,this.O_.io(e=>{n.enqueueAndForget(async()=>{wo(this)&&(O("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.M_.add(4),await lo(t),t.N_.set("Unknown"),t.M_.delete(4),await ho(t)}(this))})}),this.N_=new uo(n,r)}}async function ho(e){if(wo(e))for(const t of e.x_)await t(!0)}async function lo(e){for(const t of e.x_)await t(!1)}function fo(e,t){const n=e;n.F_.has(t.targetId)||(n.F_.set(t.targetId,t),vo(n)?yo(n):Ao(n).Xo()&&mo(n,t))}function go(e,t){const n=e,r=Ao(n);n.F_.delete(t),r.Xo()&&po(n,t),0===n.F_.size&&(r.Xo()?r.n_():wo(n)&&n.N_.set("Unknown"))}function mo(e,t){var n;e.L_.xe(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(re.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),Ao(e).P_(t)}function po(e,t){e.L_.xe(t),Ao(e).I_(t)}function yo(t){t.L_=new ii({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),ot:e=>t.F_.get(e)||null,tt:()=>t.datastore.serializer.databaseId}),Ao(t).start(),t.N_.w_()}function vo(e){return wo(e)&&!Ao(e).Zo()&&0<e.F_.size}function wo(e){return 0===e.M_.size}function _o(e){e.L_=void 0}async function bo(e,t,n){if(!De(t))throw t;e.M_.add(1),await lo(e),e.N_.set("Offline"),n=n||(()=>Da(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{O("RemoteStore","Retrying IndexedDB access"),await n(),e.M_.delete(1),await ho(e)})}function Io(t,n){return n().catch(e=>bo(t,e,n))}async function Eo(e){const t=e,n=No(t);let r=0<t.v_.length?t.v_[t.v_.length-1].batchId:-1;for(;wo(i=t)&&i.v_.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.v_.length&&n.n_();break}r=e.batchId,function(e,t){e.v_.push(t);const n=No(e);n.Xo()&&n.E_&&n.d_(t.mutations)}(t,e)}catch(e){await bo(t,e)}var i;To(t)&&So(t)}function To(e){return wo(e)&&!No(e).Zo()&&0<e.v_.length}function So(e){No(e).start()}async function xo(e,t){t&&No(e).E_&&await async function(e,t){if(zr(n=t.code)&&n!==q.ABORTED){const r=e.v_.shift();No(e).t_(),await Io(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await Eo(e)}var n}(e,t),To(e)&&So(e)}async function Do(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),O("RemoteStore","RemoteStore received new credentials");var r=wo(n);n.M_.add(3),await lo(n),r&&n.N_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.M_.delete(3),await ho(n)}async function Co(e,t){const n=e;t?(n.M_.delete(2),await ho(n)):(n.M_.add(2),await lo(n),n.N_.set("Unknown"))}function Ao(t){return t.B_||(t.B_=function(e,t,n){const r=e;return r.f_(),new so(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Po:(async function(e){e.N_.set("Online")}).bind(null,t),To:(async function(n){n.F_.forEach((e,t)=>{mo(n,e)})}).bind(null,t),Ao:(async function(e,t){_o(e),vo(e)?(e.N_.D_(t),yo(e)):e.N_.set("Unknown")}).bind(null,t),h_:(async function(e,t,n){if(e.N_.set("Online"),t instanceof ni&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.F_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.F_.delete(r),e.L_.removeTarget(r))}(e,t)}catch(n){O("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await bo(e,n)}else if(t instanceof ei?e.L_.Ke(t):t instanceof ti?e.L_.He(t):e.L_.We(t),!n.isEqual(re.min()))try{const t=await Da(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.L_.rt(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.F_.get(t);n&&i.F_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.F_.get(e);var r;n&&(i.F_.set(e,n.withResumeToken(Tt.EMPTY_BYTE_STRING,n.snapshotVersion)),po(i,e),r=new Fi(n.target,e,t,n.sequenceNumber),mo(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){O("RemoteStore","Failed to raise snapshot:",t),await bo(e,t)}}).bind(null,t)}),t.x_.push(async e=>{e?(t.B_.t_(),vo(t)?yo(t):t.N_.set("Unknown")):(await t.B_.stop(),_o(t))})),t.B_}function No(t){return t.k_||(t.k_=function(e,t,n){const r=e;return r.f_(),new ao(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Po:()=>Promise.resolve(),To:(async function(e){No(e).V_()}).bind(null,t),Ao:xo.bind(null,t),R_:(async function(e){const t=No(e);for(const n of e.v_)t.d_(n.mutations)}).bind(null,t),A_:(async function(e,t,n){const r=e.v_.shift(),i=qr.from(r,t,n);await Io(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await Eo(e)}).bind(null,t)}),t.x_.push(async e=>{e?(t.k_.t_(),await Eo(t)):(await t.k_.stop(),0<t.v_.length&&(O("RemoteStore",`Stopping write stream with ${t.v_.length} pending writes`),t.v_=[]))})),t.k_}class ko{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new G,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new ko(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new j(q.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Ro(e,t){if(F("AsyncQueue",`${t}: ${e}`),De(e))return new j(q.UNAVAILABLE,`${t}: ${e}`);throw e}class Mo{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ue.comparator(e.key,t.key):(e,t)=>ue.comparator(e.key,t.key),this.keyedMap=ir(),this.sortedSet=new pt(this.comparator)}static emptySet(e){return new Mo(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Mo))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new Mo;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Lo{constructor(){this.q_=new pt(ue.comparator)}track(e){var t=e.doc.key,n=this.q_.get(t);!n||0!==e.type&&3===n.type?this.q_=this.q_.insert(t,e):3===e.type&&1!==n.type?this.q_=this.q_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.q_=this.q_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.q_=this.q_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.q_=this.q_.remove(t):1===e.type&&2===n.type?this.q_=this.q_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.q_=this.q_.insert(t,{type:2,doc:e.doc}):U()}Q_(){const n=[];return this.q_.inorderTraversal((e,t)=>{n.push(t)}),n}}class Oo{constructor(e,t,n,r,i,s,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new Oo(e,t,Mo.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Wn(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Fo{constructor(){this.K_=void 0,this.U_=[]}W_(){return this.U_.some(e=>e.G_())}}class Po{constructor(){this.queries=new tr(e=>Yn(e),Wn),this.onlineState="Unknown",this.z_=new Set}}async function Vo(e,t){const n=e;let r=3;var i=t.query;let s=n.queries.get(i);s?!s.W_()&&t.G_()&&(r=2):(s=new Fo,r=t.G_()?0:1);try{switch(r){case 0:s.K_=await n.onListen(i,!0);break;case 1:s.K_=await n.onListen(i,!1);break;case 2:await n.onFirstRemoteStoreListen(i)}}catch(e){const n=Ro(e,`Initialization of query '${Jn(t.query)}' failed`);return void t.onError(n)}n.queries.set(i,s),s.U_.push(t),t.j_(n.onlineState),!s.K_||t.H_(s.K_)&&Bo(n)}async function Uo(e,t){const n=e,r=t.query;let i=3;const s=n.queries.get(r);if(s){const e=s.U_.indexOf(t);0<=e&&(s.U_.splice(e,1),0===s.U_.length?i=t.G_()?0:1:!s.W_()&&t.G_()&&(i=2))}switch(i){case 0:return n.queries.delete(r),n.onUnlisten(r,!0);case 1:return n.queries.delete(r),n.onUnlisten(r,!1);case 2:return n.onLastRemoteStoreUnlisten(r);default:return}}function Bo(e){e.z_.forEach(e=>{e.next()})}(D=D||{}).J_="default",D.Cache="cache";class qo{constructor(e,t,n){this.query=e,this.Y_=t,this.Z_=!1,this.X_=null,this.onlineState="Unknown",this.options=n||{}}H_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Oo(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Z_?this.ea(e)&&(this.Y_.next(e),t=!0):this.ta(e,this.onlineState)&&(this.na(e),t=!0),this.X_=e,t}onError(e){this.Y_.error(e)}j_(e){this.onlineState=e;let t=!1;return this.X_&&!this.Z_&&this.ta(this.X_,e)&&(this.na(this.X_),t=!0),t}ta(e,t){return!e.fromCache||(!this.G_()||(!this.options.ra||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t))}ea(e){if(0<e.docChanges.length)return!0;var t=this.X_&&this.X_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}na(e){e=Oo.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Z_=!0,this.Y_.next(e)}G_(){return this.options.source!==D.Cache}}class jo{constructor(e,t){this.ia=e,this.byteLength=t}sa(){return"metadata"in this.ia}}class Go{constructor(e){this.serializer=e}Ps(e){return wi(this.serializer,e)}Is(e){return e.metadata.exists?Si(this.serializer,e.document,!1):Zt.newNoDocument(this.Ps(e.metadata.name),this.Ts(e.metadata.readTime))}Ts(e){return gi(e)}}class zo{constructor(e,t,n){this.oa=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Ko(e)}_a(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ia.namedQuery)this.queries.push(e.ia.namedQuery);else if(e.ia.documentMetadata){this.documents.push({metadata:e.ia.documentMetadata}),e.ia.documentMetadata.exists||++t;const n=se.fromString(e.ia.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ia.document&&(this.documents[this.documents.length-1].document=e.ia.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}aa(e){const t=new Map,n=new Go(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.Ps(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||cr()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=cr(),a=nr;for(const e of n){const n=t.Ps(e.metadata.name);e.document&&(s=s.add(n));const c=t.Is(e);c.setReadTime(t.Ts(e.metadata.readTime)),a=a.insert(n,c)}const o=i.os.newChangeBuffer({trackRemovals:!0}),u=await Na(i,(r=r,$n(jn(se.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>Aa(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Qr.removeMatchingKeysForTargetId(t,u.targetId).next(()=>i.Qr.addMatchingKeys(t,s,u.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.cs,e.ls)).next(()=>e.cs)))}(this.localStore,new Go(this.serializer),this.documents,this.oa.id),t=this.aa(this.documents);for(const e of this.queries)await async function(e,n,r=cr()){const i=await Na(e,$n(Ki(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=gi(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.$r.saveNamedQuery(e,n);t=i.withResumeToken(Tt.EMPTY_BYTE_STRING,t);return s.ns=s.ns.insert(t.targetId,t),s.Qr.updateTargetData(e,t).next(()=>s.Qr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Qr.addMatchingKeys(e,r,i.targetId)).next(()=>s.$r.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,ua:this.collectionGroups,ca:e}}}function Ko(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class $o{constructor(e){this.key=e}}class Qo{constructor(e){this.key=e}}class Ho{constructor(e,t){this.query=e,this.la=t,this.ha=null,this.hasCachedResults=!1,this.current=!1,this.Pa=cr(),this.mutatedKeys=cr(),this.Ia=er(e),this.Ta=new Mo(this.Ia)}get Ea(){return this.la}da(e,t){const o=t?t.Aa:new Lo,u=(t||this).Ta;let c=(t||this).mutatedKeys,h=u,l=!1;const d="F"===this.query.limitType&&u.size===this.query.limit?u.last():null,f="L"===this.query.limitType&&u.size===this.query.limit?u.first():null;if(e.inorderTraversal((e,t)=>{const n=u.get(e),r=Xn(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Ra(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Ia(r,d)||f&&this.Ia(r,f)<0)&&(l=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||f)&&(l=!0)),a&&(c=r?(h=h.add(r),s?c.add(e):c.delete(e)):(h=h.delete(e),c.delete(e)))}),null!==this.query.limit)for(;h.size>this.query.limit;){const e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),c=c.delete(e.key),o.track({type:1,doc:e})}return{Ta:h,Aa:o,Xi:l,mutatedKeys:c}}Ra(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){var i=this.Ta;this.Ta=e.Ta,this.mutatedKeys=e.mutatedKeys;const s=e.Aa.Q_();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return U()}};return n(e)-n(t)}(e.type,t.type)||this.Ia(e.doc,t.doc)),this.Va(n),r=null!=r&&r;var a=t&&!r?this.ma():[],o=0===this.Pa.size&&this.current&&!r?1:0,u=o!==this.ha;return this.ha=o,0!==s.length||u?{snapshot:new Oo(this.query,e.Ta,i,s,e.mutatedKeys,0==o,u,!1,!!n&&0<n.resumeToken.approximateByteSize()),fa:a}:{fa:a}}j_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ta:this.Ta,Aa:new Lo,mutatedKeys:this.mutatedKeys,Xi:!1},!1)):{fa:[]}}ga(e){return!this.la.has(e)&&!!this.Ta.has(e)&&!this.Ta.get(e).hasLocalMutations}Va(e){e&&(e.addedDocuments.forEach(e=>this.la=this.la.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.la=this.la.delete(e)),this.current=e.current)}ma(){if(!this.current)return[];const t=this.Pa;this.Pa=cr(),this.Ta.forEach(e=>{this.ga(e.key)&&(this.Pa=this.Pa.add(e.key))});const n=[];return t.forEach(e=>{this.Pa.has(e)||n.push(new Qo(e))}),this.Pa.forEach(e=>{t.has(e)||n.push(new $o(e))}),n}pa(e){this.la=e.hs,this.Pa=cr();var t=this.da(e.documents);return this.applyChanges(t,!0)}ya(){return Oo.fromInitialDocuments(this.query,this.Ta,this.mutatedKeys,0===this.ha,this.hasCachedResults)}}class Wo{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Yo{constructor(e){this.key=e,this.wa=!1}}class Jo{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Sa={},this.ba=new tr(e=>Yn(e),Wn),this.Da=new Map,this.Ca=new Set,this.va=new pt(ue.comparator),this.Fa=new Map,this.Ma=new sa,this.xa={},this.Oa=new Map,this.Na=Os.Ln(),this.onlineState="Unknown",this.La=void 0}get isPrimaryClient(){return!0===this.La}}async function Xo(e,t,n,r){var i=await Na(e.localStore,$n(t)),s=i.targetId,a=n?e.sharedClientState.addLocalQueryTarget(s):"not-current";let o;return r&&(o=await Zo(e,t,s,"current"===a,i.resumeToken)),e.isPrimaryClient&&n&&fo(e.remoteStore,i),o}async function Zo(r,e,t,n,i){r.Ba=(e,t,n)=>async function(e,t,n,r){let i=t.view.da(n);i.Xi&&(i=await Ra(e.localStore,t.query,!1).then(({documents:e})=>t.view.da(e,i)));var s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s,a);return uu(e,t.targetId,a.fa),a.snapshot}(r,e,t,n);const s=await Ra(r.localStore,e,!0),a=new Ho(e,s.hs),o=a.da(s.documents),u=Zr.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),c=a.applyChanges(o,r.isPrimaryClient,u);uu(r,t,c.fa);var h=new Wo(e,t,a);return r.ba.set(e,h),r.Da.has(t)?r.Da.get(t).push(e):r.Da.set(t,[e]),c.snapshot}async function eu(e,t,n){const r=mu(e);try{const e=await function(e,i){const s=e,a=ne.now(),o=i.reduce((e,t)=>e.add(t.key),cr());let u,c;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=nr,r=cr();return s.os.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=mr(r.transform,e||null);null!=i&&(null===n&&(n=Xt.empty()),n.set(r.field,i))}return n||null}(n,u.get(n.key).overlayedDocument);null!=i&&t.push(new Lr(n.key,i,function r(e){const i=[];return gt(e.fields,(e,t)=>{const n=new oe([e]);if(Qt(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new It(i)}(i.value.mapValue),xr.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:sr(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.xa[e.currentUser.toKey()];r=r||new pt(Z),r=r.insert(t,n),e.xa[e.currentUser.toKey()]=r}(r,e.batchId,n),await hu(r,e.changes),await Eo(r.remoteStore)}catch(e){const t=Ro(e,"Failed to persist write");n.reject(t)}}async function tu(e,t){const r=e;try{const e=await Ca(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Fa.get(t);n&&(B(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.wa=!0:0<e.modifiedDocuments.size?B(n.wa):0<e.removedDocuments.size&&(B(n.wa),n.wa=!1))}),await hu(r,e,t)}catch(e){await _e(e)}}function nu(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ba.forEach((e,t)=>{var n=t.view.j_(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.U_)e.j_(n)&&(r=!0)}),r&&Bo(t)}(t.eventManager,i),r.length&&t.Sa.h_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function ru(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.os.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=be.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);B(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=cr();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);su(n,r,null),iu(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await hu(n,e)}catch(e){await _e(e)}}function iu(e,t){(e.Oa.get(t)||[]).forEach(e=>{e.resolve()}),e.Oa.delete(t)}function su(e,t,n){const r=e;let i=r.xa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.xa[r.currentUser.toKey()]=i}}function au(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Da.get(e))t.ba.delete(r),n&&t.Sa.ka(r,n);t.Da.delete(e),t.isPrimaryClient&&t.Ma.Vr(e).forEach(e=>{t.Ma.containsKey(e)||ou(t,e)})}function ou(e,t){e.Ca.delete(t.path.canonicalString());var n=e.va.get(t);null!==n&&(go(e.remoteStore,n),e.va=e.va.remove(t),e.Fa.delete(n),cu(e))}function uu(e,t,n){for(const r of n)r instanceof $o?(e.Ma.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.va.get(n)||e.Ca.has(r)||(O("SyncEngine","New document in limbo: "+n),e.Ca.add(r),cu(e))}(e,r)):r instanceof Qo?(O("SyncEngine","Document no longer in limbo: "+r.key),e.Ma.removeReference(r.key,t),e.Ma.containsKey(r.key)||ou(e,r.key)):U()}function cu(e){for(;0<e.Ca.size&&e.va.size<e.maxConcurrentLimboResolutions;){var t=e.Ca.values().next().value;e.Ca.delete(t);var n=new ue(se.fromString(t)),t=e.Na.next();e.Fa.set(t,new Yo(n)),e.va=e.va.insert(n,t),fo(e.remoteStore,new Fi($n(jn(n.path)),t,"TargetPurposeLimboResolution",Le.oe))}}async function hu(e,t,r){const i=e,s=[],a=[],o=[];i.ba.isEmpty()||(i.ba.forEach((e,n)=>{o.push(i.Ba(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=ba.Ki(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.Sa.h_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>be.forEach(t,t=>be.forEach(t.qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>be.forEach(t.Qi,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!De(e))throw e;O("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ns.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.ns=r.ns.insert(t,i)}}}(i.localStore,a))}async function lu(r,e){const i=r;if(gu(i),mu(i),!0===e&&!0!==i.La){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await du(i,r.toArray());i.La=!0,await Co(i.remoteStore,!0);for(const r of e)fo(i.remoteStore,r)}else if(!1===e&&!1!==i.La){const r=[];let n=Promise.resolve();i.Da.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(au(i,t),ka(i.localStore,t,!0))),go(i.remoteStore,t)}),await n,await du(i,r),function(e){const n=e;n.Fa.forEach((e,t)=>{go(n.remoteStore,t)}),n.Ma.mr(),n.Fa=new Map,n.va=new pt(ue.comparator)}(i),i.La=!1,await Co(i.remoteStore,!1)}}async function du(t,n){const r=t,i=[],s=[];for(const t of n){let e;const h=r.Da.get(t);if(h&&0!==h.length){e=await Na(r.localStore,$n(h[0]));for(const t of h){const n=r.ba.get(t),h=(a=r,o=n,c=u=void 0,c=await Ra((u=a).localStore,o.query,!0),c=o.view.pa(c),u.isPrimaryClient&&uu(u,o.targetId,c.fa),await c);h.snapshot&&s.push(h.snapshot)}}else{const h=await Ma(r.localStore,t);e=await Na(r.localStore,h),await Zo(r,fu(h),t,!1,e.resumeToken)}i.push(e)}var a,o,u,c;return r.Sa.h_(s),i}function fu(e){return qn(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function gu(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=tu.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Fa.get(t);if(r&&r.wa)return cr().add(r.key);{let e=cr();const r=n.Da.get(t);if(!r)return e;for(const t of r){const r=n.ba.get(t);e=e.unionWith(r.view.Ea)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Fa.get(t),s=i&&i.key;if(s){let e=new pt(ue.comparator);e=e.insert(s,Zt.newNoDocument(s,re.min()));const n=cr().add(s),i=new Xr(re.min(),new Map,new pt(Z),e,n);await tu(r,i),r.va=r.va.remove(s),r.Fa.delete(t),cu(r)}else await ka(r.localStore,t,!1).then(()=>au(r,t,n)).catch(_e)}).bind(null,t),t.Sa.h_=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.U_)t.H_(e)&&(r=!0);i.K_=e}}r&&Bo(n)}).bind(null,t.eventManager),t.Sa.ka=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.U_)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function mu(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=ru.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(B(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);su(r,t,n),iu(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await hu(r,e)}catch(n){await _e(n)}}).bind(null,t),t}class pu{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=no(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return Sa(this.persistence,new Ea,e.initialUser,this.serializer)}createPersistence(e){return new la(fa.Hr,this.serializer)}createSharedClientState(e){return new Ka}async terminate(){var e;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(e=this.indexBackfillerScheduler)||void 0===e||e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class yu extends pu{constructor(e,t,n){super(),this.Qa=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Qa.initialize(this,e),await mu(this.Qa.syncEngine),await Eo(this.Qa.remoteStore),await this.persistence.fi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return Sa(this.persistence,new Ea,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new js(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Me(t,this.persistence);return new Re(e.asyncQueue,n)}createPersistence(e){var t=_a(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Ds.withCacheSize(this.cacheSizeBytes):Ds.DEFAULT;return new ya(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,eo(),to(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new Ka}}class vu extends yu{constructor(e,t){super(e,t,!1),this.Qa=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Qa.syncEngine;this.sharedClientState instanceof za&&(this.sharedClientState.syncEngine={Zs:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.vn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):be.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await Eo(i.remoteStore):"acknowledged"===n||"rejected"===n?(su(i,t,r||null),iu(i,t),i.localStore.mutationQueue.Mn(t)):U(),await hu(i,s)):O("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Xs:(async function(e,t,n,r){const i=e;if(i.La)O("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.Da.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await La(i.localStore,Zn(s[0])),r=Xr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,Tt.EMPTY_BYTE_STRING);await hu(i,e,r);break}case"rejected":await ka(i.localStore,t,!0),au(i,t,r);break;default:U()}}}).bind(null,t),eo:(async function(e,t,n){const r=gu(e);if(r.La){for(const e of t)if(r.Da.has(e)&&r.sharedClientState.isActiveQueryTarget(e))O("SyncEngine","Adding an already active target "+e);else{const t=await Ma(r.localStore,e),n=await Na(r.localStore,t);await Zo(r,fu(t),n.targetId,!1,n.resumeToken),fo(r.remoteStore,n)}for(const e of n)r.Da.has(e)&&await ka(r.localStore,e,!1).then(()=>{go(r.remoteStore,e),au(r,e)}).catch(_e)}}).bind(null,t),Bi:(function(e){return e.localStore.persistence.Bi()}).bind(null,t),Ys:(async function(e,t){const n=e;return La(n.localStore,t).then(e=>hu(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.fi(async e=>{await lu(this.Qa.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}createSharedClientState(e){var t=eo();if(!za.D(t))throw new j(q.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=_a(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new za(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class wu{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>nu(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){O("SyncEngine","User change. New user:",t.toKey());const i=await xa(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.Oa.forEach(e=>{e.forEach(e=>{e.reject(new j(q.CANCELLED,r))})}),e.Oa.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await hu(n,i.us)}var r}).bind(null,this.syncEngine),await Co(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Po}createDatastore(e){var t,n,r,i=no(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new Za(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new oo(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>nu(this.syncEngine,e,0),e=new(Qa.D()?Qa:$a),new co(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Jo(e,t,n,r,i,s);return a&&(o.La=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e;await async function(e){const t=e;O("RemoteStore","RemoteStore shutting down."),t.M_.add(5),await lo(t),t.O_.shutdown(),t.N_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate()}}function _u(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class bu{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Ka(this.observer.next,e)}error(e){this.observer.error?this.Ka(this.observer.error,e):F("Uncaught Error in snapshot listener:",e.toString())}$a(){this.muted=!0}Ka(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class Iu{constructor(e,t){this.Ua=e,this.serializer=t,this.metadata=new G,this.buffer=new Uint8Array,this.Wa=new TextDecoder("utf-8"),this.Ga().then(e=>{e&&e.sa()?this.metadata.resolve(e.ia.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ia)}`))},e=>this.metadata.reject(e))}close(){return this.Ua.cancel()}async getMetadata(){return this.metadata.promise}async qa(){return await this.getMetadata(),this.Ga()}async Ga(){var e=await this.za();if(null===e)return null;var t=this.Wa.decode(e),n=Number(t);isNaN(n)&&this.ja(`length string (${t}) is not valid number`);t=await this.Ha(n);return new jo(JSON.parse(t),e.length+n)}Ja(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async za(){for(;this.Ja()<0&&!await this.Ya(););if(0===this.buffer.length)return null;var e=this.Ja();e<0&&this.ja("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Ha(e){for(;this.buffer.length<e;)await this.Ya()&&this.ja("Reached the end of bundle when more is expected.");var t=this.Wa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}ja(e){throw this.Ua.cancel(),new Error(`Invalid bundle format: ${e}`)}async Ya(){var e=await this.Ua.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class Eu{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw this.lastTransactionError=new j(q.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const t=await async function(e,t){const r=e,n={documents:t.map(e=>vi(r.serializer,e))},i=await r.xo("BatchGetDocuments",r.serializer.databaseId,se.emptyPath(),n,t.length),s=new Map;i.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){B(!!t.found),t.found.name,t.found.updateTime;var n=wi(e,t.found.name),r=gi(t.found.updateTime),i=t.found.createTime?gi(t.found.createTime):re.min(),s=new Xt({mapValue:{fields:t.found.fields}});return Zt.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){B(!!t.missing),B(!!t.readTime);var n=wi(e,t.missing),r=gi(t.readTime);return Zt.newNoDocument(n,r)}(n,e):U());var n;s.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=s.get(e.toString());B(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Vr(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=ue.fromPath(t);this.mutations.push(new Ur(n,this.precondition(n)))}),await async function(e,t){const n=e,r={writes:t.map(e=>xi(n.serializer,e))};await n.Co("Commit",n.serializer.databaseId,se.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw U();t=re.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new j(q.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(re.min())?xr.exists(!1):xr.updateTime(t):xr.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return xr.exists(!0);if(t.isEqual(re.min()))throw new j(q.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return xr.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Tu{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Za=n.maxAttempts,this.Yo=new ro(this.asyncQueue,"transaction_retry")}Xa(){--this.Za,this.eu()}eu(){this.Yo.$o(async()=>{const t=new Eu(this.datastore),e=this.tu(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.nu(e)}))}).catch(e=>{this.nu(e)})})}tu(e){try{var t=this.updateFunction(e);return!Oe(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}}nu(e){0<this.Za&&this.ru(e)?(--this.Za,this.asyncQueue.enqueueAndForget(()=>(this.eu(),Promise.resolve()))):this.deferred.reject(e)}ru(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!zr(t)}}class Su{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=k.UNAUTHENTICATED,this.clientId=X.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{O("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(O("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new j(q.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new G;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=Ro(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function xu(e,t){e.asyncQueue.verifyOperationInProgress(),O("FirestoreClient","Initializing OfflineComponentProvider");var n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await xa(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function Du(e,n){e.asyncQueue.verifyOperationInProgress();var t=await Au(e);O("FirestoreClient","Initializing OnlineComponentProvider"),await n.initialize(t,e.configuration),e.setCredentialChangeListener(e=>Do(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>Do(n.remoteStore,t)),e._onlineComponents=n}function Cu(e){return"FirebaseError"===e.name?e.code===q.FAILED_PRECONDITION||e.code===q.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function Au(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){O("FirestoreClient","Using user provided OfflineComponentProvider");try{await xu(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!Cu(n))throw n;P("Error using user provided cache. Falling back to memory cache: "+n),await xu(t,new pu)}}else O("FirestoreClient","Using default OfflineComponentProvider"),await xu(t,new pu);return t._offlineComponents}async function Nu(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(O("FirestoreClient","Using user provided OnlineComponentProvider"),await Du(e,e._uninitializedComponentsProvider._online)):(O("FirestoreClient","Using default OnlineComponentProvider"),await Du(e,new wu))),e._onlineComponents}function ku(e){return Au(e).then(e=>e.persistence)}function Ru(e){return Au(e).then(e=>e.localStore)}function Mu(e){return Nu(e).then(e=>e.remoteStore)}function Lu(e){return Nu(e).then(e=>e.syncEngine)}async function Ou(e){const t=await Nu(e),n=t.eventManager;return n.onListen=(async function(e,t,n=!0){const r=gu(e);let i;const s=r.ba.get(t);return i=s?(r.sharedClientState.addLocalQueryTarget(s.targetId),s.view.ya()):await Xo(r,t,n,!0),i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t,n){const r=e,i=r.ba.get(t),s=r.Da.get(i.targetId);if(1<s.length)return r.Da.set(i.targetId,s.filter(e=>!Wn(e,t))),void r.ba.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(i.targetId),r.sharedClientState.isActiveQueryTarget(i.targetId)||await ka(r.localStore,i.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(i.targetId),n&&go(r.remoteStore,i.targetId),au(r,i.targetId)}).catch(_e)):(au(r,i.targetId),await ka(r.localStore,i.targetId,!0))}).bind(null,t.syncEngine),n.onFirstRemoteStoreListen=(async function(e,t){await Xo(gu(e),t,!0,!1)}).bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=(async function(e,t){const n=e,r=n.ba.get(t),i=n.Da.get(r.targetId);n.isPrimaryClient&&1===i.length&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),go(n.remoteStore,r.targetId))}).bind(null,t.syncEngine),n}function Fu(e,t,n={}){const r=new G;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new bu({next:e=>{r.enqueueAndForget(()=>Uo(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new j(q.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new j(q.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new qo(jn(i.path),e,{includeMetadataChanges:!0,ra:!0});return Vo(n,o)}(await Ou(e),e.asyncQueue,t,n,r)),r.promise}function Pu(e,t,n={}){const r=new G;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new bu({next:e=>{n.enqueueAndForget(()=>Uo(t,a)),e.fromCache&&"server"===r.source?i.reject(new j(q.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new qo(e,s,{includeMetadataChanges:!0,ra:!0});return Vo(t,a)}(await Ou(e),e.asyncQueue,t,n,r)),r.promise}function Vu(e,t,n,r){const i=(n=n,t=no(t),s="string"==typeof n?$r().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return _u(e,t);if(e instanceof ArrayBuffer)return _u(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new Iu(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=gi(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.$r.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(Ko(i));const a=new zo(i,t.localStore,n.serializer);let e=await n.qa();for(;e;){const t=await a._a(e);t&&r._updateProgress(t),e=await n.qa()}var s=await a.complete();return await hu(t,s.ca,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.$r.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.ua)}catch(t){return P("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await Lu(e),i,r)})}function Uu(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Bu=new Map;function qu(e,t,n){if(!n)throw new j(q.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function ju(e,t,n,r){if(!0===t&&!0===r)throw new j(q.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Gu(e){if(!ue.isDocumentKey(e))throw new j(q.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function zu(e){if(ue.isDocumentKey(e))throw new j(q.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ku(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":U();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function $u(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new j(q.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Ku(e);throw new j(q.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Qu(e,t){if(t<=0)throw new j(q.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Hu{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new j(q.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new j(q.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}ju("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Uu(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new j(q.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new j(q.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new j(q.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class Wu{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Hu({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new j(q.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new j(q.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 Hu(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new K;switch(e.type){case"firstParty":return new W(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new j(q.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Bu.get(e);t&&(O("ComponentProvider","Removing Datastore"),Bu.delete(e),t.terminate())}(this),Promise.resolve()}}function Yu(n,e,t,r={}){var i;const s=(n=$u(n,Wu))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&P("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=k.MOCK_USER;else{e=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e),[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(i)),""].join(".")}(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new j(q.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new k(s)}n._authCredentials=new $(new z(e,t))}}class Ju{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Ju(this.firestore,e,this._query)}}class Xu{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Zu(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Xu(this.firestore,e,this._key)}}class Zu extends Ju{constructor(e,t,n){super(e,t,jn(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Xu(this.firestore,null,new ue(e))}withConverter(e){return new Zu(this.firestore,e,this._path)}}function ec(e,t,...n){if(e=y(e),qu("collection","path",t),e instanceof Wu){var r=se.fromString(t,...n);return zu(r),new Zu(e,null,r)}if(!(e instanceof Xu||e instanceof Zu))throw new j(q.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(se.fromString(t,...n));return zu(r),new Zu(e.firestore,null,r)}function tc(e,t,...n){if(e=y(e),qu("doc","path",t=1===arguments.length?X.newId():t),e instanceof Wu){var r=se.fromString(t,...n);return Gu(r),new Xu(e,null,new ue(r))}if(!(e instanceof Xu||e instanceof Zu))throw new j(q.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(se.fromString(t,...n));return Gu(r),new Xu(e.firestore,e instanceof Zu?e.converter:null,new ue(r))}function nc(e,t){return e=y(e),t=y(t),(e instanceof Xu||e instanceof Zu)&&(t instanceof Xu||t instanceof Zu)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function rc(e,t){return e=y(e),t=y(t),e instanceof Ju&&t instanceof Ju&&e.firestore===t.firestore&&Wn(e._query,t._query)&&e.converter===t.converter}class ic{constructor(){this.iu=Promise.resolve(),this.su=[],this.ou=!1,this._u=[],this.au=null,this.uu=!1,this.cu=!1,this.lu=[],this.Yo=new ro(this,"async_queue_retry"),this.hu=()=>{var e=to();e&&O("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Yo.Wo()};const e=to();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.hu)}get isShuttingDown(){return this.ou}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Pu(),this.Iu(e)}enterRestrictedMode(e){if(!this.ou){this.ou=!0,this.cu=e||!1;const t=to();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.hu)}}enqueue(e){if(this.Pu(),this.ou)return new Promise(()=>{});const t=new G;return this.Iu(()=>this.ou&&this.cu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.su.push(e),this.Tu()))}async Tu(){if(0!==this.su.length){try{await this.su[0](),this.su.shift(),this.Yo.reset()}catch(e){if(!De(e))throw e;O("AsyncQueue","Operation failed with retryable error: "+e)}0<this.su.length&&this.Yo.$o(()=>this.Tu())}}Iu(e){var t=this.iu.then(()=>(this.uu=!0,e().catch(e=>{throw this.au=e,this.uu=!1,F("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.uu=!1,e))));return this.iu=t}enqueueAfterDelay(e,t,n){this.Pu(),-1<this.lu.indexOf(e)&&(t=0);var r=ko.createAndSchedule(this,e,t,n,e=>this.Eu(e));return this._u.push(r),r}Pu(){this.au&&U()}verifyOperationInProgress(){}async du(){for(var e;await(e=this.iu),e!==this.iu;);}Au(e){for(const t of this._u)if(t.timerId===e)return!0;return!1}Ru(t){return this.du().then(()=>{this._u.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this._u)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.du()})}Vu(e){this.lu.push(e)}Eu(e){var t=this._u.indexOf(e);this._u.splice(t,1)}}function sc(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class ac{constructor(){this._progressObserver={},this._taskCompletionResolver=new G,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var oc,uc,cc,hc,lc;class dc extends Wu{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ic,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||gc(this),this._firestoreClient.terminate()}}function fc(e){return e._firestoreClient||gc(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function gc(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new Rt(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Uu(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new Su(e._authCredentials,e._appCheckCredentials,e._queue,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function mc(e,t,n){const r=new G;return e.asyncQueue.enqueue(async()=>{try{await xu(e,n),await Du(e,t),r.resolve()}catch(e){const t=e;if(!Cu(t))throw t;P("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function pc(e){return function(e){const t=new G;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;wo(n.remoteStore)||O("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Oa.get(e)||[];r.push(t),n.Oa.set(e,r)}catch(e){const n=Ro(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await Lu(e),t)),t.promise}(fc(e=$u(e,dc)))}function yc(e){return(n=fc(e=$u(e,dc))).asyncQueue.enqueue(async()=>{const e=await ku(n),t=await Mu(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.M_.delete(0),ho(t)}(t)});var n}function vc(e){return(n=fc(e=$u(e,dc))).asyncQueue.enqueue(async()=>{const e=await ku(n),t=await Mu(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.M_.add(0),await lo(t),t.N_.set("Offline")}(t)});var n}function wc(t,e){return n=fc(t=$u(t,dc)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.$r.getNamedQuery(e,t))}(await Ru(n),r)).then(e=>e?new Ju(t,null,e.query):null);var n,r}function _c(e){if(e._initialized||e._terminated)throw new j(q.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class bc{constructor(e){this._byteString=e}static fromBase64String(e){try{return new bc(Tt.fromBase64String(e))}catch(e){throw new j(q.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new bc(Tt.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class Ic{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new j(q.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new oe(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class Ec{constructor(e){this._methodName=e}}class Tc{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new j(q.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new j(q.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Z(this._lat,e._lat)||Z(this._long,e._long)}}const Sc=/^__.*__$/;class xc{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Lr(e,this.data,this.fieldMask,t,this.fieldTransforms):new Mr(e,this.data,t,this.fieldTransforms)}}class Dc{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Lr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Cc(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw U()}}class Ac{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.mu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get fu(){return this.settings.fu}gu(e){return new Ac(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}pu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.gu({path:n,yu:!1});return r.wu(e),r}Su(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.gu({path:n,yu:!1});return r.mu(),r}bu(e){return this.gu({path:void 0,yu:!0})}Du(e){return Wc(e,this.settings.methodName,this.settings.Cu||!1,this.path,this.settings.vu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}mu(){if(this.path)for(let e=0;e<this.path.length;e++)this.wu(this.path.get(e))}wu(e){if(0===e.length)throw this.Du("Document fields must not be empty");if(Cc(this.fu)&&Sc.test(e))throw this.Du('Document fields cannot begin and end with "__"')}}class Nc{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||no(e)}Fu(e,t,n,r=!1){return new Ac({fu:e,methodName:t,vu:n,path:oe.emptyPath(),yu:!1,Cu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function kc(e){var t=e._freezeSettings(),n=no(e._databaseId);return new Nc(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Rc(e,t,n,r,i,s={}){const a=e.Fu(s.merge||s.mergeFields?2:0,t,n,i);Kc("Data must be an object, but it was:",a,r);var o=Gc(r,a);let u,c;if(s.merge)u=new It(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=$c(t,r,n);if(!a.contains(i))throw new j(q.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Yc(e,i)||e.push(i)}u=new It(e),c=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=a.fieldTransforms;return new xc(new Xt(o),u,c)}class Mc extends Ec{_toFieldTransform(e){if(2!==e.fu)throw 1===e.fu?e.Du(`${this._methodName}() can only appear at the top level of your update data`):e.Du(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Mc}}function Lc(e,t,n){return new Ac({fu:3,vu:t.settings.vu,methodName:e._methodName,yu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class Oc extends Ec{_toFieldTransform(e){return new Tr(e.path,new pr)}isEqual(e){return e instanceof Oc}}class Fc extends Ec{constructor(e,t){super(e),this.Mu=t}_toFieldTransform(e){const t=Lc(this,e,!0),n=this.Mu.map(e=>jc(e,t)),r=new yr(n);return new Tr(e.path,r)}isEqual(e){return e instanceof Fc&&m(this.Mu,e.Mu)}}class Pc extends Ec{constructor(e,t){super(e),this.Mu=t}_toFieldTransform(e){const t=Lc(this,e,!0),n=this.Mu.map(e=>jc(e,t)),r=new wr(n);return new Tr(e.path,r)}isEqual(e){return e instanceof Pc&&m(this.Mu,e.Mu)}}class Vc extends Ec{constructor(e,t){super(e),this.xu=t}_toFieldTransform(e){var t=new br(e.serializer,fr(e.serializer,this.xu));return new Tr(e.path,t)}isEqual(e){return e instanceof Vc&&this.xu===e.xu}}function Uc(e,i,s,t){const a=e.Fu(1,i,s);Kc("Data must be an object, but it was:",a,t);const o=[],u=Xt.empty();gt(t,(e,t)=>{var n=Hc(i,e,s);t=y(t);var r=a.Su(n);if(t instanceof Mc)o.push(n);else{const e=jc(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new It(o);return new Dc(u,n,a.fieldTransforms)}function Bc(e,t,n,r,i,s){const a=e.Fu(1,t,n),o=[$c(t,r,n)],u=[i];if(s.length%2!=0)throw new j(q.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)o.push($c(t,s[f])),u.push(s[f+1]);const c=[],h=Xt.empty();for(let g=o.length-1;0<=g;--g)if(!Yc(c,o[g])){const t=o[g];var l=y(l=u[g]);const r=a.Su(t);if(l instanceof Mc)c.push(t);else{const e=jc(l,r);null!=e&&(c.push(t),h.set(t,e))}}var d=new It(c);return new Dc(h,d,a.fieldTransforms)}function qc(e,t,n,r=!1){return jc(n,e.Fu(r?4:3,t))}function jc(e,t){if(zc(e=y(e)))return Kc("Unsupported field value:",t,e),Gc(e,t);if(e instanceof Ec)return function(e,t){if(!Cc(t.fu))throw t.Du(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Du(`${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.yu&&4!==t.fu)throw t.Du("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=jc(i,t.bu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=y(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return fr(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=ne.fromDate(e);return{timestampValue:di(t.serializer,n)}}if(e instanceof ne){n=new ne(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:di(t.serializer,n)}}if(e instanceof Tc)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof bc)return{bytesValue:fi(t.serializer,e._byteString)};if(e instanceof Xu){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.Du(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:mi(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Du(`Unsupported field value: ${Ku(e)}`)}(e,t)}function Gc(e,r){const i={};return mt(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):gt(e,(e,t)=>{var n=jc(t,r.pu(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function zc(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ne||e instanceof Tc||e instanceof bc||e instanceof Xu||e instanceof Ec)}function Kc(e,t,n){if(!zc(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=Ku(n);throw"an object"===r?t.Du(e+" a custom object"):t.Du(e+" "+r)}var i}function $c(e,t,n){if((t=y(t))instanceof Ic)return t._internalPath;if("string"==typeof t)return Hc(e,t);throw Wc("Field path arguments must be of type string or ",e,!1,void 0,n)}const Qc=new RegExp("[~\\*/\\[\\]]");function Hc(t,n,r){if(0<=n.search(Qc))throw Wc(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new Ic(...n.split("."))._internalPath}catch(e){throw Wc(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Wc(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(s||a)&&(u+=" (found",s&&(u+=` in field ${r}`),a&&(u+=` in document ${i}`),u+=")"),new j(q.INVALID_ARGUMENT,o+e+u)}function Yc(e,t){return e.some(e=>e.isEqual(t))}class Jc{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Xu(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Xc(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(Zc("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Xc extends Jc{data(){return super.data()}}function Zc(e,t){return"string"==typeof t?Hc(e,t):(t instanceof Ic?t:t._delegate)._internalPath}function eh(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new j(q.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class th{}class nh extends th{}function rh(e,t,...n){let r=[];t instanceof th&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof sh).length,n=e.filter(e=>e instanceof ih).length;if(1<t||0<t&&0<n)throw new j(q.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class ih extends nh{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new ih(e,t,n)}_apply(e){var t=this._parse(e);return fh(e._query,t),new Ju(e.firestore,e.converter,Qn(e._query,t))}_parse(e){var t=kc(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new j(q.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){dh(a,s);const t=[];for(const n of a)t.push(lh(r,e,n));o={arrayValue:{values:t}}}else o=lh(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||dh(a,s),o=qc(n,t,a,"in"===s||"not-in"===s);return an.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class sh extends th{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new sh(e,t)}_parse(t){var e=this._queryConstraints.map(e=>e._parse(t)).filter(e=>0<e.getFilters().length);return 1===e.length?e[0]:on.create(e,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(const e of t.getFlattenedFilters())fh(n,e),n=Qn(n,e)}(e._query,t),new Ju(e.firestore,e.converter,Qn(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class ah extends nh{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new ah(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new j(q.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new j(q.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new rn(t,n)}(e._query,this._field,this._direction);return new Ju(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Bn(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class oh extends nh{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new oh(e,t,n)}_apply(e){return new Ju(e.firestore,e.converter,Hn(e._query,this._limit,this._limitType))}}class uh extends nh{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uh(e,t,n)}_apply(e){var t,n=hh(e,this.type,this._docOrFields,this._inclusive);return new Ju(e.firestore,e.converter,(t=e._query,e=n,new Bn(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class ch extends nh{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new ch(e,t,n)}_apply(e){var t,n=hh(e,this.type,this._docOrFields,this._inclusive);return new Ju(e.firestore,e.converter,(t=e._query,e=n,new Bn(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function hh(e,t,n,r){if(n[0]=y(n[0]),n[0]instanceof Jc)return function(e,t,n,r,i){if(!r)throw new j(q.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Kn(e))if(n.field.isKeyField())s.push(jt(t,r.key));else{const e=r.data.field(n.field);if(At(e))throw new j(q.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new j(q.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new en(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=kc(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new j(q.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u<i.length;u++){const c=i[u];if(a[u].field.isKeyField()){if("string"!=typeof c)throw new j(q.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!zn(e)&&-1!==c.indexOf("/"))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(se.fromString(c));if(!ue.isDocumentKey(n))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new ue(n);o.push(jt(t,i))}else{const e=qc(n,r,c);o.push(e)}}return new en(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function lh(e,t,n){if("string"==typeof(n=y(n))){if(""===n)throw new j(q.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!zn(t)&&-1!==n.indexOf("/"))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(se.fromString(n));if(!ue.isDocumentKey(r))throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return jt(e,new ue(r))}if(n instanceof Xu)return jt(e,n._key);throw new j(q.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ku(n)}.`)}function dh(e,t){if(!Array.isArray(e)||0===e.length)throw new j(q.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function fh(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(e){switch(e){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[]}}(t.op));if(null!==n)throw n===t.op?new j(q.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new j(q.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class gh{convertValue(e,t="none"){switch(Ft(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Dt(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(Ct(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 U()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return gt(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new Tc(Dt(e.latitude),Dt(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=Nt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(kt(e));default:return null}}convertTimestamp(e){var t=xt(e);return new ne(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=se.fromString(e);B(Oi(n));const r=new Mt(n.get(1),n.get(3)),i=new ue(n.popFirst(5));return r.isEqual(t)||F(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function mh(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class ph extends gh{constructor(e){super(),this.firestore=e}convertBytes(e){return new bc(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Xu(this.firestore,null,t)}}class yh{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class vh extends Jc{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new wh(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(Zc("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class wh extends vh{data(e={}){return super.data(e)}}class _h{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new yh(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new wh(this._firestore,this._userDataWriter,e.key,e,new yh(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new j(q.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new wh(s._firestore,s._userDataWriter,e.doc.key,e.doc,new yh(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new wh(s._firestore,s._userDataWriter,e.doc.key,e.doc,new yh(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return U()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function bh(e,t){return e instanceof vh&&t instanceof vh?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 _h&&t instanceof _h&&e._firestore===t._firestore&&rc(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class Ih extends gh{constructor(e){super(),this.firestore=e}convertBytes(e){return new bc(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Xu(this.firestore,null,t)}}function Eh(t){t=$u(t,Xu);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return function(e,t){const n=new G;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new j(q.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=Ro(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await Ru(e),t,n)),n.promise}(e,t._key).then(e=>new vh(n,r,t._key,e,new yh(null!==e&&e.hasLocalMutations,!0),t.converter))}function Th(t){t=$u(t,Ju);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return function(e,t){const n=new G;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await Ra(e,t,!0),s=new Ho(t,i.hs),a=s.da(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=Ro(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await Ru(e),t,n)),n.promise}(e,t._query).then(e=>new _h(n,r,t,e))}function Sh(e,t,n){e=$u(e,Xu);var r=$u(e.firestore,dc),i=mh(e.converter,t,n);return Ah(r,[Rc(kc(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,xr.none())])}function xh(e,t,n,...r){e=$u(e,Xu);var i=$u(e.firestore,dc),s=kc(i);let a;return a="string"==typeof(t=y(t))||t instanceof Ic?Bc(s,"updateDoc",e._key,t,n,r):Uc(s,"updateDoc",e._key,t),Ah(i,[a.toMutation(e._key,xr.exists(!0))])}function Dh(t,...n){var e;t=y(t);let r={includeMetadataChanges:!1,source:"default"},i=0;"object"!=typeof n[i]||sc(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges,source:r.source};if(sc(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Xu)o=$u(t.firestore,dc),u=jn(t._key.path),a={next:e=>{n[i]&&n[i](Nh(o,t,e))},error:n[i+1],complete:n[i+2]};else{const c=$u(t,Ju);o=$u(c.firestore,dc),u=c._query;const h=new Ih(o);a={next:e=>{n[i]&&n[i](new _h(o,h,c,e))},error:n[i+1],complete:n[i+2]},eh(t._query)}return function(e,t,n,r){const i=new bu(r),s=new qo(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Vo(await Ou(e),s)),()=>{i.$a(),e.asyncQueue.enqueueAndForget(async()=>Uo(await Ou(e),s))}}(fc(o),u,s,a)}function Ch(e,t){return function(e,t){const n=new bu(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.z_.add(t),t.next()}(await Ou(e),n)),()=>{n.$a(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.z_.delete(t)}(await Ou(e),n))}}(fc(e=$u(e,dc)),sc(t)?t:{next:t})}function Ah(e,t){return function(e,t){const n=new G;return e.asyncQueue.enqueueAndForget(async()=>eu(await Lu(e),t,n)),n.promise}(fc(e),t)}function Nh(e,t,n){var r=n.docs.get(t._key),i=new Ih(e);return new vh(e,i,t._key,r,new yh(n.hasPendingWrites,n.fromCache),t.converter)}const kh={maxAttempts:5};class Rh{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=kc(e)}set(e,t,n){this._verifyNotCommitted();const r=Mh(e,this._firestore),i=mh(r.converter,t,n),s=Rc(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,xr.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=Mh(e,this._firestore);let s;return s="string"==typeof(t=y(t))||t instanceof Ic?Bc(this._dataReader,"WriteBatch.update",i._key,t,n,r):Uc(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,xr.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=Mh(e,this._firestore);return this._mutations=this._mutations.concat(new Vr(t._key,xr.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new j(q.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function Mh(e,t){if((e=y(e)).firestore!==t)throw new j(q.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class Lh extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=kc(e)}get(e){const n=Mh(e,this._firestore),r=new ph(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return U();const t=e[0];if(t.isFoundDocument())return new Jc(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Jc(this._firestore,r,n._key,null,n.converter);throw U()})}set(e,t,n){var r=Mh(e,this._firestore),i=mh(r.converter,t,n),i=Rc(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=Mh(e,this._firestore),s="string"==typeof(t=y(t))||t instanceof Ic?Bc(this._dataReader,"Transaction.update",i._key,t,n,r):Uc(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=Mh(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=Mh(e,this._firestore),n=new Ih(this._firestore);return super.get(e).then(e=>new vh(this._firestore,n,t._key,e._document,new yh(!1,!1),t.converter))}}function Oh(t,n,e){t=$u(t,dc);var r=Object.assign(Object.assign({},kh),e);return function(e){if(e.maxAttempts<1)throw new j(q.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new G;return t.asyncQueue.enqueueAndForget(async()=>{var e=await Nu(t).then(e=>e.datastore);new Tu(t.asyncQueue,e,r,n,i).Xa()}),i.promise}(fc(t),e=>n(new Lh(t,e)),r)}uc=!0,cc=ul.SDK_VERSION,R=cc,ul._registerComponent(new v("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new dc(new Q(e.getProvider("auth-internal")),new J(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new j(q.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Mt(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:uc},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),ul.registerVersion(A,N,oc),ul.registerVersion(A,N,"esm2017");function Fh(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new j("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Ph(){if("undefined"==typeof Uint8Array)throw new j("unimplemented","Uint8Arrays are not available in this environment.")}function Vh(){if("undefined"==typeof atob)throw new j("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Uh{constructor(e){this._delegate=e}static fromBase64String(e){return Vh(),new Uh(bc.fromBase64String(e))}static fromUint8Array(e){return Ph(),new Uh(bc.fromUint8Array(e))}toBase64(){return Vh(),this._delegate.toBase64()}toUint8Array(){return Ph(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Bh(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class qh{enableIndexedDbPersistence(e,t){return function(e,t){_c(e=$u(e,dc));var n=fc(e);if(n._uninitializedComponentsProvider)throw new j(q.FAILED_PRECONDITION,"SDK cache is already specified.");P("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new wu;return mc(n,i,new yu(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){_c(e=$u(e,dc));var t=fc(e);if(t._uninitializedComponentsProvider)throw new j(q.FAILED_PRECONDITION,"SDK cache is already specified.");P("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new wu;return mc(t,r,new vu(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new j(q.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new G;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Ee.D())return Promise.resolve();var t=e+"main";await Ee.delete(t)}(_a(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class jh{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Mt||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||P("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){Yu(this._delegate,e,t,n)}enableNetwork(){return yc(this._delegate)}disableNetwork(){return vc(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,ju("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return pc(this._delegate)}onSnapshotsInSync(e){return Ch(this._delegate,e)}get app(){if(!this._appCompat)throw new j("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new nl(this,ec(this._delegate,e))}catch(e){throw Hh(e,"collection()","Firestore.collection()")}}doc(e){try{return new Qh(this,tc(this._delegate,e))}catch(e){throw Hh(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Zh(this,function(e,t){if(e=$u(e,Wu),qu("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new j(q.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ju(e,null,(t=t,new Bn(se.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Hh(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Oh(this._delegate,e=>t(new zh(this,e)))}batch(){return fc(this._delegate),new Kh(new Rh(this._delegate,e=>Ah(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=fc(t=$u(t,dc)),r=new ac,Vu(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return wc(this._delegate,e).then(e=>e?new Zh(this,e):null)}}class Gh extends gh{constructor(e){super(),this.firestore=e}convertBytes(e){return new Uh(new bc(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Qh.forKey(t,this.firestore,null)}}class zh{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Gh(e)}get(e){const t=rl(e);return this._delegate.get(t).then(e=>new Jh(this._firestore,new vh(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=rl(e);return n?(Fh("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=rl(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=rl(e);return this._delegate.delete(t),this}}class Kh{constructor(e){this._delegate=e}set(e,t,n){var r=rl(e);return n?(Fh("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=rl(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=rl(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class $h{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new wh(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Xh(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=$h.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new $h(e,new Gh(e),t),r.set(t,i)),i}}$h.INSTANCES=new WeakMap;class Qh{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Gh(e)}static forPath(e,t,n){if(e.length%2!=0)throw new j("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Qh(t,new Xu(t._delegate,n,new ue(e)))}static forKey(e,t,n){return new Qh(t,new Xu(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new nl(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new nl(this.firestore,ec(this._delegate,e))}catch(e){throw Hh(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=y(e))instanceof Xu&&nc(this._delegate,e)}set(e,t){t=Fh("DocumentReference.set",t);try{return t?Sh(this._delegate,e,t):Sh(this._delegate,e)}catch(e){throw Hh(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?xh(this._delegate,e):xh(this._delegate,e,t,...n)}catch(e){throw Hh(e,"updateDoc()","DocumentReference.update()")}}delete(){return Ah($u((e=this._delegate).firestore,dc),[new Vr(e._key,xr.none())]);var e}onSnapshot(...e){var t=Wh(e),n=Yh(e,e=>new Jh(this.firestore,new vh(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return Dh(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?Eh:"server"===(null==e?void 0:e.source)?function(t){t=$u(t,Xu);const n=$u(t.firestore,dc);return Fu(fc(n),t._key,{source:"server"}).then(e=>Nh(n,t,e))}:function(t){t=$u(t,Xu);const n=$u(t.firestore,dc);return Fu(fc(n),t._key).then(e=>Nh(n,t,e))})(this._delegate),t.then(e=>new Jh(this.firestore,new vh(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Qh(this.firestore,e?this._delegate.withConverter($h.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Hh(e,t,n){return e.message=e.message.replace(t,n),e}function Wh(e){for(const t of e)if("object"==typeof t&&!Bh(t))return t;return{}}function Yh(e,t){var n;let r;return r=Bh(e[0])?e[0]:Bh(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class Jh{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Qh(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 bh(this._delegate,e._delegate)}}class Xh extends Jh{data(e){var t=this._delegate.data(e);return this._delegate._converter||void 0!==t||U(),t}}class Zh{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Gh(e)}where(e,t,n){try{return new Zh(this.firestore,rh(this._delegate,(r=n,i=t,s=Zc("where",e),ih._create(s,i,r))))}catch(e){throw Hh(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new Zh(this.firestore,rh(this._delegate,([n,r="asc"]=[e,t],i=r,s=Zc("orderBy",n),ah._create(s,i))))}catch(e){throw Hh(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new Zh(this.firestore,rh(this._delegate,(Qu("limit",t=e),oh._create("limit",t,"F"))))}catch(e){throw Hh(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Zh(this.firestore,rh(this._delegate,(Qu("limitToLast",t=e),oh._create("limitToLast",t,"L"))))}catch(e){throw Hh(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return uh._create("startAt",e,!0)}(...e)))}catch(e){throw Hh(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return uh._create("startAfter",e,!1)}(...e)))}catch(e){throw Hh(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return ch._create("endBefore",e,!1)}(...e)))}catch(e){throw Hh(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Zh(this.firestore,rh(this._delegate,function(...e){return ch._create("endAt",e,!0)}(...e)))}catch(e){throw Hh(e,"endAt()","Query.endAt()")}}isEqual(e){return rc(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?Th:"server"===(null==e?void 0:e.source)?function(t){t=$u(t,Ju);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return Pu(e,t._query,{source:"server"}).then(e=>new _h(n,r,t,e))}:function(t){t=$u(t,Ju);const n=$u(t.firestore,dc),e=fc(n),r=new Ih(n);return eh(t._query),Pu(e,t._query).then(e=>new _h(n,r,t,e))})(this._delegate),t.then(e=>new tl(this.firestore,new _h(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Wh(e),n=Yh(e,e=>new tl(this.firestore,new _h(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return Dh(this._delegate,t,n)}withConverter(e){return new Zh(this.firestore,e?this._delegate.withConverter($h.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class el{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Xh(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class tl{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Zh(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 Xh(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new el(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Xh(this._firestore,e))})}isEqual(e){return bh(this._delegate,e._delegate)}}class nl extends Zh{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new Qh(this.firestore,e):null}doc(e){try{return void 0===e?new Qh(this.firestore,tc(this._delegate)):new Qh(this.firestore,tc(this._delegate,e))}catch(e){throw Hh(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=$u(e.firestore,dc),r=tc(e),i=mh(e.converter,t);return Ah(n,[Rc(kc(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,xr.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Qh(this.firestore,e))}isEqual(e){return nc(this._delegate,e._delegate)}withConverter(e){return new nl(this.firestore,e?this._delegate.withConverter($h.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function rl(e){return $u(e,Xu)}const il={Firestore:jh,GeoPoint:Tc,Timestamp:ne,Blob:Uh,Transaction:zh,WriteBatch:Kh,DocumentReference:Qh,DocumentSnapshot:Jh,Query:Zh,QueryDocumentSnapshot:Xh,QuerySnapshot:tl,CollectionReference:nl,FieldPath:class sl{constructor(...e){this._delegate=new Ic(...e)}static documentId(){return new sl(oe.keyField().canonicalString())}isEqual(e){return(e=y(e))instanceof Ic&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class al{constructor(e){this._delegate=e}static serverTimestamp(){const e=new Oc("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new al(e)}static delete(){const e=new Mc("deleteField");return e._methodName="FieldValue.delete",new al(e)}static arrayUnion(...e){const t=function(...e){return new Fc("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new al(t)}static arrayRemove(...e){const t=function(...e){return new Pc("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new al(t)}static increment(e){const t=new Vc("increment",e);return t._methodName="FieldValue.increment",new al(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,M.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};hc=t.default,lc=(e,t)=>new jh(e,t,new qh),hc.INTERNAL.registerComponent(new v("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return lc(t,n)},"PUBLIC").setServiceProps(Object.assign({},il))),hc.registerVersion("@firebase/firestore-compat","0.3.30-dataconnect-preview.42eb5e521")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-firestore-compat.js - be sure to load firebase-app.js first.")}});
|
|
2
2
|
//# sourceMappingURL=firebase-firestore-compat.js.map
|