Kargi-Sitesi/node_modules/firebase/firebase-firestore.js

3 lines
430 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import{_registerComponent as e,registerVersion as i,_getProvider,getApp as s,_removeServiceInstance as o,SDK_VERSION as _}from"https://www.gstatic.com/firebasejs/11.0.1/firebase-app.js";const stringToByteArray$1=function(e){const i=[];let s=0;for(let o=0;o<e.length;o++){let _=e.charCodeAt(o);_<128?i[s++]=_:_<2048?(i[s++]=_>>6|192,i[s++]=63&_|128):55296==(64512&_)&&o+1<e.length&&56320==(64512&e.charCodeAt(o+1))?(_=65536+((1023&_)<<10)+(1023&e.charCodeAt(++o)),i[s++]=_>>18|240,i[s++]=_>>12&63|128,i[s++]=_>>6&63|128,i[s++]=63&_|128):(i[s++]=_>>12|224,i[s++]=_>>6&63|128,i[s++]=63&_|128)}return i},h={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,i){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const s=i?this.byteToCharMapWebSafe_:this.byteToCharMap_,o=[];for(let i=0;i<e.length;i+=3){const _=e[i],h=i+1<e.length,d=h?e[i+1]:0,f=i+2<e.length,g=f?e[i+2]:0,b=_>>2,w=(3&_)<<4|d>>4;let O=(15&d)<<2|g>>6,q=63&g;f||(q=64,h||(O=64)),o.push(s[b],s[w],s[O],s[q])}return o.join("")},encodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?btoa(e):this.encodeByteArray(stringToByteArray$1(e),i)},decodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?atob(e):function(e){const i=[];let s=0,o=0;for(;s<e.length;){const _=e[s++];if(_<128)i[o++]=String.fromCharCode(_);else if(_>191&&_<224){const h=e[s++];i[o++]=String.fromCharCode((31&_)<<6|63&h)}else if(_>239&&_<365){const h=((7&_)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;i[o++]=String.fromCharCode(55296+(h>>10)),i[o++]=String.fromCharCode(56320+(1023&h))}else{const h=e[s++],d=e[s++];i[o++]=String.fromCharCode((15&_)<<12|(63&h)<<6|63&d)}}return i.join("")}(this.decodeStringToByteArray(e,i))},decodeStringToByteArray(e,i){this.init_();const s=i?this.charToByteMapWebSafe_:this.charToByteMap_,o=[];for(let i=0;i<e.length;){const _=s[e.charAt(i++)],h=i<e.length?s[e.charAt(i)]:0;++i;const d=i<e.length?s[e.charAt(i)]:64;++i;const f=i<e.length?s[e.charAt(i)]:64;if(++i,null==_||null==h||null==d||null==f)throw new DecodeBase64StringError;const g=_<<2|h>>4;if(o.push(g),64!==d){const e=h<<4&240|d>>2;if(o.push(e),64!==f){const e=d<<6&192|f;o.push(e)}}}return o},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 DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const i=stringToByteArray$1(e);return h.encodeByteArray(i,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){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__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const i=e&&function(e){try{return h.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return i&&JSON.parse(i)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const i=(e=>{var i,s;return null===(s=null===(i=getDefaults())||void 0===i?void 0:i.emulatorHosts)||void 0===s?void 0:s[e]})(e);if(!i)return;const s=i.lastIndexOf(":");if(s<=0||s+1===i.length)throw new Error(`Invalid host ${i} with no separate hostname and port!`);const o=parseInt(i.substring(s+1),10);return"["===i[0]?[i.substring(1,s-1),o]:[i.substring(0,s),o]};function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function isSafari(){return!function isNode(){var e;const i=null===(e=getDefaults())||void 0===e?void 0:e.forceEnvironment;if("node"===i)return!0;if("browser"===i)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class FirebaseError extends Error{constructor(e,i,s){super(i),this.code=e,this.customData=s,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,i,s){this.service=e,this.serviceName=i,this.errors=s}create(e,...i){const s=i[0]||{},o=`${this.service}/${e}`,_=this.errors[e],h=_?function replaceTemplate(e,i){return e.replace(d,((e,s)=>{const o=i[s];return null!=o?String(o):`<${s}?>`}))}(_,s):"Error",f=`${this.serviceName}: ${h} (${o}).`;return new FirebaseError(o,f,s)}}const d=/\{\$([^}]+)}/g;function deepEqual(e,i){if(e===i)return!0;const s=Object.keys(e),o=Object.keys(i);for(const _ of s){if(!o.includes(_))return!1;const s=e[_],h=i[_];if(isObject(s)&&isObject(h)){if(!deepEqual(s,h))return!1}else if(s!==h)return!1}for(const e of o)if(!s.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,i,s){this.name=e,this.instanceFactory=i,this.type=s,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}}var f;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(f||(f={}));const g={debug:f.DEBUG,verbose:f.VERBOSE,info:f.INFO,warn:f.WARN,error:f.ERROR,silent:f.SILENT},b=f.INFO,w={[f.DEBUG]:"log",[f.VERBOSE]:"log",[f.INFO]:"info",[f.WARN]:"warn",[f.ERROR]:"error"},defaultLogHandler=(e,i,...s)=>{if(i<e.logLevel)return;const o=(new Date).toISOString(),_=w[i];if(!_)throw new Error(`Attempted to log a message with an invalid logType (value: ${i})`);console[_](`[${o}] ${e.name}:`,...s)};var O,q,j="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};(function(){var e;function m(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function n(e,i,s){s||(s=0);var o=Array(16);if("string"==typeof i)for(var _=0;16>_;++_)o[_]=i.charCodeAt(s++)|i.charCodeAt(s++)<<8|i.charCodeAt(s++)<<16|i.charCodeAt(s++)<<24;else for(_=0;16>_;++_)o[_]=i[s++]|i[s++]<<8|i[s++]<<16|i[s++]<<24;i=e.g[0],s=e.g[1],_=e.g[2];var h=e.g[3],d=i+(h^s&(_^h))+o[0]+3614090360&4294967295;d=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=s+(d<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[1]+3905402710&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[2]+606105819&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[3]+3250441966&4294967295)<<22&4294967295|d>>>10))+((d=i+(h^s&(_^h))+o[4]+4118548399&4294967295)<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[5]+1200080426&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[6]+2821735955&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[7]+4249261313&4294967295)<<22&4294967295|d>>>10))+((d=i+(h^s&(_^h))+o[8]+1770035416&4294967295)<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[9]+2336552879&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[10]+4294925233&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[11]+2304563134&4294967295)<<22&4294967295|d>>>10))+((d=i+(h^s&(_^h))+o[12]+1804603682&4294967295)<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[13]+4254626195&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[14]+2792965006&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[15]+1236535329&4294967295)<<22&4294967295|d>>>10))+((d=i+(_^h&(s^_))+o[1]+4129170786&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[6]+3225465664&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[11]+643717713&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[0]+3921069994&4294967295)<<20&4294967295|d>>>12))+((d=i+(_^h&(s^_))+o[5]+3593408605&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[10]+38016083&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[15]+3634488961&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[4]+3889429448&4294967295)<<20&4294967295|d>>>12))+((d=i+(_^h&(s^_))+o[9]+568446438&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[14]+3275163606&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[3]+4107603335&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[8]+1163531501&4294967295)<<20&4294967295|d>>>12))+((d=i+(_^h&(s^_))+o[13]+2850285829&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[2]+4243563512&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[7]+1735328473&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[12]+2368359562&4294967295)<<20&4294967295|d>>>12))+((d=i+(s^_^h)+o[5]+4294588738&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[8]+2272392833&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[11]+1839030562&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[14]+4259657740&4294967295)<<23&4294967295|d>>>9))+((d=i+(s^_^h)+o[1]+2763975236&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[4]+1272893353&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[7]+4139469664&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[10]+3200236656&4294967295)<<23&4294967295|d>>>9))+((d=i+(s^_^h)+o[13]+681279174&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[0]+3936430074&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[3]+3572445317&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[6]+76029189&4294967295)<<23&4294967295|d>>>9))+((d=i+(s^_^h)+o[9]+3654602809&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[12]+3873151461&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[15]+530742520&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[2]+3299628645&4294967295)<<23&4294967295|d>>>9))+((d=i+(_^(s|~h))+o[0]+4096336452&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[7]+1126891415&4294967295)<<10&4294967295|d>>>22))+((d=_+(i^(h|~s))+o[14]+2878612391&4294967295)<<15&4294967295|d>>>17))+((d=s+(h^(_|~i))+o[5]+4237533241&4294967295)<<21&4294967295|d>>>11))+((d=i+(_^(s|~h))+o[12]+1700485571&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[3]+2399980690&4294967295)<<10&4294967295|d>>>22))+((d=_+(i^(h|~s))+o[10]+4293915773&4294967295)<<15&4294967295|d>>>17))+((d=s+(h^(_|~i))+o[1]+2240044497&4294967295)<<21&4294967295|d>>>11))+((d=i+(_^(s|~h))+o[8]+1873313359&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[15]+4264355552&4294967295)<<10&4294967295|d>>>22))+((d=_+(i^(h|~s))+o[6]+2734768916&4294967295)<<15&4294967295|d>>>17))+((d=s+(h^(_|~i))+o[13]+1309151649&4294967295)<<21&4294967295|d>>>11))+((h=(i=s+((d=i+(_^(s|~h))+o[4]+4149444226&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[11]+3174756917&4294967295)<<10&4294967295|d>>>22))^((_=h+((d=_+(i^(h|~s))+o[2]+718787259&4294967295)<<15&4294967295|d>>>17))|~i))+o[9]+3951481745&4294967295,e.g[0]=e.g[0]+i&4294967295,e.g[1]=e.g[1]+(_+(d<<21&4294967295|d>>>11))&4294967295,e.g[2]=e.g[2]+_&4294967295,e.g[3]=e.g[3]+h&4294967295}function t(e,i){this.h=i;for(var s=[],o=!0,_=e.length-1;0<=_;_--){var h=0|e[_];o&&h==i||(s[_]=h,o=!1)}this.g=s}!function k(e,i){function c(){}c.prototype=i.prototype,e.D=i.prototype,e.prototype=new c,e.prototype.constructor=e,e.C=function(e,s,o){for(var _=Array(arguments.length-2),h=2;h<arguments.length;h++)_[h-2]=arguments[h];return i.prototype[s].apply(e,_)}}(m,(function l(){this.blockSize=-1})),m.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},m.prototype.u=function(e,i){void 0===i&&(i=e.length);for(var s=i-this.blockSize,o=this.B,_=this.h,h=0;h<i;){if(0==_)for(;h<=s;)n(this,e,h),h+=this.blockSize;if("string"==typeof e){for(;h<i;)if(o[_++]=e.charCodeAt(h++),_==this.blockSize){n(this,o),_=0;break}}else for(;h<i;)if(o[_++]=e[h++],_==this.blockSize){n(this,o),_=0;break}}this.h=_,this.o+=i},m.prototype.v=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var i=1;i<e.length-8;++i)e[i]=0;var s=8*this.o;for(i=e.length-8;i<e.length;++i)e[i]=255&s,s/=256;for(this.u(e),e=Array(16),i=s=0;4>i;++i)for(var o=0;32>o;o+=8)e[s++]=this.g[i]>>>o&255;return e};var i={};function u(e){return-128<=e&&128>e?function p(e,s){var o=i;return Object.prototype.hasOwnProperty.call(o,e)?o[e]:o[e]=s(e)}(e,(function(e){return new t([0|e],0>e?-1:0)})):new t([0|e],0>e?-1:0)}function v(e){if(isNaN(e)||!isFinite(e))return s;if(0>e)return x(v(-e));for(var i=[],o=1,_=0;e>=o;_++)i[_]=e/o|0,o*=4294967296;return new t(i,0)}var s=u(0),o=u(1),_=u(16777216);function C(e){if(0!=e.h)return!1;for(var i=0;i<e.g.length;i++)if(0!=e.g[i])return!1;return!0}function B(e){return-1==e.h}function x(e){for(var i=e.g.length,s=[],_=0;_<i;_++)s[_]=~e.g[_];return new t(s,~e.h).add(o)}function F(e,i){return e.add(x(i))}function G(e,i){for(;(65535&e[i])!=e[i];)e[i+1]+=e[i]>>>16,e[i]&=65535,i++}function H(e,i){this.g=e,this.h=i}function D(e,i){if(C(i))throw Error("division by zero");if(C(e))return new H(s,s);if(B(e))return i=D(x(e),i),new H(x(i.g),x(i.h));if(B(i))return i=D(e,x(i)),new H(x(i.g),i.h);if(30<e.g.length){if(B(e)||B(i))throw Error("slowDivide_ only works with positive integers.");for(var _=o,h=i;0>=h.l(e);)_=I(_),h=I(h);var d=J(_,1),f=J(h,1);for(h=J(h,2),_=J(_,2);!C(h);){var g=f.add(h);0>=g.l(e)&&(d=d.add(_),f=g),h=J(h,1),_=J(_,1)}return i=F(e,d.j(i)),new H(d,i)}for(d=s;0<=e.l(i);){for(_=Math.max(1,Math.floor(e.m()/i.m())),h=48>=(h=Math.ceil(Math.log(_)/Math.LN2))?1:Math.pow(2,h-48),g=(f=v(_)).j(i);B(g)||0<g.l(e);)g=(f=v(_-=h)).j(i);C(f)&&(f=o),d=d.add(f),e=F(e,g)}return new H(d,e)}function I(e){for(var i=e.g.length+1,s=[],o=0;o<i;o++)s[o]=e.i(o)<<1|e.i(o-1)>>>31;return new t(s,e.h)}function J(e,i){var s=i>>5;i%=32;for(var o=e.g.length-s,_=[],h=0;h<o;h++)_[h]=0<i?e.i(h+s)>>>i|e.i(h+s+1)<<32-i:e.i(h+s);return new t(_,e.h)}(e=t.prototype).m=function(){if(B(this))return-x(this).m();for(var e=0,i=1,s=0;s<this.g.length;s++){var o=this.i(s);e+=(0<=o?o:4294967296+o)*i,i*=4294967296}return e},e.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(C(this))return"0";if(B(this))return"-"+x(this).toString(e);for(var i=v(Math.pow(e,6)),s=this,o="";;){var _=D(s,i).g,h=((0<(s=F(s,_.j(i))).g.length?s.g[0]:s.h)>>>0).toString(e);if(C(s=_))return h+o;for(;6>h.length;)h="0"+h;o=h+o}},e.i=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return B(e=F(this,e))?-1:C(e)?0:1},e.abs=function(){return B(this)?x(this):this},e.add=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0,_=0;_<=i;_++){var h=o+(65535&this.i(_))+(65535&e.i(_)),d=(h>>>16)+(this.i(_)>>>16)+(e.i(_)>>>16);o=d>>>16,h&=65535,d&=65535,s[_]=d<<16|h}return new t(s,-2147483648&s[s.length-1]?-1:0)},e.j=function(e){if(C(this)||C(e))return s;if(B(this))return B(e)?x(this).j(x(e)):x(x(this).j(e));if(B(e))return x(this.j(x(e)));if(0>this.l(_)&&0>e.l(_))return v(this.m()*e.m());for(var i=this.g.length+e.g.length,o=[],h=0;h<2*i;h++)o[h]=0;for(h=0;h<this.g.length;h++)for(var d=0;d<e.g.length;d++){var f=this.i(h)>>>16,g=65535&this.i(h),b=e.i(d)>>>16,w=65535&e.i(d);o[2*h+2*d]+=g*w,G(o,2*h+2*d),o[2*h+2*d+1]+=f*w,G(o,2*h+2*d+1),o[2*h+2*d+1]+=g*b,G(o,2*h+2*d+1),o[2*h+2*d+2]+=f*b,G(o,2*h+2*d+2)}for(h=0;h<i;h++)o[h]=o[2*h+1]<<16|o[2*h];for(h=i;h<2*i;h++)o[h]=0;return new t(o,0)},e.A=function(e){return D(this,e).h},e.and=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0;o<i;o++)s[o]=this.i(o)&e.i(o);return new t(s,this.h&e.h)},e.or=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0;o<i;o++)s[o]=this.i(o)|e.i(o);return new t(s,this.h|e.h)},e.xor=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0;o<i;o++)s[o]=this.i(o)^e.i(o);return new t(s,this.h^e.h)},m.prototype.digest=m.prototype.v,m.prototype.reset=m.prototype.s,m.prototype.update=m.prototype.u,q=m,t.prototype.add=t.prototype.add,t.prototype.multiply=t.prototype.j,t.prototype.modulo=t.prototype.A,t.prototype.compare=t.prototype.l,t.prototype.toNumber=t.prototype.m,t.prototype.toString=t.prototype.toString,t.prototype.getBits=t.prototype.i,t.fromNumber=v,t.fromString=function y(e,i){if(0==e.length)throw Error("number format error: empty string");if(2>(i=i||10)||36<i)throw Error("radix out of range: "+i);if("-"==e.charAt(0))return x(y(e.substring(1),i));if(0<=e.indexOf("-"))throw Error('number format error: interior "-" character');for(var o=v(Math.pow(i,8)),_=s,h=0;h<e.length;h+=8){var d=Math.min(8,e.length-h),f=parseInt(e.substring(h,h+d),i);8>d?(d=v(Math.pow(i,d)),_=_.j(d).add(v(f))):_=(_=_.j(o)).add(v(f))}return _},O=t}).apply(void 0!==j?j:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var $,ee,te,ne,re,ie,se,oe,ae="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};(function(){var e,i="function"==typeof Object.defineProperties?Object.defineProperty:function(e,i,s){return e==Array.prototype||e==Object.prototype||(e[i]=s.value),e};var s=function ba(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof ae&&ae];for(var i=0;i<e.length;++i){var s=e[i];if(s&&s.Math==Math)return s}throw Error("Cannot find global object")}(this);!function da(e,o){if(o)e:{var _=s;e=e.split(".");for(var h=0;h<e.length-1;h++){var d=e[h];if(!(d in _))break e;_=_[d]}(o=o(h=_[e=e[e.length-1]]))!=h&&null!=o&&i(_,e,{configurable:!0,writable:!0,value:o})}}("Array.prototype.values",(function(e){return e||function(){return function ea(e,i){e instanceof String&&(e+="");var s=0,o=!1,_={next:function(){if(!o&&s<e.length){var _=s++;return{value:i(_,e[_]),done:!1}}return o=!0,{done:!0,value:void 0}}};return _[Symbol.iterator]=function(){return _},_}(this,(function(e,i){return i}))}}));var o=o||{},_=this||self;function ha(e){var i=typeof e;return"array"==(i="object"!=i?i:e?Array.isArray(e)?"array":i:"null")||"object"==i&&"number"==typeof e.length}function n(e){var i=typeof e;return"object"==i&&null!=e||"function"==i}function ia(e,i,s){return e.call.apply(e.bind,arguments)}function ja(e,i,s){if(!e)throw Error();if(2<arguments.length){var o=Array.prototype.slice.call(arguments,2);return function(){var s=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(s,o),e.apply(i,s)}}return function(){return e.apply(i,arguments)}}function p(e,i,s){return(p=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ia:ja).apply(null,arguments)}function ka(e,i){var s=Array.prototype.slice.call(arguments,1);return function(){var i=s.slice();return i.push.apply(i,arguments),e.apply(this,i)}}function r(e,i){function c(){}c.prototype=i.prototype,e.aa=i.prototype,e.prototype=new c,e.prototype.constructor=e,e.Qb=function(e,s,o){for(var _=Array(arguments.length-2),h=2;h<arguments.length;h++)_[h-2]=arguments[h];return i.prototype[s].apply(e,_)}}function la(e){const i=e.length;if(0<i){const s=Array(i);for(let o=0;o<i;o++)s[o]=e[o];return s}return[]}function ma(e,i){for(let i=1;i<arguments.length;i++){const s=arguments[i];if(ha(s)){const i=e.length||0,o=s.length||0;e.length=i+o;for(let _=0;_<o;_++)e[i+_]=s[_]}else e.push(s)}}function t(e){return/^[\s\xa0]*$/.test(e)}function u(){var e=_.navigator;return e&&(e=e.userAgent)?e:""}function oa(e){return oa[" "](e),e}oa[" "]=function(){};var h=!(-1==u().indexOf("Gecko")||-1!=u().toLowerCase().indexOf("webkit")&&-1==u().indexOf("Edge")||-1!=u().indexOf("Trident")||-1!=u().indexOf("MSIE")||-1!=u().indexOf("Edge"));function qa(e,i,s){for(const o in e)i.call(s,e[o],o,e)}function sa(e){const i={};for(const s in e)i[s]=e[s];return i}const d="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ua(e,i){let s,o;for(let i=1;i<arguments.length;i++){for(s in o=arguments[i],o)e[s]=o[s];for(let i=0;i<d.length;i++)s=d[i],Object.prototype.hasOwnProperty.call(o,s)&&(e[s]=o[s])}}function va(e){var i=1;e=e.split(":");const s=[];for(;0<i&&e.length;)s.push(e.shift()),i--;return e.length&&s.push(e.join(":")),s}function wa(e){_.setTimeout((()=>{throw e}),0)}function xa(){var e=w;let i=null;return e.g&&(i=e.g,e.g=e.g.next,e.g||(e.h=null),i.next=null),i}var f=new class na{constructor(e,i){this.i=e,this.j=i,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 Ca),(e=>e.reset()));class Ca{constructor(){this.next=this.g=this.h=null}set(e,i){this.h=e,this.g=i,this.next=null}reset(){this.next=this.g=this.h=null}}let g,b=!1,w=new class Aa{constructor(){this.h=this.g=null}add(e,i){const s=f.get();s.set(e,i),this.h?this.h.next=s:this.g=s,this.h=s}},Ea=()=>{const e=_.Promise.resolve(void 0);g=()=>{e.then(Da)}};var Da=()=>{for(var e;e=xa();){try{e.h.call(e.g)}catch(e){wa(e)}var i=f;i.j(e),100>i.h&&(i.h++,e.next=i.g,i.g=e)}b=!1};function z(){this.s=this.s,this.C=this.C}function A(e,i){this.type=e,this.g=this.target=i,this.defaultPrevented=!1}z.prototype.s=!1,z.prototype.ma=function(){this.s||(this.s=!0,this.N())},z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},A.prototype.h=function(){this.defaultPrevented=!0};var O=function(){if(!_.addEventListener||!Object.defineProperty)return!1;var e=!1,i=Object.defineProperty({},"passive",{get:function(){e=!0}});try{const c=()=>{};_.addEventListener("test",c,i),_.removeEventListener("test",c,i)}catch(e){}return e}();function C(e,i){if(A.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 s=this.type=e.type,o=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=i,i=e.relatedTarget){if(h){e:{try{oa(i.nodeName);var _=!0;break e}catch(e){}_=!1}_||(i=null)}}else"mouseover"==s?i=e.fromElement:"mouseout"==s&&(i=e.toElement);this.relatedTarget=i,o?(this.clientX=void 0!==o.clientX?o.clientX:o.pageX,this.clientY=void 0!==o.clientY?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.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:q[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&C.aa.h.call(this)}}r(C,A);var q={2:"touch",3:"pen",4:"mouse"};C.prototype.h=function(){C.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var j="closure_listenable_"+(1e6*Math.random()|0),ue=0;function Ia(e,i,s,o,_){this.listener=e,this.proxy=null,this.src=i,this.type=s,this.capture=!!o,this.ha=_,this.key=++ue,this.da=this.fa=!1}function Ja(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function Ka(e){this.src=e,this.g={},this.h=0}function Ma(e,i){var s=i.type;if(s in e.g){var o,_=e.g[s],h=Array.prototype.indexOf.call(_,i,void 0);(o=0<=h)&&Array.prototype.splice.call(_,h,1),o&&(Ja(i),0==e.g[s].length&&(delete e.g[s],e.h--))}}function La(e,i,s,o){for(var _=0;_<e.length;++_){var h=e[_];if(!h.da&&h.listener==i&&h.capture==!!s&&h.ha==o)return _}return-1}Ka.prototype.add=function(e,i,s,o,_){var h=e.toString();(e=this.g[h])||(e=this.g[h]=[],this.h++);var d=La(e,i,o,_);return-1<d?(i=e[d],s||(i.fa=!1)):((i=new Ia(i,this.src,h,!!o,_)).fa=s,e.push(i)),i};var ce="closure_lm_"+(1e6*Math.random()|0),le={};function Qa(e,i,s,o,_){if(o&&o.once)return Ra(e,i,s,o,_);if(Array.isArray(i)){for(var h=0;h<i.length;h++)Qa(e,i[h],s,o,_);return null}return s=Sa(s),e&&e[j]?e.K(i,s,n(o)?!!o.capture:!!o,_):Ta(e,i,s,!1,o,_)}function Ta(e,i,s,o,_,h){if(!i)throw Error("Invalid event type");var d=n(_)?!!_.capture:!!_,f=Ua(e);if(f||(e[ce]=f=new Ka(e)),(s=f.add(i,s,o,d,h)).proxy)return s;if(o=function Va(){function a(i){return e.call(a.src,a.listener,i)}const e=Xa;return a}(),s.proxy=o,o.src=e,o.listener=s,e.addEventListener)O||(_=d),void 0===_&&(_=!1),e.addEventListener(i.toString(),o,_);else if(e.attachEvent)e.attachEvent(Wa(i.toString()),o);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(o)}return s}function Ra(e,i,s,o,_){if(Array.isArray(i)){for(var h=0;h<i.length;h++)Ra(e,i[h],s,o,_);return null}return s=Sa(s),e&&e[j]?e.L(i,s,n(o)?!!o.capture:!!o,_):Ta(e,i,s,!0,o,_)}function Ya(e,i,s,o,_){if(Array.isArray(i))for(var h=0;h<i.length;h++)Ya(e,i[h],s,o,_);else o=n(o)?!!o.capture:!!o,s=Sa(s),e&&e[j]?(e=e.i,(i=String(i).toString())in e.g&&(-1<(s=La(h=e.g[i],s,o,_))&&(Ja(h[s]),Array.prototype.splice.call(h,s,1),0==h.length&&(delete e.g[i],e.h--)))):e&&(e=Ua(e))&&(i=e.g[i.toString()],e=-1,i&&(e=La(i,s,o,_)),(s=-1<e?i[e]:null)&&Za(s))}function Za(e){if("number"!=typeof e&&e&&!e.da){var i=e.src;if(i&&i[j])Ma(i.i,e);else{var s=e.type,o=e.proxy;i.removeEventListener?i.removeEventListener(s,o,e.capture):i.detachEvent?i.detachEvent(Wa(s),o):i.addListener&&i.removeListener&&i.removeListener(o),(s=Ua(i))?(Ma(s,e),0==s.h&&(s.src=null,i[ce]=null)):Ja(e)}}}function Wa(e){return e in le?le[e]:le[e]="on"+e}function Xa(e,i){if(e.da)e=!0;else{i=new C(i,this);var s=e.listener,o=e.ha||e.src;e.fa&&Za(e),e=s.call(o,i)}return e}function Ua(e){return(e=e[ce])instanceof Ka?e:null}var _e="__closure_events_fn_"+(1e9*Math.random()>>>0);function Sa(e){return"function"==typeof e?e:(e[_e]||(e[_e]=function(i){return e.handleEvent(i)}),e[_e])}function E(){z.call(this),this.i=new Ka(this),this.M=this,this.F=null}function F(e,i){var s,o=e.F;if(o)for(s=[];o;o=o.F)s.push(o);if(e=e.M,o=i.type||i,"string"==typeof i)i=new A(i,e);else if(i instanceof A)i.target=i.target||e;else{var _=i;ua(i=new A(o,e),_)}if(_=!0,s)for(var h=s.length-1;0<=h;h--){var d=i.g=s[h];_=ab(d,o,!0,i)&&_}if(_=ab(d=i.g=e,o,!0,i)&&_,_=ab(d,o,!1,i)&&_,s)for(h=0;h<s.length;h++)_=ab(d=i.g=s[h],o,!1,i)&&_}function ab(e,i,s,o){if(!(i=e.i.g[String(i)]))return!0;i=i.concat();for(var _=!0,h=0;h<i.length;++h){var d=i[h];if(d&&!d.da&&d.capture==s){var f=d.listener,g=d.ha||d.src;d.fa&&Ma(e.i,d),_=!1!==f.call(g,o)&&_}}return _&&!o.defaultPrevented}function bb(e,i,s){if("function"==typeof e)s&&(e=p(e,s));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=p(e.handleEvent,e)}return 2147483647<Number(i)?-1:_.setTimeout(e,i||0)}function cb(e){e.g=bb((()=>{e.g=null,e.i&&(e.i=!1,cb(e))}),e.l);const i=e.h;e.h=null,e.m.apply(null,i)}r(E,z),E.prototype[j]=!0,E.prototype.removeEventListener=function(e,i,s,o){Ya(this,e,i,s,o)},E.prototype.N=function(){if(E.aa.N.call(this),this.i){var e,i=this.i;for(e in i.g){for(var s=i.g[e],o=0;o<s.length;o++)Ja(s[o]);delete i.g[e],i.h--}}this.F=null},E.prototype.K=function(e,i,s,o){return this.i.add(String(e),i,!1,s,o)},E.prototype.L=function(e,i,s,o){return this.i.add(String(e),i,!0,s,o)};class eb extends z{constructor(e,i){super(),this.m=e,this.l=i,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:cb(this)}N(){super.N(),this.g&&(_.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function G(e){z.call(this),this.h=e,this.g={}}r(G,z);var he=[];function gb(e){qa(e.g,(function(e,i){this.g.hasOwnProperty(i)&&Za(e)}),e),e.g={}}G.prototype.N=function(){G.aa.N.call(this),gb(this)},G.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var de=_.JSON.stringify,me=_.JSON.parse;function kb(){}function lb(e){return e.h||(e.h=e.i())}function mb(){}kb.prototype.h=null;var fe={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function nb(){A.call(this,"d")}function ob(){A.call(this,"c")}r(nb,A),r(ob,A);var ge={},Ie=null;function qb(){return Ie=Ie||new E}function rb(e){A.call(this,ge.La,e)}function J(e){const i=qb();F(i,new rb(i))}function sb(e,i){A.call(this,ge.STAT_EVENT,e),this.stat=i}function K(e){const i=qb();F(i,new sb(i,e))}function tb(e,i){A.call(this,ge.Ma,e),this.size=i}function ub(e,i){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return _.setTimeout((function(){e()}),i)}function vb(){this.g=!0}function L(e,i,s,o){e.info((function(){return"XMLHTTP TEXT ("+i+"): "+function yb(e,i){if(!e.g)return i;if(!i)return null;try{var s=JSON.parse(i);if(s)for(e=0;e<s.length;e++)if(Array.isArray(s[e])){var o=s[e];if(!(2>o.length)){var _=o[1];if(Array.isArray(_)&&!(1>_.length)){var h=_[0];if("noop"!=h&&"stop"!=h&&"close"!=h)for(var d=1;d<_.length;d++)_[d]=""}}}return de(s)}catch(e){return i}}(e,s)+(o?" "+o:"")}))}ge.La="serverreachability",r(rb,A),ge.STAT_EVENT="statevent",r(sb,A),ge.Ma="timingevent",r(tb,A),vb.prototype.xa=function(){this.g=!1},vb.prototype.info=function(){};var Te,pe={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Ee={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function Db(){}function M(e,i,s,o){this.j=e,this.i=i,this.l=s,this.R=o||1,this.U=new G(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 Eb}function Eb(){this.i=null,this.g="",this.h=!1}r(Db,kb),Db.prototype.g=function(){return new XMLHttpRequest},Db.prototype.i=function(){return{}},Te=new Db;var Pe={},Ae={};function Hb(e,i,s){e.L=1,e.v=Ib(N(i)),e.m=s,e.P=!0,Jb(e,null)}function Jb(e,i){e.F=Date.now(),Kb(e),e.A=N(e.v);var s=e.A,o=e.R;Array.isArray(o)||(o=[String(o)]),Lb(s.i,"t",o),e.C=0,s=e.j.J,e.h=new Eb,e.g=Mb(e.j,s?i:null,!e.m),0<e.O&&(e.M=new eb(p(e.Y,e,e.g),e.O)),i=e.U,s=e.g,o=e.ca;var _="readystatechange";Array.isArray(_)||(_&&(he[0]=_.toString()),_=he);for(var h=0;h<_.length;h++){var d=Qa(s,_[h],o||i.handleEvent,!1,i.h||i);if(!d)break;i.g[d.key]=d}i=e.H?sa(e.H):{},e.m?(e.u||(e.u="POST"),i["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,i)):(e.u="GET",e.g.ea(e.A,e.u,null,i)),J(),function wb(e,i,s,o,_,h){e.info((function(){if(e.g)if(h)for(var d="",f=h.split("&"),g=0;g<f.length;g++){var b=f[g].split("=");if(1<b.length){var w=b[0];b=b[1];var O=w.split("_");d=2<=O.length&&"type"==O[1]?d+(w+"=")+b+"&":d+(w+"=redacted&")}}else d=null;else d=h;return"XMLHTTP REQ ("+o+") [attempt "+_+"]: "+i+"\n"+s+"\n"+d}))}(e.i,e.u,e.A,e.l,e.R,e.m)}function Pb(e){return!!e.g&&("GET"==e.u&&2!=e.L&&e.j.Ca)}function Sb(e,i){var s=e.C,o=i.indexOf("\n",s);return-1==o?Ae:(s=Number(i.substring(s,o)),isNaN(s)?Pe:(o+=1)+s>i.length?Ae:(i=i.slice(o,o+s),e.C=o+s,i))}function Kb(e){e.S=Date.now()+e.I,Wb(e,e.I)}function Wb(e,i){if(null!=e.B)throw Error("WatchDog timer not null");e.B=ub(p(e.ba,e),i)}function Ob(e){e.B&&(_.clearTimeout(e.B),e.B=null)}function Qb(e){0==e.j.G||e.J||Ub(e.j,e)}function Q(e){Ob(e);var i=e.M;i&&"function"==typeof i.ma&&i.ma(),e.M=null,gb(e.U),e.g&&(i=e.g,e.g=null,i.abort(),i.ma())}function Rb(e,i){try{var s=e.j;if(0!=s.G&&(s.g==e||Xb(s.h,e)))if(!e.K&&Xb(s.h,e)&&3==s.G){try{var o=s.Da.g.parse(i)}catch(e){o=null}if(Array.isArray(o)&&3==o.length){var _=o;if(0==_[0]){e:if(!s.u){if(s.g){if(!(s.g.F+3e3<e.F))break e;Yb(s),Zb(s)}$b(s),K(18)}}else s.za=_[1],0<s.za-s.T&&37500>_[2]&&s.F&&0==s.v&&!s.C&&(s.C=ub(p(s.Za,s),6e3));if(1>=ac(s.h)&&s.ca){try{s.ca()}catch(e){}s.ca=void 0}}else R(s,11)}else if((e.K||s.g==e)&&Yb(s),!t(i))for(_=s.Da.g.parse(i),i=0;i<_.length;i++){let b=_[i];if(s.T=b[0],b=b[1],2==s.G)if("c"==b[0]){s.K=b[1],s.ia=b[2];const i=b[3];null!=i&&(s.la=i,s.j.info("VER="+s.la));const _=b[4];null!=_&&(s.Aa=_,s.j.info("SVER="+s.Aa));const w=b[5];null!=w&&"number"==typeof w&&0<w&&(o=1.5*w,s.L=o,s.j.info("backChannelRequestTimeoutMs_="+o)),o=s;const O=e.g;if(O){const e=O.g?O.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var h=o.h;h.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(h.j=h.l,h.g=new Set,h.h&&(bc(h,h.h),h.h=null))}if(o.D){const e=O.g?O.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(o.ya=e,S(o.I,o.D,e))}}s.G=3,s.l&&s.l.ua(),s.ba&&(s.R=Date.now()-e.F,s.j.info("Handshake RTT: "+s.R+"ms"));var d=e;if((o=s).qa=cc(o,o.J?o.ia:null,o.W),d.K){dc(o.h,d);var f=d,g=o.L;g&&(f.I=g),f.B&&(Ob(f),Kb(f)),o.g=d}else ec(o);0<s.i.length&&fc(s)}else"stop"!=b[0]&&"close"!=b[0]||R(s,7);else 3==s.G&&("stop"==b[0]||"close"==b[0]?"stop"==b[0]?R(s,7):gc(s):"noop"!=b[0]&&s.l&&s.l.ta(b),s.v=0)}J()}catch(e){}}M.prototype.ca=function(e){e=e.target;const i=this.M;i&&3==P(e)?i.j():this.Y(e)},M.prototype.Y=function(e){try{if(e==this.g)e:{const q=P(this.g);var i=this.g.Ba();this.g.Z();if(!(3>q)&&(3!=q||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=q||7==i||J(),Ob(this);var s=this.g.Z();this.X=s;t:if(Pb(this)){var o=Nb(this.g);e="";var h=o.length,d=4==P(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Q(this),Qb(this);var f="";break t}this.h.i=new _.TextDecoder}for(i=0;i<h;i++)this.h.h=!0,e+=this.h.i.decode(o[i],{stream:!(d&&i==h-1)});o.length=0,this.h.g+=e,this.C=0,f=this.h.g}else f=this.g.oa();if(this.o=200==s,function xb(e,i,s,o,_,h,d){e.info((function(){return"XMLHTTP RESP ("+o+") [ attempt "+_+"]: "+i+"\n"+s+"\n"+h+" "+d}))}(this.i,this.u,this.A,this.l,this.R,q,s),this.o){if(this.T&&!this.K){t:{if(this.g){var g,b=this.g;if((g=b.g?b.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!t(g)){var w=g;break t}}w=null}if(!(s=w)){this.o=!1,this.s=3,K(12),Q(this),Qb(this);break e}L(this.i,this.l,s,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Rb(this,s)}if(this.P){let e;for(s=!0;!this.J&&this.C<f.length;){if(e=Sb(this,f),e==Ae){4==q&&(this.s=4,K(14),s=!1),L(this.i,this.l,null,"[Incomplete Response]");break}if(e==Pe){this.s=4,K(15),L(this.i,this.l,f,"[Invalid Chunk]"),s=!1;break}L(this.i,this.l,e,null),Rb(this,e)}if(Pb(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=q||0!=f.length||this.h.h||(this.s=1,K(16),s=!1),this.o=this.o&&s,s){if(0<f.length&&!this.W){this.W=!0;var O=this.j;O.g==this&&O.ba&&!O.M&&(O.j.info("Great, no buffering proxy detected. Bytes received: "+f.length),Tb(O),O.M=!0,K(11))}}else L(this.i,this.l,f,"[Invalid Chunked Response]"),Q(this),Qb(this)}else L(this.i,this.l,f,null),Rb(this,f);4==q&&Q(this),this.o&&!this.J&&(4==q?Ub(this.j,this):(this.o=!1,Kb(this)))}else(function Vb(e){const i={};e=(e.g&&2<=P(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let o=0;o<e.length;o++){if(t(e[o]))continue;var s=va(e[o]);const _=s[0];if("string"!=typeof(s=s[1]))continue;s=s.trim();const h=i[_]||[];i[_]=h,h.push(s)}!function ra(e,i){for(const s in e)i.call(void 0,e[s],s,e)}(i,(function(e){return e.join(", ")}))})(this.g),400==s&&0<f.indexOf("Unknown SID")?(this.s=3,K(12)):(this.s=0,K(13)),Q(this),Qb(this)}}}catch(e){}},M.prototype.cancel=function(){this.J=!0,Q(this)},M.prototype.ba=function(){this.B=null;const e=Date.now();0<=e-this.S?(function zb(e,i){e.info((function(){return"TIMEOUT: "+i}))}(this.i,this.A),2!=this.L&&(J(),K(17)),Q(this),this.s=2,Qb(this)):Wb(this,this.S-e)};function ic(e){this.l=e||10,_.PerformanceNavigationTiming?e=0<(e=_.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):e=!!(_.chrome&&_.chrome.loadTimes&&_.chrome.loadTimes()&&_.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 jc(e){return!!e.h||!!e.g&&e.g.size>=e.j}function ac(e){return e.h?1:e.g?e.g.size:0}function Xb(e,i){return e.h?e.h==i:!!e.g&&e.g.has(i)}function bc(e,i){e.g?e.g.add(i):e.h=i}function dc(e,i){e.h&&e.h==i?e.h=null:e.g&&e.g.has(i)&&e.g.delete(i)}function kc(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let i=e.i;for(const s of e.g.values())i=i.concat(s.D);return i}return la(e.i)}function nc(e,i){if(e.forEach&&"function"==typeof e.forEach)e.forEach(i,void 0);else if(ha(e)||"string"==typeof e)Array.prototype.forEach.call(e,i,void 0);else for(var s=function mc(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(ha(e)||"string"==typeof e){var i=[];e=e.length;for(var s=0;s<e;s++)i.push(s);return i}i=[],s=0;for(const o in e)i[s++]=o;return i}}}(e),o=function lc(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(ha(e)){for(var i=[],s=e.length,o=0;o<s;o++)i.push(e[o]);return i}for(o in i=[],s=0,e)i[s++]=e[o];return i}(e),_=o.length,h=0;h<_;h++)i.call(void 0,o[h],s&&s[h],e)}ic.prototype.cancel=function(){if(this.i=kc(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 Re=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function T(e){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof T){this.h=e.h,qc(this,e.j),this.o=e.o,this.g=e.g,rc(this,e.s),this.l=e.l;var i=e.i,s=new sc;s.i=i.i,i.g&&(s.g=new Map(i.g),s.h=i.h),tc(this,s),this.m=e.m}else e&&(i=String(e).match(Re))?(this.h=!1,qc(this,i[1]||"",!0),this.o=uc(i[2]||""),this.g=uc(i[3]||"",!0),rc(this,i[4]),this.l=uc(i[5]||"",!0),tc(this,i[6]||"",!0),this.m=uc(i[7]||"")):(this.h=!1,this.i=new sc(null,this.h))}function N(e){return new T(e)}function qc(e,i,s){e.j=s?uc(i,!0):i,e.j&&(e.j=e.j.replace(/:$/,""))}function rc(e,i){if(i){if(i=Number(i),isNaN(i)||0>i)throw Error("Bad port number "+i);e.s=i}else e.s=null}function tc(e,i,s){i instanceof sc?(e.i=i,function Ac(e,i){i&&!e.j&&(U(e),e.i=null,e.g.forEach((function(e,i){var s=i.toLowerCase();i!=s&&(Dc(this,i),Lb(this,s,e))}),e)),e.j=i}(e.i,e.h)):(s||(i=vc(i,Se)),e.i=new sc(i,e.h))}function S(e,i,s){e.i.set(i,s)}function Ib(e){return S(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function uc(e,i){return e?i?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function vc(e,i,s){return"string"==typeof e?(e=encodeURI(e).replace(i,Cc),s&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function Cc(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}T.prototype.toString=function(){var e=[],i=this.j;i&&e.push(vc(i,Ve,!0),":");var s=this.g;return(s||"file"==i)&&(e.push("//"),(i=this.o)&&e.push(vc(i,Ve,!0),"@"),e.push(encodeURIComponent(String(s)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(s=this.s)&&e.push(":",String(s))),(s=this.l)&&(this.g&&"/"!=s.charAt(0)&&e.push("/"),e.push(vc(s,"/"==s.charAt(0)?be:ve,!0))),(s=this.i.toString())&&e.push("?",s),(s=this.m)&&e.push("#",vc(s,we)),e.join("")};var ye,Ve=/[#\/\?@]/g,ve=/[#\?:]/g,be=/[#\?]/g,Se=/[#\?@]/g,we=/#/g;function sc(e,i){this.h=this.g=null,this.i=e||null,this.j=!!i}function U(e){e.g||(e.g=new Map,e.h=0,e.i&&function pc(e,i){if(e){e=e.split("&");for(var s=0;s<e.length;s++){var o=e[s].indexOf("="),_=null;if(0<=o){var h=e[s].substring(0,o);_=e[s].substring(o+1)}else h=e[s];i(h,_?decodeURIComponent(_.replace(/\+/g," ")):"")}}}(e.i,(function(i,s){e.add(decodeURIComponent(i.replace(/\+/g," ")),s)})))}function Dc(e,i){U(e),i=V(e,i),e.g.has(i)&&(e.i=null,e.h-=e.g.get(i).length,e.g.delete(i))}function Ec(e,i){return U(e),i=V(e,i),e.g.has(i)}function Lb(e,i,s){Dc(e,i),0<s.length&&(e.i=null,e.g.set(V(e,i),la(s)),e.h+=s.length)}function V(e,i){return i=String(i),e.j&&(i=i.toLowerCase()),i}function W(e,i,s,o,_){try{_&&(_.onload=null,_.onerror=null,_.onabort=null,_.ontimeout=null),o(s)}catch(e){}}function Hc(){this.g=new class{stringify(e){return _.JSON.stringify(e,void 0)}parse(e){return _.JSON.parse(e,void 0)}}}function Ic(e,i,s){const o=s||"";try{nc(e,(function(e,s){let _=e;n(e)&&(_=de(e)),i.push(o+s+"="+encodeURIComponent(_))}))}catch(e){throw i.push(o+"type="+encodeURIComponent("_badmap")),e}}function Jc(e){this.l=e.Ub||null,this.j=e.eb||!1}function Kc(e,i){E.call(this),this.D=e,this.o=i,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 Nc(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Mc(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Lc(e)}function Lc(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Oc(e){let i="";return qa(e,(function(e,s){i+=s,i+=":",i+=e,i+="\r\n"})),i}function Pc(e,i,s){e:{for(o in s){var o=!1;break e}o=!0}o||(s=Oc(s),"string"==typeof e?null!=s&&encodeURIComponent(String(s)):S(e,i,s))}function X(e){E.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=sc.prototype).add=function(e,i){U(this),this.i=null,e=V(this,e);var s=this.g.get(e);return s||this.g.set(e,s=[]),s.push(i),this.h+=1,this},e.forEach=function(e,i){U(this),this.g.forEach((function(s,o){s.forEach((function(s){e.call(i,s,o,this)}),this)}),this)},e.na=function(){U(this);const e=Array.from(this.g.values()),i=Array.from(this.g.keys()),s=[];for(let o=0;o<i.length;o++){const _=e[o];for(let e=0;e<_.length;e++)s.push(i[o])}return s},e.V=function(e){U(this);let i=[];if("string"==typeof e)Ec(this,e)&&(i=i.concat(this.g.get(V(this,e))));else{e=Array.from(this.g.values());for(let s=0;s<e.length;s++)i=i.concat(e[s])}return i},e.set=function(e,i){return U(this),this.i=null,Ec(this,e=V(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[i]),this.h+=1,this},e.get=function(e,i){return e&&0<(e=this.V(e)).length?String(e[0]):i},e.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],i=Array.from(this.g.keys());for(var s=0;s<i.length;s++){var o=i[s];const h=encodeURIComponent(String(o)),d=this.V(o);for(o=0;o<d.length;o++){var _=h;""!==d[o]&&(_+="="+encodeURIComponent(String(d[o]))),e.push(_)}}return this.i=e.join("&")},r(Jc,kb),Jc.prototype.g=function(){return new Kc(this.l,this.j)},Jc.prototype.i=(ye={},function(){return ye}),r(Kc,E),(e=Kc.prototype).open=function(e,i){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=i,this.readyState=1,Lc(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const i={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(i.body=e),(this.D||_).fetch(new Request(this.A,i)).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,Mc(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,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==_.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;Nc(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=function(e){if(this.g){if(this.o&&e.value)this.response.push(e.value);else if(!this.o){var i=e.value?e.value:new Uint8Array(0);(i=this.v.decode(i,{stream:!e.done}))&&(this.response=this.responseText+=i)}e.done?Mc(this):Lc(this),3==this.readyState&&Nc(this)}},e.Ra=function(e){this.g&&(this.response=this.responseText=e,Mc(this))},e.Qa=function(e){this.g&&(this.response=e,Mc(this))},e.ga=function(){this.g&&Mc(this)},e.setRequestHeader=function(e,i){this.u.append(e,i)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],i=this.h.entries();for(var s=i.next();!s.done;)s=s.value,e.push(s[0]+": "+s[1]),s=i.next();return e.join("\r\n")},Object.defineProperty(Kc.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),r(X,E);var De=/^https?$/i,Ce=["POST","PUT"];function Sc(e,i){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=i,e.m=5,Uc(e),Vc(e)}function Uc(e){e.A||(e.A=!0,F(e,"complete"),F(e,"error"))}function Wc(e){if(e.h&&void 0!==o&&(!e.v[1]||4!=P(e)||2!=e.Z()))if(e.u&&4==P(e))bb(e.Ea,0,e);else if(F(e,"readystatechange"),4==P(e)){e.h=!1;try{const o=e.Z();e:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var i=!0;break e;default:i=!1}var s;if(!(s=i)){var h;if(h=0===o){var d=String(e.D).match(Re)[1]||null;!d&&_.self&&_.self.location&&(d=_.self.location.protocol.slice(0,-1)),h=!De.test(d?d.toLowerCase():"")}s=h}if(s)F(e,"complete"),F(e,"success");else{e.m=6;try{var f=2<P(e)?e.g.statusText:""}catch(e){f=""}e.l=f+" ["+e.Z()+"]",Uc(e)}}finally{Vc(e)}}}function Vc(e,i){if(e.g){Tc(e);const s=e.g,o=e.v[0]?()=>{}:null;e.g=null,e.v=null,i||F(e,"ready");try{s.onreadystatechange=o}catch(e){}}}function Tc(e){e.I&&(_.clearTimeout(e.I),e.I=null)}function P(e){return e.g?e.g.readyState:0}function Nb(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 Xc(e,i,s){return s&&s.internalChannelParams&&s.internalChannelParams[e]||i}function Yc(e){this.Aa=0,this.i=[],this.j=new vb,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=Xc("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=Xc("baseRetryDelayMs",5e3,e),this.cb=Xc("retryDelaySeedMs",1e4,e),this.Wa=Xc("forwardChannelMaxRetries",2,e),this.wa=Xc("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 ic(e&&e.concurrentRequestLimit),this.Da=new Hc,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 gc(e){if(Zc(e),3==e.G){var i=e.U++,s=N(e.I);if(S(s,"SID",e.K),S(s,"RID",i),S(s,"TYPE","terminate"),$c(e,s),(i=new M(e,e.j,i)).L=2,i.v=Ib(N(s)),s=!1,_.navigator&&_.navigator.sendBeacon)try{s=_.navigator.sendBeacon(i.v.toString(),"")}catch(e){}!s&&_.Image&&((new Image).src=i.v,s=!0),s||(i.g=Mb(i.j,null),i.g.ea(i.v)),i.F=Date.now(),Kb(i)}ad(e)}function Zb(e){e.g&&(Tb(e),e.g.cancel(),e.g=null)}function Zc(e){Zb(e),e.u&&(_.clearTimeout(e.u),e.u=null),Yb(e),e.h.cancel(),e.s&&("number"==typeof e.s&&_.clearTimeout(e.s),e.s=null)}function fc(e){if(!jc(e.h)&&!e.s){e.s=!0;var i=e.Ga;g||Ea(),b||(g(),b=!0),w.add(i,e),e.B=0}}function ed(e,i){var s;s=i?i.l:e.U++;const o=N(e.I);S(o,"SID",e.K),S(o,"RID",s),S(o,"AID",e.T),$c(e,o),e.m&&e.o&&Pc(o,e.m,e.o),s=new M(e,e.j,s,e.B+1),null===e.m&&(s.H=e.o),i&&(e.i=i.D.concat(e.i)),i=dd(e,s,1e3),s.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),bc(e.h,s),Hb(s,o,i)}function $c(e,i){e.H&&qa(e.H,(function(e,s){S(i,s,e)})),e.l&&nc({},(function(e,s){S(i,s,e)}))}function dd(e,i,s){s=Math.min(e.i.length,s);var o=e.l?p(e.l.Na,e.l,e):null;e:{var _=e.i;let i=-1;for(;;){const e=["count="+s];-1==i?0<s?(i=_[0].g,e.push("ofs="+i)):i=0:e.push("ofs="+i);let h=!0;for(let d=0;d<s;d++){let s=_[d].g;const f=_[d].map;if(s-=i,0>s)i=Math.max(0,_[d].g-100),h=!1;else try{Ic(f,e,"req"+s+"_")}catch(e){o&&o(f)}}if(h){o=e.join("&");break e}}}return e=e.i.splice(0,s),i.D=e,o}function ec(e){if(!e.g&&!e.u){e.Y=1;var i=e.Fa;g||Ea(),b||(g(),b=!0),w.add(i,e),e.v=0}}function $b(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=ub(p(e.Fa,e),cd(e,e.v)),e.v++,!0)}function Tb(e){null!=e.A&&(_.clearTimeout(e.A),e.A=null)}function fd(e){e.g=new M(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var i=N(e.qa);S(i,"RID","rpc"),S(i,"SID",e.K),S(i,"AID",e.T),S(i,"CI",e.F?"0":"1"),!e.F&&e.ja&&S(i,"TO",e.ja),S(i,"TYPE","xmlhttp"),$c(e,i),e.m&&e.o&&Pc(i,e.m,e.o),e.L&&(e.g.I=e.L);var s=e.g;e=e.ia,s.L=1,s.v=Ib(N(i)),s.m=null,s.P=!0,Jb(s,e)}function Yb(e){null!=e.C&&(_.clearTimeout(e.C),e.C=null)}function Ub(e,i){var s=null;if(e.g==i){Yb(e),Tb(e),e.g=null;var o=2}else{if(!Xb(e.h,i))return;s=i.D,dc(e.h,i),o=1}if(0!=e.G)if(i.o)if(1==o){s=i.m?i.m.length:0,i=Date.now()-i.F;var _=e.B;F(o=qb(),new tb(o,s)),fc(e)}else ec(e);else if(3==(_=i.s)||0==_&&0<i.X||!(1==o&&function bd(e,i){return!(ac(e.h)>=e.h.j-(e.s?1:0)||(e.s?(e.i=i.D.concat(e.i),0):1==e.G||2==e.G||e.B>=(e.Va?0:e.Wa)||(e.s=ub(p(e.Ga,e,i),cd(e,e.B)),e.B++,0)))}(e,i)||2==o&&$b(e)))switch(s&&0<s.length&&(i=e.h,i.i=i.i.concat(s)),_){case 1:R(e,5);break;case 4:R(e,10);break;case 3:R(e,6);break;default:R(e,2)}}function cd(e,i){let s=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(s*=2),s*i}function R(e,i){if(e.j.info("Error code "+i),2==i){var s=p(e.fb,e),o=e.Xa;const i=!o;o=new T(o||"//www.google.com/images/cleardot.gif"),_.location&&"http"==_.location.protocol||qc(o,"https"),Ib(o),i?function Fc(e,i){const s=new vb;if(_.Image){const o=new Image;o.onload=ka(W,s,"TestLoadImage: loaded",!0,i,o),o.onerror=ka(W,s,"TestLoadImage: error",!1,i,o),o.onabort=ka(W,s,"TestLoadImage: abort",!1,i,o),o.ontimeout=ka(W,s,"TestLoadImage: timeout",!1,i,o),_.setTimeout((function(){o.ontimeout&&o.ontimeout()}),1e4),o.src=e}else i(!1)}(o.toString(),s):function Gc(e,i){new vb;const s=new AbortController,o=setTimeout((()=>{s.abort(),W(0,0,!1,i)}),1e4);fetch(e,{signal:s.signal}).then((e=>{clearTimeout(o),e.ok?W(0,0,!0,i):W(0,0,!1,i)})).catch((()=>{clearTimeout(o),W(0,0,!1,i)}))}(o.toString(),s)}else K(2);e.G=0,e.l&&e.l.sa(i),ad(e),Zc(e)}function ad(e){if(e.G=0,e.ka=[],e.l){const i=kc(e.h);0==i.length&&0==e.i.length||(ma(e.ka,i),ma(e.ka,e.i),e.h.i.length=0,la(e.i),e.i.length=0),e.l.ra()}}function cc(e,i,s){var o=s instanceof T?N(s):new T(s);if(""!=o.g)i&&(o.g=i+"."+o.g),rc(o,o.s);else{var h=_.location;o=h.protocol,i=i?i+"."+h.hostname:h.hostname,h=+h.port;var d=new T(null);o&&qc(d,o),i&&(d.g=i),h&&rc(d,h),s&&(d.l=s),o=d}return s=e.D,i=e.ya,s&&i&&S(o,s,i),S(o,"VER",e.la),$c(e,o),o}function Mb(e,i,s){if(i&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(i=e.Ca&&!e.pa?new X(new Jc({eb:s})):new X(e.pa)).Ha(e.J),i}function gd(){}function hd(){}function Y(e,i){E.call(this),this.g=new Yc(i),this.l=e,this.h=i&&i.messageUrlParams||null,e=i&&i.messageHeaders||null,i&&i.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=i&&i.initMessageHeaders||null,i&&i.messageContentType&&(e?e["X-WebChannel-Content-Type"]=i.messageContentType:e={"X-WebChannel-Content-Type":i.messageContentType}),i&&i.va&&(e?e["X-WebChannel-Client-Profile"]=i.va:e={"X-WebChannel-Client-Profile":i.va}),this.g.S=e,(e=i&&i.Sb)&&!t(e)&&(this.g.m=e),this.v=i&&i.supportsCrossDomainXhr||!1,this.u=i&&i.sendRawJson||!1,(i=i&&i.httpSessionIdParam)&&!t(i)&&(this.g.D=i,null!==(e=this.h)&&i in e&&(i in(e=this.h)&&delete e[i])),this.j=new Z(this)}function id(e){nb.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var i=e.__sm__;if(i){e:{for(const s in i){e=s;break e}e=void 0}(this.i=e)&&(e=this.i,i=null!==i&&e in i?i[e]:void 0),this.data=i}else this.data=e}function jd(){ob.call(this),this.status=1}function Z(e){this.g=e}(e=X.prototype).Ha=function(e){this.J=e},e.ea=function(e,i,s,o){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);i=i?i.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Te.g(),this.v=this.o?lb(this.o):lb(Te),this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(i,String(e),!0),this.B=!1}catch(e){return void Sc(this,e)}if(e=s||"",s=new Map(this.headers),o)if(Object.getPrototypeOf(o)===Object.prototype)for(var h in o)s.set(h,o[h]);else{if("function"!=typeof o.keys||"function"!=typeof o.get)throw Error("Unknown input type for opt_headers: "+String(o));for(const e of o.keys())s.set(e,o.get(e))}o=Array.from(s.keys()).find((e=>"content-type"==e.toLowerCase())),h=_.FormData&&e instanceof _.FormData,!(0<=Array.prototype.indexOf.call(Ce,i,void 0))||o||h||s.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[e,i]of s)this.g.setRequestHeader(e,i);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){Sc(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,F(this,"complete"),F(this,"abort"),Vc(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0)),X.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb())},e.bb=function(){Wc(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2<P(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 i=this.g.responseText;return e&&0==i.indexOf(e)&&(i=i.substring(e.length)),me(i)}},e.Ba=function(){return this.m},e.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=Yc.prototype).la=8,e.G=1,e.connect=function(e,i,s,o){K(0),this.W=e,this.H=i||{},s&&void 0!==o&&(this.H.OSID=s,this.H.OAID=o),this.F=this.X,this.I=cc(this,null,this.W),fc(this)},e.Ga=function(e){if(this.s)if(this.s=null,1==this.G){if(!e){this.U=Math.floor(1e5*Math.random()),e=this.U++;const _=new M(this,this.j,e);let h=this.o;if(this.S&&(h?(h=sa(h),ua(h,this.S)):h=this.S),null!==this.m||this.O||(_.H=h,h=null),this.P)e:{for(var i=0,s=0;s<this.i.length;s++){var o=this.i[s];if(void 0===(o="__data__"in o.map&&"string"==typeof(o=o.map.__data__)?o.length:void 0))break;if(4096<(i+=o)){i=s;break e}if(4096===i||s===this.i.length-1){i=s+1;break e}}i=1e3}else i=1e3;i=dd(this,_,i),S(s=N(this.I),"RID",e),S(s,"CVER",22),this.D&&S(s,"X-HTTP-Session-Id",this.D),$c(this,s),h&&(this.O?i="headers="+encodeURIComponent(String(Oc(h)))+"&"+i:this.m&&Pc(s,this.m,h)),bc(this.h,_),this.Ua&&S(s,"TYPE","init"),this.P?(S(s,"$req",i),S(s,"SID","null"),_.T=!0,Hb(_,s,null)):Hb(_,s,i),this.G=2}}else 3==this.G&&(e?ed(this,e):0==this.i.length||jc(this.h)||ed(this))},e.Fa=function(){if(this.u=null,fd(this),this.ba&&!(this.M||null==this.g||0>=this.R)){var e=2*this.R;this.j.info("BP detection timer enabled: "+e),this.A=ub(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,K(10),Zb(this),fd(this))},e.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19))},e.fb=function(e){e?(this.j.info("Successfully pinged google.com"),K(2)):(this.j.info("Failed to ping google.com"),K(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=gd.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},hd.prototype.g=function(e,i){return new Y(e,i)},r(Y,E),Y.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Y.prototype.close=function(){gc(this.g)},Y.prototype.o=function(e){var i=this.g;if("string"==typeof e){var s={};s.__data__=e,e=s}else this.u&&((s={}).__data__=de(e),e=s);i.i.push(new class{constructor(e,i){this.g=e,this.map=i}}(i.Ya++,e)),3==i.G&&fc(i)},Y.prototype.N=function(){this.g.l=null,delete this.j,gc(this.g),delete this.g,Y.aa.N.call(this)},r(id,nb),r(jd,ob),r(Z,gd),Z.prototype.ua=function(){F(this.g,"a")},Z.prototype.ta=function(e){F(this.g,new id(e))},Z.prototype.sa=function(e){F(this.g,new jd)},Z.prototype.ra=function(){F(this.g,"b")},hd.prototype.createWebChannel=hd.prototype.g,Y.prototype.send=Y.prototype.o,Y.prototype.open=Y.prototype.m,Y.prototype.close=Y.prototype.close,oe=function(){return new hd},se=function(){return qb()},ie=ge,re={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},pe.NO_ERROR=0,pe.TIMEOUT=8,pe.HTTP_ERROR=6,ne=pe,Ee.COMPLETE="complete",te=Ee,mb.EventType=fe,fe.OPEN="a",fe.CLOSE="b",fe.ERROR="c",fe.MESSAGE="d",E.prototype.listen=E.prototype.K,ee=mb,X.prototype.listenOnce=X.prototype.L,X.prototype.getLastError=X.prototype.Ka,X.prototype.getLastErrorCode=X.prototype.Ba,X.prototype.getStatus=X.prototype.Z,X.prototype.getResponseJson=X.prototype.Oa,X.prototype.getResponseText=X.prototype.oa,X.prototype.send=X.prototype.ea,X.prototype.setWithCredentials=X.prototype.Ha,$=X}).apply(void 0!==ae?ae:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});const ue="@firebase/firestore";class User{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}}User.UNAUTHENTICATED=new User(null),User.GOOGLE_CREDENTIALS=new User("google-credentials-uid"),User.FIRST_PARTY=new User("first-party-uid"),User.MOCK_USER=new User("mock-user");let ce="11.0.1";const le=new class Logger{constructor(e){this.name=e,this._logLevel=b,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in f))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?g[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,f.DEBUG,...e),this._logHandler(this,f.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,f.VERBOSE,...e),this._logHandler(this,f.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,f.INFO,...e),this._logHandler(this,f.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,f.WARN,...e),this._logHandler(this,f.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,f.ERROR,...e),this._logHandler(this,f.ERROR,...e)}}("@firebase/firestore");function __PRIVATE_getLogLevel(){return le.logLevel}function setLogLevel(e){le.setLogLevel(e)}function __PRIVATE_logDebug(e,...i){if(le.logLevel<=f.DEBUG){const s=i.map(__PRIVATE_argToString);le.debug(`Firestore (${ce}): ${e}`,...s)}}function __PRIVATE_logError(e,...i){if(le.logLevel<=f.ERROR){const s=i.map(__PRIVATE_argToString);le.error(`Firestore (${ce}): ${e}`,...s)}}function __PRIVATE_logWarn(e,...i){if(le.logLevel<=f.WARN){const s=i.map(__PRIVATE_argToString);le.warn(`Firestore (${ce}): ${e}`,...s)}}function __PRIVATE_argToString(e){if("string"==typeof e)return e;try{return function __PRIVATE_formatJSON(e){return JSON.stringify(e)}(e)}catch(i){return e}}function fail(e="Unexpected state"){const i=`FIRESTORE (${ce}) INTERNAL ASSERTION FAILED: `+e;throw __PRIVATE_logError(i),new Error(i)}function __PRIVATE_hardAssert(e,i){e||fail()}function __PRIVATE_debugAssert(e,i){e||fail()}function __PRIVATE_debugCast(e,i){return e}const _e={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 FirestoreError extends FirebaseError{constructor(e,i){super(e,i),this.code=e,this.message=i,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __PRIVATE_Deferred{constructor(){this.promise=new Promise(((e,i)=>{this.resolve=e,this.reject=i}))}}class __PRIVATE_OAuthToken{constructor(e,i){this.user=i,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class __PRIVATE_EmptyAuthCredentialsProvider{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,i){e.enqueueRetryable((()=>i(User.UNAUTHENTICATED)))}shutdown(){}}class __PRIVATE_EmulatorAuthCredentialsProvider{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,i){this.changeListener=i,e.enqueueRetryable((()=>i(this.token.user)))}shutdown(){this.changeListener=null}}class __PRIVATE_FirebaseAuthCredentialsProvider{constructor(e){this.t=e,this.currentUser=User.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,i){__PRIVATE_hardAssert(void 0===this.o);let s=this.i;const __PRIVATE_guardedChangeListener=e=>this.i!==s?(s=this.i,i(e)):Promise.resolve();let o=new __PRIVATE_Deferred;this.o=()=>{this.i++,this.currentUser=this.u(),o.resolve(),o=new __PRIVATE_Deferred,e.enqueueRetryable((()=>__PRIVATE_guardedChangeListener(this.currentUser)))};const __PRIVATE_awaitNextToken=()=>{const i=o;e.enqueueRetryable((async()=>{await i.promise,await __PRIVATE_guardedChangeListener(this.currentUser)}))},__PRIVATE_registerAuth=e=>{__PRIVATE_logDebug("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),__PRIVATE_awaitNextToken())};this.t.onInit((e=>__PRIVATE_registerAuth(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?__PRIVATE_registerAuth(e):(__PRIVATE_logDebug("FirebaseAuthCredentialsProvider","Auth not yet detected"),o.resolve(),o=new __PRIVATE_Deferred)}}),0),__PRIVATE_awaitNextToken()}getToken(){const e=this.i,i=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(i).then((i=>this.i!==e?(__PRIVATE_logDebug("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):i?(__PRIVATE_hardAssert("string"==typeof i.accessToken),new __PRIVATE_OAuthToken(i.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return __PRIVATE_hardAssert(null===e||"string"==typeof e),new User(e)}}class __PRIVATE_FirstPartyToken{constructor(e,i,s){this.l=e,this.h=i,this.P=s,this.type="FirstParty",this.user=User.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);const 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 __PRIVATE_FirstPartyAuthCredentialsProvider{constructor(e,i,s){this.l=e,this.h=i,this.P=s}getToken(){return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l,this.h,this.P))}start(e,i){e.enqueueRetryable((()=>i(User.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class AppCheckToken{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class __PRIVATE_FirebaseAppCheckTokenProvider{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,i){__PRIVATE_hardAssert(void 0===this.o);const onTokenChanged=e=>{null!=e.error&&__PRIVATE_logDebug("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const s=e.token!==this.R;return this.R=e.token,__PRIVATE_logDebug("FirebaseAppCheckTokenProvider",`Received ${s?"new":"existing"} token.`),s?i(e.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable((()=>onTokenChanged(i)))};const __PRIVATE_registerAppCheck=e=>{__PRIVATE_logDebug("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>__PRIVATE_registerAppCheck(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?__PRIVATE_registerAppCheck(e):__PRIVATE_logDebug("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.token),this.R=e.token,new AppCheckToken(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class __PRIVATE_EmptyAppCheckTokenProvider{getToken(){return Promise.resolve(new AppCheckToken(""))}invalidateToken(){}start(e,i){}shutdown(){}}function __PRIVATE_randomBytes(e){const i="undefined"!=typeof self&&(self.crypto||self.msCrypto),s=new Uint8Array(e);if(i&&"function"==typeof i.getRandomValues)i.getRandomValues(s);else for(let i=0;i<e;i++)s[i]=Math.floor(256*Math.random());return s}class __PRIVATE_AutoId{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=Math.floor(256/e.length)*e.length;let s="";for(;s.length<20;){const o=__PRIVATE_randomBytes(40);for(let _=0;_<o.length;++_)s.length<20&&o[_]<i&&(s+=e.charAt(o[_]%e.length))}return s}}function __PRIVATE_primitiveComparator(e,i){return e<i?-1:e>i?1:0}function __PRIVATE_arrayEquals(e,i,s){return e.length===i.length&&e.every(((e,o)=>s(e,i[o])))}function __PRIVATE_immediateSuccessor(e){return e+"\0"}class Timestamp{constructor(e,i){if(this.seconds=e,this.nanoseconds=i,i<0)throw new FirestoreError(_e.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+i);if(i>=1e9)throw new FirestoreError(_e.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+i);if(e<-62135596800)throw new FirestoreError(_e.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new FirestoreError(_e.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Timestamp.fromMillis(Date.now())}static fromDate(e){return Timestamp.fromMillis(e.getTime())}static fromMillis(e){const i=Math.floor(e/1e3),s=Math.floor(1e6*(e-1e3*i));return new Timestamp(i,s)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,e.nanoseconds):__PRIVATE_primitiveComparator(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class SnapshotVersion{constructor(e){this.timestamp=e}static fromTimestamp(e){return new SnapshotVersion(e)}static min(){return new SnapshotVersion(new Timestamp(0,0))}static max(){return new SnapshotVersion(new Timestamp(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 BasePath{constructor(e,i,s){void 0===i?i=0:i>e.length&&fail(),void 0===s?s=e.length-i:s>e.length-i&&fail(),this.segments=e,this.offset=i,this.len=s}get length(){return this.len}isEqual(e){return 0===BasePath.comparator(this,e)}child(e){const i=this.segments.slice(this.offset,this.limit());return e instanceof BasePath?e.forEach((e=>{i.push(e)})):i.push(e),this.construct(i)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let i=0;i<this.length;i++)if(this.get(i)!==e.get(i))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let i=0;i<this.length;i++)if(this.get(i)!==e.get(i))return!1;return!0}forEach(e){for(let i=this.offset,s=this.limit();i<s;i++)e(this.segments[i])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,i){const s=Math.min(e.length,i.length);for(let o=0;o<s;o++){const s=e.get(o),_=i.get(o);if(s<_)return-1;if(s>_)return 1}return e.length<i.length?-1:e.length>i.length?1:0}}class ResourcePath extends BasePath{construct(e,i,s){return new ResourcePath(e,i,s)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const i=[];for(const s of e){if(s.indexOf("//")>=0)throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid segment (${s}). Paths must not contain // in them.`);i.push(...s.split("/").filter((e=>e.length>0)))}return new ResourcePath(i)}static emptyPath(){return new ResourcePath([])}}const he=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class FieldPath$1 extends BasePath{construct(e,i,s){return new FieldPath$1(e,i,s)}static isValidIdentifier(e){return he.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),FieldPath$1.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new FieldPath$1(["__name__"])}static fromServerFormat(e){const i=[];let s="",o=0;const __PRIVATE_addCurrentSegment=()=>{if(0===s.length)throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);i.push(s),s=""};let _=!1;for(;o<e.length;){const i=e[o];if("\\"===i){if(o+1===e.length)throw new FirestoreError(_e.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const i=e[o+1];if("\\"!==i&&"."!==i&&"`"!==i)throw new FirestoreError(_e.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);s+=i,o+=2}else"`"===i?(_=!_,o++):"."!==i||_?(s+=i,o++):(__PRIVATE_addCurrentSegment(),o++)}if(__PRIVATE_addCurrentSegment(),_)throw new FirestoreError(_e.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new FieldPath$1(i)}static emptyPath(){return new FieldPath$1([])}}class DocumentKey{constructor(e){this.path=e}static fromPath(e){return new DocumentKey(ResourcePath.fromString(e))}static fromName(e){return new DocumentKey(ResourcePath.fromString(e).popFirst(5))}static empty(){return new DocumentKey(ResourcePath.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ResourcePath.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,i){return ResourcePath.comparator(e.path,i.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new DocumentKey(new ResourcePath(e.slice()))}}class FieldIndex{constructor(e,i,s,o){this.indexId=e,this.collectionGroup=i,this.fields=s,this.indexState=o}}function __PRIVATE_fieldIndexGetArraySegment(e){return e.fields.find((e=>2===e.kind))}function __PRIVATE_fieldIndexGetDirectionalSegments(e){return e.fields.filter((e=>2!==e.kind))}function __PRIVATE_fieldIndexSemanticComparator(e,i){let s=__PRIVATE_primitiveComparator(e.collectionGroup,i.collectionGroup);if(0!==s)return s;for(let o=0;o<Math.min(e.fields.length,i.fields.length);++o)if(s=__PRIVATE_indexSegmentComparator(e.fields[o],i.fields[o]),0!==s)return s;return __PRIVATE_primitiveComparator(e.fields.length,i.fields.length)}FieldIndex.UNKNOWN_ID=-1;class IndexSegment{constructor(e,i){this.fieldPath=e,this.kind=i}}function __PRIVATE_indexSegmentComparator(e,i){const s=FieldPath$1.comparator(e.fieldPath,i.fieldPath);return 0!==s?s:__PRIVATE_primitiveComparator(e.kind,i.kind)}class IndexState{constructor(e,i){this.sequenceNumber=e,this.offset=i}static empty(){return new IndexState(0,IndexOffset.min())}}function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e,i){const s=e.toTimestamp().seconds,o=e.toTimestamp().nanoseconds+1,_=SnapshotVersion.fromTimestamp(1e9===o?new Timestamp(s+1,0):new Timestamp(s,o));return new IndexOffset(_,DocumentKey.empty(),i)}function __PRIVATE_newIndexOffsetFromDocument(e){return new IndexOffset(e.readTime,e.key,-1)}class IndexOffset{constructor(e,i,s){this.readTime=e,this.documentKey=i,this.largestBatchId=s}static min(){return new IndexOffset(SnapshotVersion.min(),DocumentKey.empty(),-1)}static max(){return new IndexOffset(SnapshotVersion.max(),DocumentKey.empty(),-1)}}function __PRIVATE_indexOffsetComparator(e,i){let s=e.readTime.compareTo(i.readTime);return 0!==s?s:(s=DocumentKey.comparator(e.documentKey,i.documentKey),0!==s?s:__PRIVATE_primitiveComparator(e.largestBatchId,i.largestBatchId))}const de="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class PersistenceTransaction{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e){if(e.code!==_e.FAILED_PRECONDITION||e.message!==de)throw e;__PRIVATE_logDebug("LocalStore","Unexpectedly lost primary lease")}class PersistencePromise{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(e,i){return this.callbackAttached&&fail(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(e,this.result):new PersistencePromise(((s,o)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(s,o)},this.catchCallback=e=>{this.wrapFailure(i,e).next(s,o)}}))}toPromise(){return new Promise(((e,i)=>{this.next(e,i)}))}wrapUserFunction(e){try{const i=e();return i instanceof PersistencePromise?i:PersistencePromise.resolve(i)}catch(e){return PersistencePromise.reject(e)}}wrapSuccess(e,i){return e?this.wrapUserFunction((()=>e(i))):PersistencePromise.resolve(i)}wrapFailure(e,i){return e?this.wrapUserFunction((()=>e(i))):PersistencePromise.reject(i)}static resolve(e){return new PersistencePromise(((i,s)=>{i(e)}))}static reject(e){return new PersistencePromise(((i,s)=>{s(e)}))}static waitFor(e){return new PersistencePromise(((i,s)=>{let o=0,_=0,h=!1;e.forEach((e=>{++o,e.next((()=>{++_,h&&_===o&&i()}),(e=>s(e)))})),h=!0,_===o&&i()}))}static or(e){let i=PersistencePromise.resolve(!1);for(const s of e)i=i.next((e=>e?PersistencePromise.resolve(e):s()));return i}static forEach(e,i){const s=[];return e.forEach(((e,o)=>{s.push(i.call(this,e,o))})),this.waitFor(s)}static mapArray(e,i){return new PersistencePromise(((s,o)=>{const _=e.length,h=new Array(_);let d=0;for(let f=0;f<_;f++){const g=f;i(e[g]).next((e=>{h[g]=e,++d,d===_&&s(h)}),(e=>o(e)))}}))}static doWhile(e,i){return new PersistencePromise(((s,o)=>{const process=()=>{!0===e()?i().next((()=>{process()}),o):s()};process()}))}}class __PRIVATE_SimpleDbTransaction{constructor(e,i){this.action=e,this.transaction=i,this.aborted=!1,this.V=new __PRIVATE_Deferred,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{i.error?this.V.reject(new __PRIVATE_IndexedDbTransactionError(e,i.error)):this.V.resolve()},this.transaction.onerror=i=>{const s=__PRIVATE_checkForAndReportiOSError(i.target.error);this.V.reject(new __PRIVATE_IndexedDbTransactionError(e,s))}}static open(e,i,s,o){try{return new __PRIVATE_SimpleDbTransaction(i,e.transaction(o,s))}catch(e){throw new __PRIVATE_IndexedDbTransactionError(i,e)}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(__PRIVATE_logDebug("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){const i=this.transaction.objectStore(e);return new __PRIVATE_SimpleDbStore(i)}}class __PRIVATE_SimpleDb{constructor(e,i,s){this.name=e,this.version=i,this.p=s,12.2===__PRIVATE_SimpleDb.S(getUA())&&__PRIVATE_logError("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 __PRIVATE_logDebug("SimpleDb","Removing database:",e),__PRIVATE_wrapRequest(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}())return!1;if(__PRIVATE_SimpleDb.v())return!0;const e=getUA(),i=__PRIVATE_SimpleDb.S(e),s=0<i&&i<10,o=__PRIVATE_getAndroidVersion(e),_=0<o&&o<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||s||_)}static v(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.__PRIVATE_env)||void 0===e?void 0:e.C)}static F(e,i){return e.store(i)}static S(e){const i=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),s=i?i[1].split("_").slice(0,2).join("."):"-1";return Number(s)}async M(e){return this.db||(__PRIVATE_logDebug("SimpleDb","Opening database:",this.name),this.db=await new Promise(((i,s)=>{const o=indexedDB.open(this.name,this.version);o.onsuccess=e=>{const s=e.target.result;i(s)},o.onblocked=()=>{s(new __PRIVATE_IndexedDbTransactionError(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},o.onerror=i=>{const o=i.target.error;"VersionError"===o.name?s(new FirestoreError(_e.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"===o.name?s(new FirestoreError(_e.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: "+o)):s(new __PRIVATE_IndexedDbTransactionError(e,o))},o.onupgradeneeded=e=>{__PRIVATE_logDebug("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);const i=e.target.result;this.p.O(i,o.transaction,e.oldVersion,this.version).next((()=>{__PRIVATE_logDebug("SimpleDb","Database upgrade to version "+this.version+" complete")}))}}))),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(e){this.N=e,this.db&&(this.db.onversionchange=i=>e(i))}async runTransaction(e,i,s,o){const _="readonly"===i;let h=0;for(;;){++h;try{this.db=await this.M(e);const i=__PRIVATE_SimpleDbTransaction.open(this.db,e,_?"readonly":"readwrite",s),h=o(i).next((e=>(i.g(),e))).catch((e=>(i.abort(e),PersistencePromise.reject(e)))).toPromise();return h.catch((()=>{})),await i.m,h}catch(e){const i=e,s="FirebaseError"!==i.name&&h<3;if(__PRIVATE_logDebug("SimpleDb","Transaction failed with error:",i.message,"Retrying:",s),this.close(),!s)return Promise.reject(i)}}}close(){this.db&&this.db.close(),this.db=void 0}}function __PRIVATE_getAndroidVersion(e){const i=e.match(/Android ([\d.]+)/i),s=i?i[1].split(".").slice(0,2).join("."):"-1";return Number(s)}class __PRIVATE_IterationController{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 __PRIVATE_wrapRequest(this.B.delete())}}class __PRIVATE_IndexedDbTransactionError extends FirestoreError{constructor(e,i){super(_e.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${i}`),this.name="IndexedDbTransactionError"}}function __PRIVATE_isIndexedDbTransactionError(e){return"IndexedDbTransactionError"===e.name}class __PRIVATE_SimpleDbStore{constructor(e){this.store=e}put(e,i){let s;return void 0!==i?(__PRIVATE_logDebug("SimpleDb","PUT",this.store.name,e,i),s=this.store.put(i,e)):(__PRIVATE_logDebug("SimpleDb","PUT",this.store.name,"<auto-key>",e),s=this.store.put(e)),__PRIVATE_wrapRequest(s)}add(e){return __PRIVATE_logDebug("SimpleDb","ADD",this.store.name,e,e),__PRIVATE_wrapRequest(this.store.add(e))}get(e){return __PRIVATE_wrapRequest(this.store.get(e)).next((i=>(void 0===i&&(i=null),__PRIVATE_logDebug("SimpleDb","GET",this.store.name,e,i),i)))}delete(e){return __PRIVATE_logDebug("SimpleDb","DELETE",this.store.name,e),__PRIVATE_wrapRequest(this.store.delete(e))}count(){return __PRIVATE_logDebug("SimpleDb","COUNT",this.store.name),__PRIVATE_wrapRequest(this.store.count())}U(e,i){const s=this.options(e,i),o=s.index?this.store.index(s.index):this.store;if("function"==typeof o.getAll){const e=o.getAll(s.range);return new PersistencePromise(((i,s)=>{e.onerror=e=>{s(e.target.error)},e.onsuccess=e=>{i(e.target.result)}}))}{const e=this.cursor(s),i=[];return this.W(e,((e,s)=>{i.push(s)})).next((()=>i))}}G(e,i){const s=this.store.getAll(e,null===i?void 0:i);return new PersistencePromise(((e,i)=>{s.onerror=e=>{i(e.target.error)},s.onsuccess=i=>{e(i.target.result)}}))}j(e,i){__PRIVATE_logDebug("SimpleDb","DELETE ALL",this.store.name);const s=this.options(e,i);s.H=!1;const o=this.cursor(s);return this.W(o,((e,i,s)=>s.delete()))}J(e,i){let s;i?s=e:(s={},i=e);const o=this.cursor(s);return this.W(o,i)}Y(e){const i=this.cursor({});return new PersistencePromise(((s,o)=>{i.onerror=e=>{const i=__PRIVATE_checkForAndReportiOSError(e.target.error);o(i)},i.onsuccess=i=>{const o=i.target.result;o?e(o.primaryKey,o.value).next((e=>{e?o.continue():s()})):s()}}))}W(e,i){const s=[];return new PersistencePromise(((o,_)=>{e.onerror=e=>{_(e.target.error)},e.onsuccess=e=>{const _=e.target.result;if(!_)return void o();const h=new __PRIVATE_IterationController(_),d=i(_.primaryKey,_.value,h);if(d instanceof PersistencePromise){const e=d.catch((e=>(h.done(),PersistencePromise.reject(e))));s.push(e)}h.isDone?o():null===h.K?_.continue():_.continue(h.K)}})).next((()=>PersistencePromise.waitFor(s)))}options(e,i){let s;return void 0!==e&&("string"==typeof e?s=e:i=e),{index:s,range:i}}cursor(e){let i="next";if(e.reverse&&(i="prev"),e.index){const s=this.store.index(e.index);return e.H?s.openKeyCursor(e.range,i):s.openCursor(e.range,i)}return this.store.openCursor(e.range,i)}}function __PRIVATE_wrapRequest(e){return new PersistencePromise(((i,s)=>{e.onsuccess=e=>{const s=e.target.result;i(s)},e.onerror=e=>{const i=__PRIVATE_checkForAndReportiOSError(e.target.error);s(i)}}))}let me=!1;function __PRIVATE_checkForAndReportiOSError(e){const i=__PRIVATE_SimpleDb.S(getUA());if(i>=12.2&&i<13){const i="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(i)>=0){const e=new FirestoreError("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${i}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return me||(me=!0,setTimeout((()=>{throw e}),0)),e}}return e}class __PRIVATE_IndexBackfillerScheduler{constructor(e,i){this.asyncQueue=e,this.Z=i,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){__PRIVATE_logDebug("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{__PRIVATE_logDebug("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){__PRIVATE_isIndexedDbTransactionError(e)?__PRIVATE_logDebug("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}await this.X(6e4)}))}}class __PRIVATE_IndexBackfiller{constructor(e,i){this.localStore=e,this.persistence=i}async ee(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",(i=>this.te(i,e)))}te(e,i){const s=new Set;let o=i,_=!0;return PersistencePromise.doWhile((()=>!0===_&&o>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((i=>{if(null!==i&&!s.has(i))return __PRIVATE_logDebug("IndexBackfiller",`Processing collection: ${i}`),this.ne(e,i,o).next((e=>{o-=e,s.add(i)}));_=!1})))).next((()=>i-o))}ne(e,i,s){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,i).next((o=>this.localStore.localDocuments.getNextDocuments(e,i,o,s).next((s=>{const _=s.changes;return this.localStore.indexManager.updateIndexEntries(e,_).next((()=>this.re(o,s))).next((s=>(__PRIVATE_logDebug("IndexBackfiller",`Updating offset: ${s}`),this.localStore.indexManager.updateCollectionGroup(e,i,s)))).next((()=>_.size))}))))}re(e,i){let s=e;return i.changes.forEach(((e,i)=>{const o=__PRIVATE_newIndexOffsetFromDocument(i);__PRIVATE_indexOffsetComparator(o,s)>0&&(s=o)})),new IndexOffset(s.readTime,s.documentKey,Math.max(i.batchId,e.largestBatchId))}}class __PRIVATE_ListenSequence{constructor(e,i){this.previousValue=e,i&&(i.sequenceNumberHandler=e=>this.ie(e),this.se=e=>i.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.se&&this.se(e),e}}function __PRIVATE_isNullOrUndefined(e){return null==e}function __PRIVATE_isNegativeZero(e){return 0===e&&1/e==-1/0}function isSafeInteger(e){return"number"==typeof e&&Number.isInteger(e)&&!__PRIVATE_isNegativeZero(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function __PRIVATE_encodeResourcePath(e){let i="";for(let s=0;s<e.length;s++)i.length>0&&(i=__PRIVATE_encodeSeparator(i)),i=__PRIVATE_encodeSegment(e.get(s),i);return __PRIVATE_encodeSeparator(i)}function __PRIVATE_encodeSegment(e,i){let s=i;const o=e.length;for(let i=0;i<o;i++){const o=e.charAt(i);switch(o){case"\0":s+="";break;case"":s+="";break;default:s+=o}}return s}function __PRIVATE_encodeSeparator(e){return e+""}function __PRIVATE_decodeResourcePath(e){const i=e.length;if(__PRIVATE_hardAssert(i>=2),2===i)return __PRIVATE_hardAssert(""===e.charAt(0)&&""===e.charAt(1)),ResourcePath.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=i-2,s=[];let o="";for(let _=0;_<i;){const i=e.indexOf("",_);switch((i<0||i>__PRIVATE_lastReasonableEscapeIndex)&&fail(),e.charAt(i+1)){case"":const h=e.substring(_,i);let d;0===o.length?d=h:(o+=h,d=o,o=""),s.push(d);break;case"":o+=e.substring(_,i),o+="\0";break;case"":o+=e.substring(_,i+1);break;default:fail()}_=i+2}return new ResourcePath(s)}__PRIVATE_ListenSequence.oe=-1;const fe=["userId","batchId"];function __PRIVATE_newDbDocumentMutationPrefixForPath(e,i){return[e,__PRIVATE_encodeResourcePath(i)]}function __PRIVATE_newDbDocumentMutationKey(e,i,s){return[e,__PRIVATE_encodeResourcePath(i),s]}const ge={},Ie=["prefixPath","collectionGroup","readTime","documentId"],Te=["prefixPath","collectionGroup","documentId"],pe=["collectionGroup","readTime","prefixPath","documentId"],Ee=["canonicalId","targetId"],Pe=["targetId","path"],Ae=["path","targetId"],Re=["collectionId","parent"],ye=["indexId","uid"],Ve=["uid","sequenceNumber"],ve=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],be=["indexId","uid","orderedDocumentKey"],Se=["userId","collectionPath","documentId"],we=["userId","collectionPath","largestBatchId"],De=["userId","collectionGroup","largestBatchId"],Ce=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],Fe=[...Ce,"documentOverlays"],xe=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Me=xe,Ne=[...Me,"indexConfiguration","indexState","indexEntries"],ke=Ne,Oe=[...Ne,"globals"];class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction{constructor(e,i){super(),this._e=e,this.currentSequenceNumber=i}}function __PRIVATE_getStore(e,i){const s=__PRIVATE_debugCast(e);return __PRIVATE_SimpleDb.F(s._e,i)}function __PRIVATE_objectSize(e){let i=0;for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i++;return i}function forEach(e,i){for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i(s,e[s])}function __PRIVATE_mapToArray(e,i){const s=[];for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&s.push(i(e[o],o,e));return s}function isEmpty(e){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i))return!1;return!0}class SortedMap{constructor(e,i){this.comparator=e,this.root=i||LLRBNode.EMPTY}insert(e,i){return new SortedMap(this.comparator,this.root.insert(e,i,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator,this.root.remove(e,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let i=this.root;for(;!i.isEmpty();){const s=this.comparator(e,i.key);if(0===s)return i.value;s<0?i=i.left:s>0&&(i=i.right)}return null}indexOf(e){let i=0,s=this.root;for(;!s.isEmpty();){const o=this.comparator(e,s.key);if(0===o)return i+s.left.size;o<0?s=s.left:(i+=s.left.size+1,s=s.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((i,s)=>(e(i,s),!1)))}toString(){const e=[];return this.inorderTraversal(((i,s)=>(e.push(`${i}:${s}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new SortedMapIterator(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!1)}getReverseIterator(){return new SortedMapIterator(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!0)}}class SortedMapIterator{constructor(e,i,s,o){this.isReverse=o,this.nodeStack=[];let _=1;for(;!e.isEmpty();)if(_=i?s(e.key,i):1,i&&o&&(_*=-1),_<0)e=this.isReverse?e.left:e.right;else{if(0===_){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const i={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 i}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class LLRBNode{constructor(e,i,s,o,_){this.key=e,this.value=i,this.color=null!=s?s:LLRBNode.RED,this.left=null!=o?o:LLRBNode.EMPTY,this.right=null!=_?_:LLRBNode.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,i,s,o,_){return new LLRBNode(null!=e?e:this.key,null!=i?i:this.value,null!=s?s:this.color,null!=o?o:this.left,null!=_?_: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,i,s){let o=this;const _=s(e,o.key);return o=_<0?o.copy(null,null,null,o.left.insert(e,i,s),null):0===_?o.copy(null,i,null,null,null):o.copy(null,null,null,null,o.right.insert(e,i,s)),o.fixUp()}removeMin(){if(this.left.isEmpty())return LLRBNode.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,i){let s,o=this;if(i(e,o.key)<0)o.left.isEmpty()||o.left.isRed()||o.left.left.isRed()||(o=o.moveRedLeft()),o=o.copy(null,null,null,o.left.remove(e,i),null);else{if(o.left.isRed()&&(o=o.rotateRight()),o.right.isEmpty()||o.right.isRed()||o.right.left.isRed()||(o=o.moveRedRight()),0===i(e,o.key)){if(o.right.isEmpty())return LLRBNode.EMPTY;s=o.right.min(),o=o.copy(s.key,s.value,null,null,o.right.removeMin())}o=o.copy(null,null,null,null,o.right.remove(e,i))}return o.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),i=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,i)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw fail();if(this.right.isRed())throw fail();const e=this.left.check();if(e!==this.right.check())throw fail();return e+(this.isRed()?0:1)}}LLRBNode.EMPTY=null,LLRBNode.RED=!0,LLRBNode.BLACK=!1,LLRBNode.EMPTY=new class LLRBEmptyNode{constructor(){this.size=0}get key(){throw fail()}get value(){throw fail()}get color(){throw fail()}get left(){throw fail()}get right(){throw fail()}copy(e,i,s,o,_){return this}insert(e,i,s){return new LLRBNode(e,i)}remove(e,i){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 SortedSet{constructor(e){this.comparator=e,this.data=new SortedMap(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((i,s)=>(e(i),!1)))}forEachInRange(e,i){const s=this.data.getIteratorFrom(e[0]);for(;s.hasNext();){const o=s.getNext();if(this.comparator(o.key,e[1])>=0)return;i(o.key)}}forEachWhile(e,i){let s;for(s=void 0!==i?this.data.getIteratorFrom(i):this.data.getIterator();s.hasNext();)if(!e(s.getNext().key))return}firstAfterOrEqual(e){const i=this.data.getIteratorFrom(e);return i.hasNext()?i.getNext().key:null}getIterator(){return new SortedSetIterator(this.data.getIterator())}getIteratorFrom(e){return new SortedSetIterator(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 i=this;return i.size<e.size&&(i=e,e=this),e.forEach((e=>{i=i.add(e)})),i}isEqual(e){if(!(e instanceof SortedSet))return!1;if(this.size!==e.size)return!1;const i=this.data.getIterator(),s=e.data.getIterator();for(;i.hasNext();){const e=i.getNext().key,o=s.getNext().key;if(0!==this.comparator(e,o))return!1}return!0}toArray(){const e=[];return this.forEach((i=>{e.push(i)})),e}toString(){const e=[];return this.forEach((i=>e.push(i))),"SortedSet("+e.toString()+")"}copy(e){const i=new SortedSet(this.comparator);return i.data=e,i}}class SortedSetIterator{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function __PRIVATE_advanceIterator(e){return e.hasNext()?e.getNext():void 0}class FieldMask{constructor(e){this.fields=e,e.sort(FieldPath$1.comparator)}static empty(){return new FieldMask([])}unionWith(e){let i=new SortedSet(FieldPath$1.comparator);for(const e of this.fields)i=i.add(e);for(const s of e)i=i.add(s);return new FieldMask(i.toArray())}covers(e){for(const i of this.fields)if(i.isPrefixOf(e))return!0;return!1}isEqual(e){return __PRIVATE_arrayEquals(this.fields,e.fields,((e,i)=>e.isEqual(i)))}}class __PRIVATE_Base64DecodeError extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}function __PRIVATE_isBase64Available(){return"undefined"!=typeof atob}class ByteString{constructor(e){this.binaryString=e}static fromBase64String(e){const i=function __PRIVATE_decodeBase64(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new __PRIVATE_Base64DecodeError("Invalid base64 string: "+e):e}}(e);return new ByteString(i)}static fromUint8Array(e){const i=function __PRIVATE_binaryStringFromUint8Array(e){let i="";for(let s=0;s<e.length;++s)i+=String.fromCharCode(e[s]);return i}(e);return new ByteString(i)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return function __PRIVATE_encodeBase64(e){return btoa(e)}(this.binaryString)}toUint8Array(){return function __PRIVATE_uint8ArrayFromBinaryString(e){const i=new Uint8Array(e.length);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return __PRIVATE_primitiveComparator(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ByteString.EMPTY_BYTE_STRING=new ByteString("");const Le=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function __PRIVATE_normalizeTimestamp(e){if(__PRIVATE_hardAssert(!!e),"string"==typeof e){let i=0;const s=Le.exec(e);if(__PRIVATE_hardAssert(!!s),s[1]){let e=s[1];e=(e+"000000000").substr(0,9),i=Number(e)}const o=new Date(e);return{seconds:Math.floor(o.getTime()/1e3),nanos:i}}return{seconds:__PRIVATE_normalizeNumber(e.seconds),nanos:__PRIVATE_normalizeNumber(e.nanos)}}function __PRIVATE_normalizeNumber(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function __PRIVATE_normalizeByteString(e){return"string"==typeof e?ByteString.fromBase64String(e):ByteString.fromUint8Array(e)}function __PRIVATE_isServerTimestamp(e){var i,s;return"server_timestamp"===(null===(s=((null===(i=null==e?void 0:e.mapValue)||void 0===i?void 0:i.fields)||{}).__type__)||void 0===s?void 0:s.stringValue)}function __PRIVATE_getPreviousValue(e){const i=e.mapValue.fields.__previous_value__;return __PRIVATE_isServerTimestamp(i)?__PRIVATE_getPreviousValue(i):i}function __PRIVATE_getLocalWriteTime(e){const i=__PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);return new Timestamp(i.seconds,i.nanos)}class DatabaseInfo{constructor(e,i,s,o,_,h,d,f,g){this.databaseId=e,this.appId=i,this.persistenceKey=s,this.host=o,this.ssl=_,this.forceLongPolling=h,this.autoDetectLongPolling=d,this.longPollingOptions=f,this.useFetchStreams=g}}class DatabaseId{constructor(e,i){this.projectId=e,this.database=i||"(default)"}static empty(){return new DatabaseId("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof DatabaseId&&e.projectId===this.projectId&&e.database===this.database}}const Be={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},qe={nullValue:"NULL_VALUE"};function __PRIVATE_typeOrder(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?__PRIVATE_isServerTimestamp(e)?4:__PRIVATE_isMaxValue(e)?9007199254740991:__PRIVATE_isVectorValue(e)?10:11:fail()}function __PRIVATE_valueEquals(e,i){if(e===i)return!0;const s=__PRIVATE_typeOrder(e);if(s!==__PRIVATE_typeOrder(i))return!1;switch(s){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===i.booleanValue;case 4:return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(i));case 3:return function __PRIVATE_timestampEquals(e,i){if("string"==typeof e.timestampValue&&"string"==typeof i.timestampValue&&e.timestampValue.length===i.timestampValue.length)return e.timestampValue===i.timestampValue;const s=__PRIVATE_normalizeTimestamp(e.timestampValue),o=__PRIVATE_normalizeTimestamp(i.timestampValue);return s.seconds===o.seconds&&s.nanos===o.nanos}(e,i);case 5:return e.stringValue===i.stringValue;case 6:return function __PRIVATE_blobEquals(e,i){return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(i.bytesValue))}(e,i);case 7:return e.referenceValue===i.referenceValue;case 8:return function __PRIVATE_geoPointEquals(e,i){return __PRIVATE_normalizeNumber(e.geoPointValue.latitude)===__PRIVATE_normalizeNumber(i.geoPointValue.latitude)&&__PRIVATE_normalizeNumber(e.geoPointValue.longitude)===__PRIVATE_normalizeNumber(i.geoPointValue.longitude)}(e,i);case 2:return function __PRIVATE_numberEquals(e,i){if("integerValue"in e&&"integerValue"in i)return __PRIVATE_normalizeNumber(e.integerValue)===__PRIVATE_normalizeNumber(i.integerValue);if("doubleValue"in e&&"doubleValue"in i){const s=__PRIVATE_normalizeNumber(e.doubleValue),o=__PRIVATE_normalizeNumber(i.doubleValue);return s===o?__PRIVATE_isNegativeZero(s)===__PRIVATE_isNegativeZero(o):isNaN(s)&&isNaN(o)}return!1}(e,i);case 9:return __PRIVATE_arrayEquals(e.arrayValue.values||[],i.arrayValue.values||[],__PRIVATE_valueEquals);case 10:case 11:return function __PRIVATE_objectEquals(e,i){const s=e.mapValue.fields||{},o=i.mapValue.fields||{};if(__PRIVATE_objectSize(s)!==__PRIVATE_objectSize(o))return!1;for(const e in s)if(s.hasOwnProperty(e)&&(void 0===o[e]||!__PRIVATE_valueEquals(s[e],o[e])))return!1;return!0}(e,i);default:return fail()}}function __PRIVATE_arrayValueContains(e,i){return void 0!==(e.values||[]).find((e=>__PRIVATE_valueEquals(e,i)))}function __PRIVATE_valueCompare(e,i){if(e===i)return 0;const s=__PRIVATE_typeOrder(e),o=__PRIVATE_typeOrder(i);if(s!==o)return __PRIVATE_primitiveComparator(s,o);switch(s){case 0:case 9007199254740991:return 0;case 1:return __PRIVATE_primitiveComparator(e.booleanValue,i.booleanValue);case 2:return function __PRIVATE_compareNumbers(e,i){const s=__PRIVATE_normalizeNumber(e.integerValue||e.doubleValue),o=__PRIVATE_normalizeNumber(i.integerValue||i.doubleValue);return s<o?-1:s>o?1:s===o?0:isNaN(s)?isNaN(o)?0:-1:1}(e,i);case 3:return __PRIVATE_compareTimestamps(e.timestampValue,i.timestampValue);case 4:return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e),__PRIVATE_getLocalWriteTime(i));case 5:return __PRIVATE_primitiveComparator(e.stringValue,i.stringValue);case 6:return function __PRIVATE_compareBlobs(e,i){const s=__PRIVATE_normalizeByteString(e),o=__PRIVATE_normalizeByteString(i);return s.compareTo(o)}(e.bytesValue,i.bytesValue);case 7:return function __PRIVATE_compareReferences(e,i){const s=e.split("/"),o=i.split("/");for(let e=0;e<s.length&&e<o.length;e++){const i=__PRIVATE_primitiveComparator(s[e],o[e]);if(0!==i)return i}return __PRIVATE_primitiveComparator(s.length,o.length)}(e.referenceValue,i.referenceValue);case 8:return function __PRIVATE_compareGeoPoints(e,i){const s=__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(i.latitude));return 0!==s?s:__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude),__PRIVATE_normalizeNumber(i.longitude))}(e.geoPointValue,i.geoPointValue);case 9:return __PRIVATE_compareArrays(e.arrayValue,i.arrayValue);case 10:return function __PRIVATE_compareVectors(e,i){var s,o,_,h;const d=e.fields||{},f=i.fields||{},g=null===(s=d.value)||void 0===s?void 0:s.arrayValue,b=null===(o=f.value)||void 0===o?void 0:o.arrayValue,w=__PRIVATE_primitiveComparator((null===(_=null==g?void 0:g.values)||void 0===_?void 0:_.length)||0,(null===(h=null==b?void 0:b.values)||void 0===h?void 0:h.length)||0);return 0!==w?w:__PRIVATE_compareArrays(g,b)}(e.mapValue,i.mapValue);case 11:return function __PRIVATE_compareMaps(e,i){if(e===Be.mapValue&&i===Be.mapValue)return 0;if(e===Be.mapValue)return 1;if(i===Be.mapValue)return-1;const s=e.fields||{},o=Object.keys(s),_=i.fields||{},h=Object.keys(_);o.sort(),h.sort();for(let e=0;e<o.length&&e<h.length;++e){const i=__PRIVATE_primitiveComparator(o[e],h[e]);if(0!==i)return i;const d=__PRIVATE_valueCompare(s[o[e]],_[h[e]]);if(0!==d)return d}return __PRIVATE_primitiveComparator(o.length,h.length)}(e.mapValue,i.mapValue);default:throw fail()}}function __PRIVATE_compareTimestamps(e,i){if("string"==typeof e&&"string"==typeof i&&e.length===i.length)return __PRIVATE_primitiveComparator(e,i);const s=__PRIVATE_normalizeTimestamp(e),o=__PRIVATE_normalizeTimestamp(i),_=__PRIVATE_primitiveComparator(s.seconds,o.seconds);return 0!==_?_:__PRIVATE_primitiveComparator(s.nanos,o.nanos)}function __PRIVATE_compareArrays(e,i){const s=e.values||[],o=i.values||[];for(let e=0;e<s.length&&e<o.length;++e){const i=__PRIVATE_valueCompare(s[e],o[e]);if(i)return i}return __PRIVATE_primitiveComparator(s.length,o.length)}function canonicalId(e){return __PRIVATE_canonifyValue(e)}function __PRIVATE_canonifyValue(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 __PRIVATE_canonifyTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return`time(${i.seconds},${i.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function __PRIVATE_canonifyByteString(e){return __PRIVATE_normalizeByteString(e).toBase64()}(e.bytesValue):"referenceValue"in e?function __PRIVATE_canonifyReference(e){return DocumentKey.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function __PRIVATE_canonifyGeoPoint(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function __PRIVATE_canonifyArray(e){let i="[",s=!0;for(const o of e.values||[])s?s=!1:i+=",",i+=__PRIVATE_canonifyValue(o);return i+"]"}(e.arrayValue):"mapValue"in e?function __PRIVATE_canonifyMap(e){const i=Object.keys(e.fields||{}).sort();let s="{",o=!0;for(const _ of i)o?o=!1:s+=",",s+=`${_}:${__PRIVATE_canonifyValue(e.fields[_])}`;return s+"}"}(e.mapValue):fail()}function __PRIVATE_estimateByteSize(e){switch(__PRIVATE_typeOrder(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const i=__PRIVATE_getPreviousValue(e);return i?16+__PRIVATE_estimateByteSize(i):16;case 5:return 2*e.stringValue.length;case 6:return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize();case 7:return e.referenceValue.length;case 9:return function __PRIVATE_estimateArrayByteSize(e){return(e.values||[]).reduce(((e,i)=>e+__PRIVATE_estimateByteSize(i)),0)}(e.arrayValue);case 10:case 11:return function __PRIVATE_estimateMapByteSize(e){let i=0;return forEach(e.fields,((e,s)=>{i+=e.length+__PRIVATE_estimateByteSize(s)})),i}(e.mapValue);default:throw fail()}}function __PRIVATE_refValue(e,i){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${i.path.canonicalString()}`}}function isInteger(e){return!!e&&"integerValue"in e}function isArray(e){return!!e&&"arrayValue"in e}function __PRIVATE_isNullValue(e){return!!e&&"nullValue"in e}function __PRIVATE_isNanValue(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function __PRIVATE_isMapValue(e){return!!e&&"mapValue"in e}function __PRIVATE_isVectorValue(e){var i,s;return"__vector__"===(null===(s=((null===(i=null==e?void 0:e.mapValue)||void 0===i?void 0:i.fields)||{}).__type__)||void 0===s?void 0:s.stringValue)}function __PRIVATE_deepClone(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const i={mapValue:{fields:{}}};return forEach(e.mapValue.fields,((e,s)=>i.mapValue.fields[e]=__PRIVATE_deepClone(s))),i}if(e.arrayValue){const i={arrayValue:{values:[]}};for(let s=0;s<(e.arrayValue.values||[]).length;++s)i.arrayValue.values[s]=__PRIVATE_deepClone(e.arrayValue.values[s]);return i}return Object.assign({},e)}function __PRIVATE_isMaxValue(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}const Ue={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function __PRIVATE_valuesGetLowerBound(e){return"nullValue"in e?qe:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?__PRIVATE_refValue(DatabaseId.empty(),DocumentKey.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?__PRIVATE_isVectorValue(e)?Ue:{mapValue:{}}:fail()}function __PRIVATE_valuesGetUpperBound(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?__PRIVATE_refValue(DatabaseId.empty(),DocumentKey.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?Ue:"mapValue"in e?__PRIVATE_isVectorValue(e)?{mapValue:{}}:Be:fail()}function __PRIVATE_lowerBoundCompare(e,i){const s=__PRIVATE_valueCompare(e.value,i.value);return 0!==s?s:e.inclusive&&!i.inclusive?-1:!e.inclusive&&i.inclusive?1:0}function __PRIVATE_upperBoundCompare(e,i){const s=__PRIVATE_valueCompare(e.value,i.value);return 0!==s?s:e.inclusive&&!i.inclusive?1:!e.inclusive&&i.inclusive?-1:0}class ObjectValue{constructor(e){this.value=e}static empty(){return new ObjectValue({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let i=this.value;for(let s=0;s<e.length-1;++s)if(i=(i.mapValue.fields||{})[e.get(s)],!__PRIVATE_isMapValue(i))return null;return i=(i.mapValue.fields||{})[e.lastSegment()],i||null}}set(e,i){this.getFieldsMap(e.popLast())[e.lastSegment()]=__PRIVATE_deepClone(i)}setAll(e){let i=FieldPath$1.emptyPath(),s={},o=[];e.forEach(((e,_)=>{if(!i.isImmediateParentOf(_)){const e=this.getFieldsMap(i);this.applyChanges(e,s,o),s={},o=[],i=_.popLast()}e?s[_.lastSegment()]=__PRIVATE_deepClone(e):o.push(_.lastSegment())}));const _=this.getFieldsMap(i);this.applyChanges(_,s,o)}delete(e){const i=this.field(e.popLast());__PRIVATE_isMapValue(i)&&i.mapValue.fields&&delete i.mapValue.fields[e.lastSegment()]}isEqual(e){return __PRIVATE_valueEquals(this.value,e.value)}getFieldsMap(e){let i=this.value;i.mapValue.fields||(i.mapValue={fields:{}});for(let s=0;s<e.length;++s){let o=i.mapValue.fields[e.get(s)];__PRIVATE_isMapValue(o)&&o.mapValue.fields||(o={mapValue:{fields:{}}},i.mapValue.fields[e.get(s)]=o),i=o}return i.mapValue.fields}applyChanges(e,i,s){forEach(i,((i,s)=>e[i]=s));for(const i of s)delete e[i]}clone(){return new ObjectValue(__PRIVATE_deepClone(this.value))}}function __PRIVATE_extractFieldMask(e){const i=[];return forEach(e.fields,((e,s)=>{const o=new FieldPath$1([e]);if(__PRIVATE_isMapValue(s)){const e=__PRIVATE_extractFieldMask(s.mapValue).fields;if(0===e.length)i.push(o);else for(const s of e)i.push(o.child(s))}else i.push(o)})),new FieldMask(i)}class MutableDocument{constructor(e,i,s,o,_,h,d){this.key=e,this.documentType=i,this.version=s,this.readTime=o,this.createTime=_,this.data=h,this.documentState=d}static newInvalidDocument(e){return new MutableDocument(e,0,SnapshotVersion.min(),SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newFoundDocument(e,i,s,o){return new MutableDocument(e,1,i,SnapshotVersion.min(),s,o,0)}static newNoDocument(e,i){return new MutableDocument(e,2,i,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newUnknownDocument(e,i){return new MutableDocument(e,3,i,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),2)}convertToFoundDocument(e,i){return!this.createTime.isEqual(SnapshotVersion.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=i,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ObjectValue.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ObjectValue.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=SnapshotVersion.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 MutableDocument&&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 MutableDocument(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 Bound{constructor(e,i){this.position=e,this.inclusive=i}}function __PRIVATE_boundCompareToDocument(e,i,s){let o=0;for(let _=0;_<e.position.length;_++){const h=i[_],d=e.position[_];if(o=h.field.isKeyField()?DocumentKey.comparator(DocumentKey.fromName(d.referenceValue),s.key):__PRIVATE_valueCompare(d,s.data.field(h.field)),"desc"===h.dir&&(o*=-1),0!==o)break}return o}function __PRIVATE_boundEquals(e,i){if(null===e)return null===i;if(null===i)return!1;if(e.inclusive!==i.inclusive||e.position.length!==i.position.length)return!1;for(let s=0;s<e.position.length;s++)if(!__PRIVATE_valueEquals(e.position[s],i.position[s]))return!1;return!0}class OrderBy{constructor(e,i="asc"){this.field=e,this.dir=i}}function __PRIVATE_orderByEquals(e,i){return e.dir===i.dir&&e.field.isEqual(i.field)}class Filter{}class FieldFilter extends Filter{constructor(e,i,s){super(),this.field=e,this.op=i,this.value=s}static create(e,i,s){return e.isKeyField()?"in"===i||"not-in"===i?this.createKeyFieldInFilter(e,i,s):new __PRIVATE_KeyFieldFilter(e,i,s):"array-contains"===i?new __PRIVATE_ArrayContainsFilter(e,s):"in"===i?new __PRIVATE_InFilter(e,s):"not-in"===i?new __PRIVATE_NotInFilter(e,s):"array-contains-any"===i?new __PRIVATE_ArrayContainsAnyFilter(e,s):new FieldFilter(e,i,s)}static createKeyFieldInFilter(e,i,s){return"in"===i?new __PRIVATE_KeyFieldInFilter(e,s):new __PRIVATE_KeyFieldNotInFilter(e,s)}matches(e){const i=e.data.field(this.field);return"!="===this.op?null!==i&&this.matchesComparison(__PRIVATE_valueCompare(i,this.value)):null!==i&&__PRIVATE_typeOrder(this.value)===__PRIVATE_typeOrder(i)&&this.matchesComparison(__PRIVATE_valueCompare(i,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 e>0;case">=":return e>=0;default:return fail()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class CompositeFilter extends Filter{constructor(e,i){super(),this.filters=e,this.op=i,this.ae=null}static create(e,i){return new CompositeFilter(e,i)}matches(e){return __PRIVATE_compositeFilterIsConjunction(this)?void 0===this.filters.find((i=>!i.matches(e))):void 0!==this.filters.find((i=>i.matches(e)))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce(((e,i)=>e.concat(i.getFlattenedFilters())),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function __PRIVATE_compositeFilterIsConjunction(e){return"and"===e.op}function __PRIVATE_compositeFilterIsDisjunction(e){return"or"===e.op}function __PRIVATE_compositeFilterIsFlatConjunction(e){return __PRIVATE_compositeFilterIsFlat(e)&&__PRIVATE_compositeFilterIsConjunction(e)}function __PRIVATE_compositeFilterIsFlat(e){for(const i of e.filters)if(i instanceof CompositeFilter)return!1;return!0}function __PRIVATE_canonifyFilter(e){if(e instanceof FieldFilter)return e.field.canonicalString()+e.op.toString()+canonicalId(e.value);if(__PRIVATE_compositeFilterIsFlatConjunction(e))return e.filters.map((e=>__PRIVATE_canonifyFilter(e))).join(",");{const i=e.filters.map((e=>__PRIVATE_canonifyFilter(e))).join(",");return`${e.op}(${i})`}}function __PRIVATE_filterEquals(e,i){return e instanceof FieldFilter?function __PRIVATE_fieldFilterEquals(e,i){return i instanceof FieldFilter&&e.op===i.op&&e.field.isEqual(i.field)&&__PRIVATE_valueEquals(e.value,i.value)}(e,i):e instanceof CompositeFilter?function __PRIVATE_compositeFilterEquals(e,i){return i instanceof CompositeFilter&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce(((e,s,o)=>e&&__PRIVATE_filterEquals(s,i.filters[o])),!0)}(e,i):void fail()}function __PRIVATE_compositeFilterWithAddedFilters(e,i){const s=e.filters.concat(i);return CompositeFilter.create(s,e.op)}function __PRIVATE_stringifyFilter(e){return e instanceof FieldFilter?function __PRIVATE_stringifyFieldFilter(e){return`${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`}(e):e instanceof CompositeFilter?function __PRIVATE_stringifyCompositeFilter(e){return e.op.toString()+" {"+e.getFilters().map(__PRIVATE_stringifyFilter).join(" ,")+"}"}(e):"Filter"}class __PRIVATE_KeyFieldFilter extends FieldFilter{constructor(e,i,s){super(e,i,s),this.key=DocumentKey.fromName(s.referenceValue)}matches(e){const i=DocumentKey.comparator(e.key,this.key);return this.matchesComparison(i)}}class __PRIVATE_KeyFieldInFilter extends FieldFilter{constructor(e,i){super(e,"in",i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("in",i)}matches(e){return this.keys.some((i=>i.isEqual(e.key)))}}class __PRIVATE_KeyFieldNotInFilter extends FieldFilter{constructor(e,i){super(e,"not-in",i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("not-in",i)}matches(e){return!this.keys.some((i=>i.isEqual(e.key)))}}function __PRIVATE_extractDocumentKeysFromArrayValue(e,i){var s;return((null===(s=i.arrayValue)||void 0===s?void 0:s.values)||[]).map((e=>DocumentKey.fromName(e.referenceValue)))}class __PRIVATE_ArrayContainsFilter extends FieldFilter{constructor(e,i){super(e,"array-contains",i)}matches(e){const i=e.data.field(this.field);return isArray(i)&&__PRIVATE_arrayValueContains(i.arrayValue,this.value)}}class __PRIVATE_InFilter extends FieldFilter{constructor(e,i){super(e,"in",i)}matches(e){const i=e.data.field(this.field);return null!==i&&__PRIVATE_arrayValueContains(this.value.arrayValue,i)}}class __PRIVATE_NotInFilter extends FieldFilter{constructor(e,i){super(e,"not-in",i)}matches(e){if(__PRIVATE_arrayValueContains(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const i=e.data.field(this.field);return null!==i&&!__PRIVATE_arrayValueContains(this.value.arrayValue,i)}}class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter{constructor(e,i){super(e,"array-contains-any",i)}matches(e){const i=e.data.field(this.field);return!(!isArray(i)||!i.arrayValue.values)&&i.arrayValue.values.some((e=>__PRIVATE_arrayValueContains(this.value.arrayValue,e)))}}class __PRIVATE_TargetImpl{constructor(e,i=null,s=[],o=[],_=null,h=null,d=null){this.path=e,this.collectionGroup=i,this.orderBy=s,this.filters=o,this.limit=_,this.startAt=h,this.endAt=d,this.ue=null}}function __PRIVATE_newTarget(e,i=null,s=[],o=[],_=null,h=null,d=null){return new __PRIVATE_TargetImpl(e,i,s,o,_,h,d)}function __PRIVATE_canonifyTarget(e){const i=__PRIVATE_debugCast(e);if(null===i.ue){let e=i.path.canonicalString();null!==i.collectionGroup&&(e+="|cg:"+i.collectionGroup),e+="|f:",e+=i.filters.map((e=>__PRIVATE_canonifyFilter(e))).join(","),e+="|ob:",e+=i.orderBy.map((e=>function __PRIVATE_canonifyOrderBy(e){return e.field.canonicalString()+e.dir}(e))).join(","),__PRIVATE_isNullOrUndefined(i.limit)||(e+="|l:",e+=i.limit),i.startAt&&(e+="|lb:",e+=i.startAt.inclusive?"b:":"a:",e+=i.startAt.position.map((e=>canonicalId(e))).join(",")),i.endAt&&(e+="|ub:",e+=i.endAt.inclusive?"a:":"b:",e+=i.endAt.position.map((e=>canonicalId(e))).join(",")),i.ue=e}return i.ue}function __PRIVATE_targetEquals(e,i){if(e.limit!==i.limit)return!1;if(e.orderBy.length!==i.orderBy.length)return!1;for(let s=0;s<e.orderBy.length;s++)if(!__PRIVATE_orderByEquals(e.orderBy[s],i.orderBy[s]))return!1;if(e.filters.length!==i.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!__PRIVATE_filterEquals(e.filters[s],i.filters[s]))return!1;return e.collectionGroup===i.collectionGroup&&!!e.path.isEqual(i.path)&&!!__PRIVATE_boundEquals(e.startAt,i.startAt)&&__PRIVATE_boundEquals(e.endAt,i.endAt)}function __PRIVATE_targetIsDocumentTarget(e){return DocumentKey.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function __PRIVATE_targetGetFieldFiltersForPath(e,i){return e.filters.filter((e=>e instanceof FieldFilter&&e.field.isEqual(i)))}function __PRIVATE_targetGetAscendingBound(e,i,s){let o=qe,_=!0;for(const s of __PRIVATE_targetGetFieldFiltersForPath(e,i)){let e=qe,i=!0;switch(s.op){case"<":case"<=":e=__PRIVATE_valuesGetLowerBound(s.value);break;case"==":case"in":case">=":e=s.value;break;case">":e=s.value,i=!1;break;case"!=":case"not-in":e=qe}__PRIVATE_lowerBoundCompare({value:o,inclusive:_},{value:e,inclusive:i})<0&&(o=e,_=i)}if(null!==s)for(let h=0;h<e.orderBy.length;++h)if(e.orderBy[h].field.isEqual(i)){const e=s.position[h];__PRIVATE_lowerBoundCompare({value:o,inclusive:_},{value:e,inclusive:s.inclusive})<0&&(o=e,_=s.inclusive);break}return{value:o,inclusive:_}}function __PRIVATE_targetGetDescendingBound(e,i,s){let o=Be,_=!0;for(const s of __PRIVATE_targetGetFieldFiltersForPath(e,i)){let e=Be,i=!0;switch(s.op){case">=":case">":e=__PRIVATE_valuesGetUpperBound(s.value),i=!1;break;case"==":case"in":case"<=":e=s.value;break;case"<":e=s.value,i=!1;break;case"!=":case"not-in":e=Be}__PRIVATE_upperBoundCompare({value:o,inclusive:_},{value:e,inclusive:i})>0&&(o=e,_=i)}if(null!==s)for(let h=0;h<e.orderBy.length;++h)if(e.orderBy[h].field.isEqual(i)){const e=s.position[h];__PRIVATE_upperBoundCompare({value:o,inclusive:_},{value:e,inclusive:s.inclusive})>0&&(o=e,_=s.inclusive);break}return{value:o,inclusive:_}}class __PRIVATE_QueryImpl{constructor(e,i=null,s=[],o=[],_=null,h="F",d=null,f=null){this.path=e,this.collectionGroup=i,this.explicitOrderBy=s,this.filters=o,this.limit=_,this.limitType=h,this.startAt=d,this.endAt=f,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function __PRIVATE_newQuery(e,i,s,o,_,h,d,f){return new __PRIVATE_QueryImpl(e,i,s,o,_,h,d,f)}function __PRIVATE_newQueryForPath(e){return new __PRIVATE_QueryImpl(e)}function __PRIVATE_queryMatchesAllDocuments(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 __PRIVATE_isCollectionGroupQuery(e){return null!==e.collectionGroup}function __PRIVATE_queryNormalizedOrderBy(e){const i=__PRIVATE_debugCast(e);if(null===i.ce){i.ce=[];const e=new Set;for(const s of i.explicitOrderBy)i.ce.push(s),e.add(s.field.canonicalString());const s=i.explicitOrderBy.length>0?i.explicitOrderBy[i.explicitOrderBy.length-1].dir:"asc",o=function __PRIVATE_getInequalityFilterFields(e){let i=new SortedSet(FieldPath$1.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(i=i.add(e.field))}))})),i}(i);o.forEach((o=>{e.has(o.canonicalString())||o.isKeyField()||i.ce.push(new OrderBy(o,s))})),e.has(FieldPath$1.keyField().canonicalString())||i.ce.push(new OrderBy(FieldPath$1.keyField(),s))}return i.ce}function __PRIVATE_queryToTarget(e){const i=__PRIVATE_debugCast(e);return i.le||(i.le=__PRIVATE__queryToTarget(i,__PRIVATE_queryNormalizedOrderBy(e))),i.le}function __PRIVATE_queryToAggregateTarget(e){const i=__PRIVATE_debugCast(e);return i.he||(i.he=__PRIVATE__queryToTarget(i,e.explicitOrderBy)),i.he}function __PRIVATE__queryToTarget(e,i){if("F"===e.limitType)return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,e.startAt,e.endAt);{i=i.map((e=>{const i="desc"===e.dir?"asc":"desc";return new OrderBy(e.field,i)}));const s=e.endAt?new Bound(e.endAt.position,e.endAt.inclusive):null,o=e.startAt?new Bound(e.startAt.position,e.startAt.inclusive):null;return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,s,o)}}function __PRIVATE_queryWithAddedFilter(e,i){const s=e.filters.concat([i]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),s,e.limit,e.limitType,e.startAt,e.endAt)}function __PRIVATE_queryWithLimit(e,i,s){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),i,s,e.startAt,e.endAt)}function __PRIVATE_queryEquals(e,i){return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e),__PRIVATE_queryToTarget(i))&&e.limitType===i.limitType}function __PRIVATE_canonifyQuery(e){return`${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`}function __PRIVATE_stringifyQuery(e){return`Query(target=${function __PRIVATE_stringifyTarget(e){let i=e.path.canonicalString();return null!==e.collectionGroup&&(i+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(i+=`, filters: [${e.filters.map((e=>__PRIVATE_stringifyFilter(e))).join(", ")}]`),__PRIVATE_isNullOrUndefined(e.limit)||(i+=", limit: "+e.limit),e.orderBy.length>0&&(i+=`, orderBy: [${e.orderBy.map((e=>function __PRIVATE_stringifyOrderBy(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(i+=", startAt: ",i+=e.startAt.inclusive?"b:":"a:",i+=e.startAt.position.map((e=>canonicalId(e))).join(",")),e.endAt&&(i+=", endAt: ",i+=e.endAt.inclusive?"a:":"b:",i+=e.endAt.position.map((e=>canonicalId(e))).join(",")),`Target(${i})`}(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`}function __PRIVATE_queryMatches(e,i){return i.isFoundDocument()&&function __PRIVATE_queryMatchesPathAndCollectionGroup(e,i){const s=i.key.path;return null!==e.collectionGroup?i.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(s):DocumentKey.isDocumentKey(e.path)?e.path.isEqual(s):e.path.isImmediateParentOf(s)}(e,i)&&function __PRIVATE_queryMatchesOrderBy(e,i){for(const s of __PRIVATE_queryNormalizedOrderBy(e))if(!s.field.isKeyField()&&null===i.data.field(s.field))return!1;return!0}(e,i)&&function __PRIVATE_queryMatchesFilters(e,i){for(const s of e.filters)if(!s.matches(i))return!1;return!0}(e,i)&&function __PRIVATE_queryMatchesBounds(e,i){return!(e.startAt&&!function __PRIVATE_boundSortsBeforeDocument(e,i,s){const o=__PRIVATE_boundCompareToDocument(e,i,s);return e.inclusive?o<=0:o<0}(e.startAt,__PRIVATE_queryNormalizedOrderBy(e),i))&&!(e.endAt&&!function __PRIVATE_boundSortsAfterDocument(e,i,s){const o=__PRIVATE_boundCompareToDocument(e,i,s);return e.inclusive?o>=0:o>0}(e.endAt,__PRIVATE_queryNormalizedOrderBy(e),i))}(e,i)}function __PRIVATE_queryCollectionGroup(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function __PRIVATE_newQueryComparator(e){return(i,s)=>{let o=!1;for(const _ of __PRIVATE_queryNormalizedOrderBy(e)){const e=__PRIVATE_compareDocs(_,i,s);if(0!==e)return e;o=o||_.field.isKeyField()}return 0}}function __PRIVATE_compareDocs(e,i,s){const o=e.field.isKeyField()?DocumentKey.comparator(i.key,s.key):function __PRIVATE_compareDocumentsByField(e,i,s){const o=i.data.field(e),_=s.data.field(e);return null!==o&&null!==_?__PRIVATE_valueCompare(o,_):fail()}(e.field,i,s);switch(e.dir){case"asc":return o;case"desc":return-1*o;default:return fail()}}class ObjectMap{constructor(e,i){this.mapKeyFn=e,this.equalsFn=i,this.inner={},this.innerSize=0}get(e){const i=this.mapKeyFn(e),s=this.inner[i];if(void 0!==s)for(const[i,o]of s)if(this.equalsFn(i,e))return o}has(e){return void 0!==this.get(e)}set(e,i){const s=this.mapKeyFn(e),o=this.inner[s];if(void 0===o)return this.inner[s]=[[e,i]],void this.innerSize++;for(let s=0;s<o.length;s++)if(this.equalsFn(o[s][0],e))return void(o[s]=[e,i]);o.push([e,i]),this.innerSize++}delete(e){const i=this.mapKeyFn(e),s=this.inner[i];if(void 0===s)return!1;for(let o=0;o<s.length;o++)if(this.equalsFn(s[o][0],e))return 1===s.length?delete this.inner[i]:s.splice(o,1),this.innerSize--,!0;return!1}forEach(e){forEach(this.inner,((i,s)=>{for(const[i,o]of s)e(i,o)}))}isEmpty(){return isEmpty(this.inner)}size(){return this.innerSize}}const Ke=new SortedMap(DocumentKey.comparator);function __PRIVATE_mutableDocumentMap(){return Ke}const Qe=new SortedMap(DocumentKey.comparator);function documentMap(...e){let i=Qe;for(const s of e)i=i.insert(s.key,s);return i}function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e){let i=Qe;return e.forEach(((e,s)=>i=i.insert(e,s.overlayedDocument))),i}function __PRIVATE_newOverlayMap(){return __PRIVATE_newDocumentKeyMap()}function __PRIVATE_newMutationMap(){return __PRIVATE_newDocumentKeyMap()}function __PRIVATE_newDocumentKeyMap(){return new ObjectMap((e=>e.toString()),((e,i)=>e.isEqual(i)))}const Ge=new SortedMap(DocumentKey.comparator),ze=new SortedSet(DocumentKey.comparator);function __PRIVATE_documentKeySet(...e){let i=ze;for(const s of e)i=i.add(s);return i}const je=new SortedSet(__PRIVATE_primitiveComparator);function __PRIVATE_targetIdSet(){return je}function __PRIVATE_toDouble(e,i){if(e.useProto3Json){if(isNaN(i))return{doubleValue:"NaN"};if(i===1/0)return{doubleValue:"Infinity"};if(i===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:__PRIVATE_isNegativeZero(i)?"-0":i}}function __PRIVATE_toInteger(e){return{integerValue:""+e}}function toNumber(e,i){return isSafeInteger(i)?__PRIVATE_toInteger(i):__PRIVATE_toDouble(e,i)}class TransformOperation{constructor(){this._=void 0}}function __PRIVATE_applyTransformOperationToLocalView(e,i,s){return e instanceof __PRIVATE_ServerTimestampTransform?function serverTimestamp$1(e,i){const s={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return i&&__PRIVATE_isServerTimestamp(i)&&(i=__PRIVATE_getPreviousValue(i)),i&&(s.fields.__previous_value__=i),{mapValue:s}}(s,i):e instanceof __PRIVATE_ArrayUnionTransformOperation?__PRIVATE_applyArrayUnionTransformOperation(e,i):e instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_applyArrayRemoveTransformOperation(e,i):function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e,i){const s=__PRIVATE_computeTransformOperationBaseValue(e,i),o=asNumber(s)+asNumber(e.Pe);return isInteger(s)&&isInteger(e.Pe)?__PRIVATE_toInteger(o):__PRIVATE_toDouble(e.serializer,o)}(e,i)}function __PRIVATE_applyTransformOperationToRemoteDocument(e,i,s){return e instanceof __PRIVATE_ArrayUnionTransformOperation?__PRIVATE_applyArrayUnionTransformOperation(e,i):e instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_applyArrayRemoveTransformOperation(e,i):s}function __PRIVATE_computeTransformOperationBaseValue(e,i){return e instanceof __PRIVATE_NumericIncrementTransformOperation?function __PRIVATE_isNumber(e){return isInteger(e)||function __PRIVATE_isDouble(e){return!!e&&"doubleValue"in e}(e)}(i)?i:{integerValue:0}:null}class __PRIVATE_ServerTimestampTransform extends TransformOperation{}class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}function __PRIVATE_applyArrayUnionTransformOperation(e,i){const s=__PRIVATE_coercedFieldValuesArray(i);for(const i of e.elements)s.some((e=>__PRIVATE_valueEquals(e,i)))||s.push(i);return{arrayValue:{values:s}}}class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}function __PRIVATE_applyArrayRemoveTransformOperation(e,i){let s=__PRIVATE_coercedFieldValuesArray(i);for(const i of e.elements)s=s.filter((e=>!__PRIVATE_valueEquals(e,i)));return{arrayValue:{values:s}}}class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation{constructor(e,i){super(),this.serializer=e,this.Pe=i}}function asNumber(e){return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue)}function __PRIVATE_coercedFieldValuesArray(e){return isArray(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class FieldTransform{constructor(e,i){this.field=e,this.transform=i}}class MutationResult{constructor(e,i){this.version=e,this.transformResults=i}}class Precondition{constructor(e,i){this.updateTime=e,this.exists=i}static none(){return new Precondition}static exists(e){return new Precondition(void 0,e)}static updateTime(e){return new Precondition(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 __PRIVATE_preconditionIsValidForDocument(e,i){return void 0!==e.updateTime?i.isFoundDocument()&&i.version.isEqual(e.updateTime):void 0===e.exists||e.exists===i.isFoundDocument()}class Mutation{}function __PRIVATE_calculateOverlayMutation(e,i){if(!e.hasLocalMutations||i&&0===i.fields.length)return null;if(null===i)return e.isNoDocument()?new __PRIVATE_DeleteMutation(e.key,Precondition.none()):new __PRIVATE_SetMutation(e.key,e.data,Precondition.none());{const s=e.data,o=ObjectValue.empty();let _=new SortedSet(FieldPath$1.comparator);for(let e of i.fields)if(!_.has(e)){let i=s.field(e);null===i&&e.length>1&&(e=e.popLast(),i=s.field(e)),null===i?o.delete(e):o.set(e,i),_=_.add(e)}return new __PRIVATE_PatchMutation(e.key,o,new FieldMask(_.toArray()),Precondition.none())}}function __PRIVATE_mutationApplyToRemoteDocument(e,i,s){e instanceof __PRIVATE_SetMutation?function __PRIVATE_setMutationApplyToRemoteDocument(e,i,s){const o=e.value.clone(),_=__PRIVATE_serverTransformResults(e.fieldTransforms,i,s.transformResults);o.setAll(_),i.convertToFoundDocument(s.version,o).setHasCommittedMutations()}(e,i,s):e instanceof __PRIVATE_PatchMutation?function __PRIVATE_patchMutationApplyToRemoteDocument(e,i,s){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return void i.convertToUnknownDocument(s.version);const o=__PRIVATE_serverTransformResults(e.fieldTransforms,i,s.transformResults),_=i.data;_.setAll(__PRIVATE_getPatch(e)),_.setAll(o),i.convertToFoundDocument(s.version,_).setHasCommittedMutations()}(e,i,s):function __PRIVATE_deleteMutationApplyToRemoteDocument(e,i,s){i.convertToNoDocument(s.version).setHasCommittedMutations()}(0,i,s)}function __PRIVATE_mutationApplyToLocalView(e,i,s,o){return e instanceof __PRIVATE_SetMutation?function __PRIVATE_setMutationApplyToLocalView(e,i,s,o){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return s;const _=e.value.clone(),h=__PRIVATE_localTransformResults(e.fieldTransforms,o,i);return _.setAll(h),i.convertToFoundDocument(i.version,_).setHasLocalMutations(),null}(e,i,s,o):e instanceof __PRIVATE_PatchMutation?function __PRIVATE_patchMutationApplyToLocalView(e,i,s,o){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return s;const _=__PRIVATE_localTransformResults(e.fieldTransforms,o,i),h=i.data;return h.setAll(__PRIVATE_getPatch(e)),h.setAll(_),i.convertToFoundDocument(i.version,h).setHasLocalMutations(),null===s?null:s.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,i,s,o):function __PRIVATE_deleteMutationApplyToLocalView(e,i,s){return __PRIVATE_preconditionIsValidForDocument(e.precondition,i)?(i.convertToNoDocument(i.version).setHasLocalMutations(),null):s}(e,i,s)}function __PRIVATE_mutationExtractBaseValue(e,i){let s=null;for(const o of e.fieldTransforms){const e=i.data.field(o.field),_=__PRIVATE_computeTransformOperationBaseValue(o.transform,e||null);null!=_&&(null===s&&(s=ObjectValue.empty()),s.set(o.field,_))}return s||null}function __PRIVATE_mutationEquals(e,i){return e.type===i.type&&!!e.key.isEqual(i.key)&&!!e.precondition.isEqual(i.precondition)&&!!function __PRIVATE_fieldTransformsAreEqual(e,i){return void 0===e&&void 0===i||!(!e||!i)&&__PRIVATE_arrayEquals(e,i,((e,i)=>function __PRIVATE_fieldTransformEquals(e,i){return e.field.isEqual(i.field)&&function __PRIVATE_transformOperationEquals(e,i){return e instanceof __PRIVATE_ArrayUnionTransformOperation&&i instanceof __PRIVATE_ArrayUnionTransformOperation||e instanceof __PRIVATE_ArrayRemoveTransformOperation&&i instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_arrayEquals(e.elements,i.elements,__PRIVATE_valueEquals):e instanceof __PRIVATE_NumericIncrementTransformOperation&&i instanceof __PRIVATE_NumericIncrementTransformOperation?__PRIVATE_valueEquals(e.Pe,i.Pe):e instanceof __PRIVATE_ServerTimestampTransform&&i instanceof __PRIVATE_ServerTimestampTransform}(e.transform,i.transform)}(e,i)))}(e.fieldTransforms,i.fieldTransforms)&&(0===e.type?e.value.isEqual(i.value):1!==e.type||e.data.isEqual(i.data)&&e.fieldMask.isEqual(i.fieldMask))}class __PRIVATE_SetMutation extends Mutation{constructor(e,i,s,o=[]){super(),this.key=e,this.value=i,this.precondition=s,this.fieldTransforms=o,this.type=0}getFieldMask(){return null}}class __PRIVATE_PatchMutation extends Mutation{constructor(e,i,s,o,_=[]){super(),this.key=e,this.data=i,this.fieldMask=s,this.precondition=o,this.fieldTransforms=_,this.type=1}getFieldMask(){return this.fieldMask}}function __PRIVATE_getPatch(e){const i=new Map;return e.fieldMask.fields.forEach((s=>{if(!s.isEmpty()){const o=e.data.field(s);i.set(s,o)}})),i}function __PRIVATE_serverTransformResults(e,i,s){const o=new Map;__PRIVATE_hardAssert(e.length===s.length);for(let _=0;_<s.length;_++){const h=e[_],d=h.transform,f=i.data.field(h.field);o.set(h.field,__PRIVATE_applyTransformOperationToRemoteDocument(d,f,s[_]))}return o}function __PRIVATE_localTransformResults(e,i,s){const o=new Map;for(const _ of e){const e=_.transform,h=s.data.field(_.field);o.set(_.field,__PRIVATE_applyTransformOperationToLocalView(e,h,i))}return o}class __PRIVATE_DeleteMutation extends Mutation{constructor(e,i){super(),this.key=e,this.precondition=i,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class __PRIVATE_VerifyMutation extends Mutation{constructor(e,i){super(),this.key=e,this.precondition=i,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class MutationBatch{constructor(e,i,s,o){this.batchId=e,this.localWriteTime=i,this.baseMutations=s,this.mutations=o}applyToRemoteDocument(e,i){const s=i.mutationResults;for(let i=0;i<this.mutations.length;i++){const o=this.mutations[i];o.key.isEqual(e.key)&&__PRIVATE_mutationApplyToRemoteDocument(o,e,s[i])}}applyToLocalView(e,i){for(const s of this.baseMutations)s.key.isEqual(e.key)&&(i=__PRIVATE_mutationApplyToLocalView(s,e,i,this.localWriteTime));for(const s of this.mutations)s.key.isEqual(e.key)&&(i=__PRIVATE_mutationApplyToLocalView(s,e,i,this.localWriteTime));return i}applyToLocalDocumentSet(e,i){const s=__PRIVATE_newMutationMap();return this.mutations.forEach((o=>{const _=e.get(o.key),h=_.overlayedDocument;let d=this.applyToLocalView(h,_.mutatedFields);d=i.has(o.key)?null:d;const f=__PRIVATE_calculateOverlayMutation(h,d);null!==f&&s.set(o.key,f),h.isValidDocument()||h.convertToNoDocument(SnapshotVersion.min())})),s}keys(){return this.mutations.reduce(((e,i)=>e.add(i.key)),__PRIVATE_documentKeySet())}isEqual(e){return this.batchId===e.batchId&&__PRIVATE_arrayEquals(this.mutations,e.mutations,((e,i)=>__PRIVATE_mutationEquals(e,i)))&&__PRIVATE_arrayEquals(this.baseMutations,e.baseMutations,((e,i)=>__PRIVATE_mutationEquals(e,i)))}}class MutationBatchResult{constructor(e,i,s,o){this.batch=e,this.commitVersion=i,this.mutationResults=s,this.docVersions=o}static from(e,i,s){__PRIVATE_hardAssert(e.mutations.length===s.length);let o=function __PRIVATE_documentVersionMap(){return Ge}();const _=e.mutations;for(let e=0;e<_.length;e++)o=o.insert(_[e].key,s[e].version);return new MutationBatchResult(e,i,s,o)}}class Overlay{constructor(e,i){this.largestBatchId=e,this.mutation=i}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 __PRIVATE_AggregateImpl{constructor(e,i,s){this.alias=e,this.aggregateType=i,this.fieldPath=s}}class ExistenceFilter{constructor(e,i){this.count=e,this.unchangedNames=i}}var We,$e;function __PRIVATE_isPermanentError(e){switch(e){default:return fail();case _e.CANCELLED:case _e.UNKNOWN:case _e.DEADLINE_EXCEEDED:case _e.RESOURCE_EXHAUSTED:case _e.INTERNAL:case _e.UNAVAILABLE:case _e.UNAUTHENTICATED:return!1;case _e.INVALID_ARGUMENT:case _e.NOT_FOUND:case _e.ALREADY_EXISTS:case _e.PERMISSION_DENIED:case _e.FAILED_PRECONDITION:case _e.ABORTED:case _e.OUT_OF_RANGE:case _e.UNIMPLEMENTED:case _e.DATA_LOSS:return!0}}function __PRIVATE_mapCodeFromRpcCode(e){if(void 0===e)return __PRIVATE_logError("GRPC error has no .code"),_e.UNKNOWN;switch(e){case We.OK:return _e.OK;case We.CANCELLED:return _e.CANCELLED;case We.UNKNOWN:return _e.UNKNOWN;case We.DEADLINE_EXCEEDED:return _e.DEADLINE_EXCEEDED;case We.RESOURCE_EXHAUSTED:return _e.RESOURCE_EXHAUSTED;case We.INTERNAL:return _e.INTERNAL;case We.UNAVAILABLE:return _e.UNAVAILABLE;case We.UNAUTHENTICATED:return _e.UNAUTHENTICATED;case We.INVALID_ARGUMENT:return _e.INVALID_ARGUMENT;case We.NOT_FOUND:return _e.NOT_FOUND;case We.ALREADY_EXISTS:return _e.ALREADY_EXISTS;case We.PERMISSION_DENIED:return _e.PERMISSION_DENIED;case We.FAILED_PRECONDITION:return _e.FAILED_PRECONDITION;case We.ABORTED:return _e.ABORTED;case We.OUT_OF_RANGE:return _e.OUT_OF_RANGE;case We.UNIMPLEMENTED:return _e.UNIMPLEMENTED;case We.DATA_LOSS:return _e.DATA_LOSS;default:return fail()}}($e=We||(We={}))[$e.OK=0]="OK",$e[$e.CANCELLED=1]="CANCELLED",$e[$e.UNKNOWN=2]="UNKNOWN",$e[$e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",$e[$e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",$e[$e.NOT_FOUND=5]="NOT_FOUND",$e[$e.ALREADY_EXISTS=6]="ALREADY_EXISTS",$e[$e.PERMISSION_DENIED=7]="PERMISSION_DENIED",$e[$e.UNAUTHENTICATED=16]="UNAUTHENTICATED",$e[$e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",$e[$e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",$e[$e.ABORTED=10]="ABORTED",$e[$e.OUT_OF_RANGE=11]="OUT_OF_RANGE",$e[$e.UNIMPLEMENTED=12]="UNIMPLEMENTED",$e[$e.INTERNAL=13]="INTERNAL",$e[$e.UNAVAILABLE=14]="UNAVAILABLE",$e[$e.DATA_LOSS=15]="DATA_LOSS";let He=null;function __PRIVATE_newTextEncoder(){return new TextEncoder}const Je=new O([4294967295,4294967295],0);function __PRIVATE_getMd5HashValue(e){const i=__PRIVATE_newTextEncoder().encode(e),s=new q;return s.update(i),new Uint8Array(s.digest())}function __PRIVATE_get64BitUints(e){const i=new DataView(e.buffer),s=i.getUint32(0,!0),o=i.getUint32(4,!0),_=i.getUint32(8,!0),h=i.getUint32(12,!0);return[new O([s,o],0),new O([_,h],0)]}class BloomFilter{constructor(e,i,s){if(this.bitmap=e,this.padding=i,this.hashCount=s,i<0||i>=8)throw new __PRIVATE_BloomFilterError(`Invalid padding: ${i}`);if(s<0)throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${s}`);if(e.length>0&&0===this.hashCount)throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${s}`);if(0===e.length&&0!==i)throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${i}`);this.Ie=8*e.length-i,this.Te=O.fromNumber(this.Ie)}Ee(e,i,s){let o=e.add(i.multiply(O.fromNumber(s)));return 1===o.compare(Je)&&(o=new O([o.getBits(0),o.getBits(1)],0)),o.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 i=__PRIVATE_getMd5HashValue(e),[s,o]=__PRIVATE_get64BitUints(i);for(let e=0;e<this.hashCount;e++){const i=this.Ee(s,o,e);if(!this.de(i))return!1}return!0}static create(e,i,s){const o=e%8==0?0:8-e%8,_=new Uint8Array(Math.ceil(e/8)),h=new BloomFilter(_,o,i);return s.forEach((e=>h.insert(e))),h}insert(e){if(0===this.Ie)return;const i=__PRIVATE_getMd5HashValue(e),[s,o]=__PRIVATE_get64BitUints(i);for(let e=0;e<this.hashCount;e++){const i=this.Ee(s,o,e);this.Ae(i)}}Ae(e){const i=Math.floor(e/8),s=e%8;this.bitmap[i]|=1<<s}}class __PRIVATE_BloomFilterError extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class RemoteEvent{constructor(e,i,s,o,_){this.snapshotVersion=e,this.targetChanges=i,this.targetMismatches=s,this.documentUpdates=o,this.resolvedLimboDocuments=_}static createSynthesizedRemoteEventForCurrentChange(e,i,s){const o=new Map;return o.set(e,TargetChange.createSynthesizedTargetChangeForCurrentChange(e,i,s)),new RemoteEvent(SnapshotVersion.min(),o,new SortedMap(__PRIVATE_primitiveComparator),__PRIVATE_mutableDocumentMap(),__PRIVATE_documentKeySet())}}class TargetChange{constructor(e,i,s,o,_){this.resumeToken=e,this.current=i,this.addedDocuments=s,this.modifiedDocuments=o,this.removedDocuments=_}static createSynthesizedTargetChangeForCurrentChange(e,i,s){return new TargetChange(s,i,__PRIVATE_documentKeySet(),__PRIVATE_documentKeySet(),__PRIVATE_documentKeySet())}}class __PRIVATE_DocumentWatchChange{constructor(e,i,s,o){this.Re=e,this.removedTargetIds=i,this.key=s,this.Ve=o}}class __PRIVATE_ExistenceFilterChange{constructor(e,i){this.targetId=e,this.me=i}}class __PRIVATE_WatchTargetChange{constructor(e,i,s=ByteString.EMPTY_BYTE_STRING,o=null){this.state=e,this.targetIds=i,this.resumeToken=s,this.cause=o}}class __PRIVATE_TargetState{constructor(){this.fe=0,this.ge=__PRIVATE_snapshotChangesMap(),this.pe=ByteString.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){e.approximateByteSize()>0&&(this.we=!0,this.pe=e)}ve(){let e=__PRIVATE_documentKeySet(),i=__PRIVATE_documentKeySet(),s=__PRIVATE_documentKeySet();return this.ge.forEach(((o,_)=>{switch(_){case 0:e=e.add(o);break;case 2:i=i.add(o);break;case 1:s=s.add(o);break;default:fail()}})),new TargetChange(this.pe,this.ye,e,i,s)}Ce(){this.we=!1,this.ge=__PRIVATE_snapshotChangesMap()}Fe(e,i){this.we=!0,this.ge=this.ge.insert(e,i)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){this.fe-=1,__PRIVATE_hardAssert(this.fe>=0)}Ne(){this.we=!0,this.ye=!0}}class __PRIVATE_WatchChangeAggregator{constructor(e){this.Le=e,this.Be=new Map,this.ke=__PRIVATE_mutableDocumentMap(),this.qe=__PRIVATE_documentTargetMap(),this.Qe=new SortedMap(__PRIVATE_primitiveComparator)}Ke(e){for(const i of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.$e(i,e.Ve):this.Ue(i,e.key,e.Ve);for(const i of e.removedTargetIds)this.Ue(i,e.key,e.Ve)}We(e){this.forEachTarget(e,(i=>{const s=this.Ge(i);switch(e.state){case 0:this.ze(i)&&s.De(e.resumeToken);break;case 1:s.Oe(),s.Se||s.Ce(),s.De(e.resumeToken);break;case 2:s.Oe(),s.Se||this.removeTarget(i);break;case 3:this.ze(i)&&(s.Ne(),s.De(e.resumeToken));break;case 4:this.ze(i)&&(this.je(i),s.De(e.resumeToken));break;default:fail()}}))}forEachTarget(e,i){e.targetIds.length>0?e.targetIds.forEach(i):this.Be.forEach(((e,s)=>{this.ze(s)&&i(s)}))}He(e){const i=e.targetId,s=e.me.count,o=this.Je(i);if(o){const _=o.target;if(__PRIVATE_targetIsDocumentTarget(_))if(0===s){const e=new DocumentKey(_.path);this.Ue(i,e,MutableDocument.newNoDocument(e,SnapshotVersion.min()))}else __PRIVATE_hardAssert(1===s);else{const o=this.Ye(i);if(o!==s){const s=this.Ze(e),_=s?this.Xe(s,e,o):1;if(0!==_){this.je(i);const e=2===_?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Qe=this.Qe.insert(i,e)}null==He||He.et(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e,i,s,o,_){var h,d,f,g,b,w;const O={localCacheCount:e,existenceFilterCount:i.count,databaseId:s.database,projectId:s.projectId},q=i.unchangedNames;return q&&(O.bloomFilter={applied:0===_,hashCount:null!==(h=null==q?void 0:q.hashCount)&&void 0!==h?h:0,bitmapLength:null!==(g=null===(f=null===(d=null==q?void 0:q.bits)||void 0===d?void 0:d.bitmap)||void 0===f?void 0:f.length)&&void 0!==g?g:0,padding:null!==(w=null===(b=null==q?void 0:q.bits)||void 0===b?void 0:b.padding)&&void 0!==w?w:0,mightContain:e=>{var i;return null!==(i=null==o?void 0:o.mightContain(e))&&void 0!==i&&i}}),O}(o,e.me,this.Le.tt(),s,_))}}}}Ze(e){const i=e.me.unchangedNames;if(!i||!i.bits)return null;const{bits:{bitmap:s="",padding:o=0},hashCount:_=0}=i;let h,d;try{h=__PRIVATE_normalizeByteString(s).toUint8Array()}catch(e){if(e instanceof __PRIVATE_Base64DecodeError)return __PRIVATE_logWarn("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{d=new BloomFilter(h,o,_)}catch(e){return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===d.Ie?null:d}Xe(e,i,s){return i.me.count===s-this.nt(e,i.targetId)?0:2}nt(e,i){const s=this.Le.getRemoteKeysForTarget(i);let o=0;return s.forEach((s=>{const _=this.Le.tt(),h=`projects/${_.projectId}/databases/${_.database}/documents/${s.path.canonicalString()}`;e.mightContain(h)||(this.Ue(i,s,null),o++)})),o}rt(e){const i=new Map;this.Be.forEach(((s,o)=>{const _=this.Je(o);if(_){if(s.current&&__PRIVATE_targetIsDocumentTarget(_.target)){const i=new DocumentKey(_.target.path);null!==this.ke.get(i)||this.it(o,i)||this.Ue(o,i,MutableDocument.newNoDocument(i,e))}s.be&&(i.set(o,s.ve()),s.Ce())}}));let s=__PRIVATE_documentKeySet();this.qe.forEach(((e,i)=>{let o=!0;i.forEachWhile((e=>{const i=this.Je(e);return!i||"TargetPurposeLimboResolution"===i.purpose||(o=!1,!1)})),o&&(s=s.add(e))})),this.ke.forEach(((i,s)=>s.setReadTime(e)));const o=new RemoteEvent(e,i,this.Qe,this.ke,s);return this.ke=__PRIVATE_mutableDocumentMap(),this.qe=__PRIVATE_documentTargetMap(),this.Qe=new SortedMap(__PRIVATE_primitiveComparator),o}$e(e,i){if(!this.ze(e))return;const s=this.it(e,i.key)?2:0;this.Ge(e).Fe(i.key,s),this.ke=this.ke.insert(i.key,i),this.qe=this.qe.insert(i.key,this.st(i.key).add(e))}Ue(e,i,s){if(!this.ze(e))return;const o=this.Ge(e);this.it(e,i)?o.Fe(i,1):o.Me(i),this.qe=this.qe.insert(i,this.st(i).delete(e)),s&&(this.ke=this.ke.insert(i,s))}removeTarget(e){this.Be.delete(e)}Ye(e){const i=this.Ge(e).ve();return this.Le.getRemoteKeysForTarget(e).size+i.addedDocuments.size-i.removedDocuments.size}xe(e){this.Ge(e).xe()}Ge(e){let i=this.Be.get(e);return i||(i=new __PRIVATE_TargetState,this.Be.set(e,i)),i}st(e){let i=this.qe.get(e);return i||(i=new SortedSet(__PRIVATE_primitiveComparator),this.qe=this.qe.insert(e,i)),i}ze(e){const i=null!==this.Je(e);return i||__PRIVATE_logDebug("WatchChangeAggregator","Detected inactive target",e),i}Je(e){const i=this.Be.get(e);return i&&i.Se?null:this.Le.ot(e)}je(e){this.Be.set(e,new __PRIVATE_TargetState),this.Le.getRemoteKeysForTarget(e).forEach((i=>{this.Ue(e,i,null)}))}it(e,i){return this.Le.getRemoteKeysForTarget(e).has(i)}}function __PRIVATE_documentTargetMap(){return new SortedMap(DocumentKey.comparator)}function __PRIVATE_snapshotChangesMap(){return new SortedMap(DocumentKey.comparator)}const Xe={asc:"ASCENDING",desc:"DESCENDING"},Ye={"<":"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"},Ze={and:"AND",or:"OR"};class JsonProtoSerializer{constructor(e,i){this.databaseId=e,this.useProto3Json=i}}function __PRIVATE_toInt32Proto(e,i){return e.useProto3Json||__PRIVATE_isNullOrUndefined(i)?i:{value:i}}function toTimestamp(e,i){return e.useProto3Json?`${new Date(1e3*i.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+i.nanoseconds).slice(-9)}Z`:{seconds:""+i.seconds,nanos:i.nanoseconds}}function __PRIVATE_toBytes(e,i){return e.useProto3Json?i.toBase64():i.toUint8Array()}function __PRIVATE_toVersion(e,i){return toTimestamp(e,i.toTimestamp())}function __PRIVATE_fromVersion(e){return __PRIVATE_hardAssert(!!e),SnapshotVersion.fromTimestamp(function fromTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}(e))}function __PRIVATE_toResourceName(e,i){return __PRIVATE_toResourcePath(e,i).canonicalString()}function __PRIVATE_toResourcePath(e,i){const s=function __PRIVATE_fullyQualifiedPrefixPath(e){return new ResourcePath(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===i?s:s.child(i)}function __PRIVATE_fromResourceName(e){const i=ResourcePath.fromString(e);return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(i)),i}function __PRIVATE_toName(e,i){return __PRIVATE_toResourceName(e.databaseId,i.path)}function fromName(e,i){const s=__PRIVATE_fromResourceName(i);if(s.get(1)!==e.databaseId.projectId)throw new FirestoreError(_e.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+s.get(1)+" vs "+e.databaseId.projectId);if(s.get(3)!==e.databaseId.database)throw new FirestoreError(_e.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+s.get(3)+" vs "+e.databaseId.database);return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(s))}function __PRIVATE_toQueryPath(e,i){return __PRIVATE_toResourceName(e.databaseId,i)}function __PRIVATE_fromQueryPath(e){const i=__PRIVATE_fromResourceName(e);return 4===i.length?ResourcePath.emptyPath():__PRIVATE_extractLocalPathFromResourceName(i)}function __PRIVATE_getEncodedDatabaseId(e){return new ResourcePath(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function __PRIVATE_extractLocalPathFromResourceName(e){return __PRIVATE_hardAssert(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function __PRIVATE_toMutationDocument(e,i,s){return{name:__PRIVATE_toName(e,i),fields:s.value.mapValue.fields}}function __PRIVATE_fromDocument(e,i,s){const o=fromName(e,i.name),_=__PRIVATE_fromVersion(i.updateTime),h=i.createTime?__PRIVATE_fromVersion(i.createTime):SnapshotVersion.min(),d=new ObjectValue({mapValue:{fields:i.fields}}),f=MutableDocument.newFoundDocument(o,_,h,d);return s&&f.setHasCommittedMutations(),s?f.setHasCommittedMutations():f}function toMutation(e,i){let s;if(i instanceof __PRIVATE_SetMutation)s={update:__PRIVATE_toMutationDocument(e,i.key,i.value)};else if(i instanceof __PRIVATE_DeleteMutation)s={delete:__PRIVATE_toName(e,i.key)};else if(i instanceof __PRIVATE_PatchMutation)s={update:__PRIVATE_toMutationDocument(e,i.key,i.data),updateMask:__PRIVATE_toDocumentMask(i.fieldMask)};else{if(!(i instanceof __PRIVATE_VerifyMutation))return fail();s={verify:__PRIVATE_toName(e,i.key)}}return i.fieldTransforms.length>0&&(s.updateTransforms=i.fieldTransforms.map((e=>function __PRIVATE_toFieldTransform(e,i){const s=i.transform;if(s instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:i.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(s instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:i.field.canonicalString(),appendMissingElements:{values:s.elements}};if(s instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:i.field.canonicalString(),removeAllFromArray:{values:s.elements}};if(s instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:i.field.canonicalString(),increment:s.Pe};throw fail()}(0,e)))),i.precondition.isNone||(s.currentDocument=function __PRIVATE_toPrecondition(e,i){return void 0!==i.updateTime?{updateTime:__PRIVATE_toVersion(e,i.updateTime)}:void 0!==i.exists?{exists:i.exists}:fail()}(e,i.precondition)),s}function __PRIVATE_fromMutation(e,i){const s=i.currentDocument?function __PRIVATE_fromPrecondition(e){return void 0!==e.updateTime?Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)):void 0!==e.exists?Precondition.exists(e.exists):Precondition.none()}(i.currentDocument):Precondition.none(),o=i.updateTransforms?i.updateTransforms.map((i=>function __PRIVATE_fromFieldTransform(e,i){let s=null;if("setToServerValue"in i)__PRIVATE_hardAssert("REQUEST_TIME"===i.setToServerValue),s=new __PRIVATE_ServerTimestampTransform;else if("appendMissingElements"in i){const e=i.appendMissingElements.values||[];s=new __PRIVATE_ArrayUnionTransformOperation(e)}else if("removeAllFromArray"in i){const e=i.removeAllFromArray.values||[];s=new __PRIVATE_ArrayRemoveTransformOperation(e)}else"increment"in i?s=new __PRIVATE_NumericIncrementTransformOperation(e,i.increment):fail();const o=FieldPath$1.fromServerFormat(i.fieldPath);return new FieldTransform(o,s)}(e,i))):[];if(i.update){i.update.name;const _=fromName(e,i.update.name),h=new ObjectValue({mapValue:{fields:i.update.fields}});if(i.updateMask){const e=function __PRIVATE_fromDocumentMask(e){const i=e.fieldPaths||[];return new FieldMask(i.map((e=>FieldPath$1.fromServerFormat(e))))}(i.updateMask);return new __PRIVATE_PatchMutation(_,h,e,s,o)}return new __PRIVATE_SetMutation(_,h,s,o)}if(i.delete){const o=fromName(e,i.delete);return new __PRIVATE_DeleteMutation(o,s)}if(i.verify){const o=fromName(e,i.verify);return new __PRIVATE_VerifyMutation(o,s)}return fail()}function __PRIVATE_toDocumentsTarget(e,i){return{documents:[__PRIVATE_toQueryPath(e,i.path)]}}function __PRIVATE_toQueryTarget(e,i){const s={structuredQuery:{}},o=i.path;let _;null!==i.collectionGroup?(_=o,s.structuredQuery.from=[{collectionId:i.collectionGroup,allDescendants:!0}]):(_=o.popLast(),s.structuredQuery.from=[{collectionId:o.lastSegment()}]),s.parent=__PRIVATE_toQueryPath(e,_);const h=function __PRIVATE_toFilters(e){if(0!==e.length)return __PRIVATE_toFilter(CompositeFilter.create(e,"and"))}(i.filters);h&&(s.structuredQuery.where=h);const d=function __PRIVATE_toOrder(e){if(0!==e.length)return e.map((e=>function __PRIVATE_toPropertyOrder(e){return{field:__PRIVATE_toFieldPathReference(e.field),direction:__PRIVATE_toDirection(e.dir)}}(e)))}(i.orderBy);d&&(s.structuredQuery.orderBy=d);const f=__PRIVATE_toInt32Proto(e,i.limit);return null!==f&&(s.structuredQuery.limit=f),i.startAt&&(s.structuredQuery.startAt=function __PRIVATE_toStartAtCursor(e){return{before:e.inclusive,values:e.position}}(i.startAt)),i.endAt&&(s.structuredQuery.endAt=function __PRIVATE_toEndAtCursor(e){return{before:!e.inclusive,values:e.position}}(i.endAt)),{_t:s,parent:_}}function __PRIVATE_toRunAggregationQueryRequest(e,i,s,o){const{_t:_,parent:h}=__PRIVATE_toQueryTarget(e,i),d={},f=[];let g=0;return s.forEach((e=>{const i=o?e.alias:"aggregate_"+g++;d[i]=e.alias,"count"===e.aggregateType?f.push({alias:i,count:{}}):"avg"===e.aggregateType?f.push({alias:i,avg:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}}):"sum"===e.aggregateType&&f.push({alias:i,sum:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:f,structuredQuery:_.structuredQuery},parent:_.parent},ut:d,parent:h}}function __PRIVATE_convertQueryTargetToQuery(e){let i=__PRIVATE_fromQueryPath(e.parent);const s=e.structuredQuery,o=s.from?s.from.length:0;let _=null;if(o>0){__PRIVATE_hardAssert(1===o);const e=s.from[0];e.allDescendants?_=e.collectionId:i=i.child(e.collectionId)}let h=[];s.where&&(h=function __PRIVATE_fromFilters(e){const i=__PRIVATE_fromFilter(e);return i instanceof CompositeFilter&&__PRIVATE_compositeFilterIsFlatConjunction(i)?i.getFilters():[i]}(s.where));let d=[];s.orderBy&&(d=function __PRIVATE_fromOrder(e){return e.map((e=>function __PRIVATE_fromPropertyOrder(e){return new OrderBy(__PRIVATE_fromFieldPathReference(e.field),function __PRIVATE_fromDirection(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(s.orderBy));let f=null;s.limit&&(f=function __PRIVATE_fromInt32Proto(e){let i;return i="object"==typeof e?e.value:e,__PRIVATE_isNullOrUndefined(i)?null:i}(s.limit));let g=null;s.startAt&&(g=function __PRIVATE_fromStartAtCursor(e){const i=!!e.before,s=e.values||[];return new Bound(s,i)}(s.startAt));let b=null;return s.endAt&&(b=function __PRIVATE_fromEndAtCursor(e){const i=!e.before,s=e.values||[];return new Bound(s,i)}(s.endAt)),__PRIVATE_newQuery(i,_,d,h,f,"F",g,b)}function __PRIVATE_fromFilter(e){return void 0!==e.unaryFilter?function __PRIVATE_fromUnaryFilter(e){switch(e.unaryFilter.op){case"IS_NAN":const i=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(i,"==",{doubleValue:NaN});case"IS_NULL":const s=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const o=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(o,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const _=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(_,"!=",{nullValue:"NULL_VALUE"});default:return fail()}}(e):void 0!==e.fieldFilter?function __PRIVATE_fromFieldFilter(e){return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field),function __PRIVATE_fromOperatorName(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 fail()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function __PRIVATE_fromCompositeFilter(e){return CompositeFilter.create(e.compositeFilter.filters.map((e=>__PRIVATE_fromFilter(e))),function __PRIVATE_fromCompositeOperatorName(e){switch(e){case"AND":return"and";case"OR":return"or";default:return fail()}}(e.compositeFilter.op))}(e):fail()}function __PRIVATE_toDirection(e){return Xe[e]}function __PRIVATE_toOperatorName(e){return Ye[e]}function __PRIVATE_toCompositeOperatorName(e){return Ze[e]}function __PRIVATE_toFieldPathReference(e){return{fieldPath:e.canonicalString()}}function __PRIVATE_fromFieldPathReference(e){return FieldPath$1.fromServerFormat(e.fieldPath)}function __PRIVATE_toFilter(e){return e instanceof FieldFilter?function __PRIVATE_toUnaryOrFieldFilter(e){if("=="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:__PRIVATE_toOperatorName(e.op),value:e.value}}}(e):e instanceof CompositeFilter?function __PRIVATE_toCompositeFilter(e){const i=e.getFilters().map((e=>__PRIVATE_toFilter(e)));return 1===i.length?i[0]:{compositeFilter:{op:__PRIVATE_toCompositeOperatorName(e.op),filters:i}}}(e):fail()}function __PRIVATE_toDocumentMask(e){const i=[];return e.fields.forEach((e=>i.push(e.canonicalString()))),{fieldPaths:i}}function __PRIVATE_isValidResourceName(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class TargetData{constructor(e,i,s,o,_=SnapshotVersion.min(),h=SnapshotVersion.min(),d=ByteString.EMPTY_BYTE_STRING,f=null){this.target=e,this.targetId=i,this.purpose=s,this.sequenceNumber=o,this.snapshotVersion=_,this.lastLimboFreeSnapshotVersion=h,this.resumeToken=d,this.expectedCount=f}withSequenceNumber(e){return new TargetData(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,i){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,i,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class __PRIVATE_LocalSerializer{constructor(e){this.ct=e}}function __PRIVATE_toDbRemoteDocument(e,i){const s=i.key,o={prefixPath:s.getCollectionPath().popLast().toArray(),collectionGroup:s.collectionGroup,documentId:s.path.lastSegment(),readTime:__PRIVATE_toDbTimestampKey(i.readTime),hasCommittedMutations:i.hasCommittedMutations};if(i.isFoundDocument())o.document=function __PRIVATE_toDocument(e,i){return{name:__PRIVATE_toName(e,i.key),fields:i.data.value.mapValue.fields,updateTime:toTimestamp(e,i.version.toTimestamp()),createTime:toTimestamp(e,i.createTime.toTimestamp())}}(e.ct,i);else if(i.isNoDocument())o.noDocument={path:s.path.toArray(),readTime:__PRIVATE_toDbTimestamp(i.version)};else{if(!i.isUnknownDocument())return fail();o.unknownDocument={path:s.path.toArray(),version:__PRIVATE_toDbTimestamp(i.version)}}return o}function __PRIVATE_toDbTimestampKey(e){const i=e.toTimestamp();return[i.seconds,i.nanoseconds]}function __PRIVATE_toDbTimestamp(e){const i=e.toTimestamp();return{seconds:i.seconds,nanoseconds:i.nanoseconds}}function __PRIVATE_fromDbTimestamp(e){const i=new Timestamp(e.seconds,e.nanoseconds);return SnapshotVersion.fromTimestamp(i)}function __PRIVATE_fromDbMutationBatch(e,i){const s=(i.baseMutations||[]).map((i=>__PRIVATE_fromMutation(e.ct,i)));for(let e=0;e<i.mutations.length-1;++e){const s=i.mutations[e];if(e+1<i.mutations.length&&void 0!==i.mutations[e+1].transform){const o=i.mutations[e+1];s.updateTransforms=o.transform.fieldTransforms,i.mutations.splice(e+1,1),++e}}const o=i.mutations.map((i=>__PRIVATE_fromMutation(e.ct,i))),_=Timestamp.fromMillis(i.localWriteTimeMs);return new MutationBatch(i.batchId,_,s,o)}function __PRIVATE_fromDbTarget(e){const i=__PRIVATE_fromDbTimestamp(e.readTime),s=void 0!==e.lastLimboFreeSnapshotVersion?__PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion):SnapshotVersion.min();let o;return o=function __PRIVATE_isDocumentQuery(e){return void 0!==e.documents}(e.query)?function __PRIVATE_fromDocumentsTarget(e){return __PRIVATE_hardAssert(1===e.documents.length),__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0])))}(e.query):function __PRIVATE_fromQueryTarget(e){return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e))}(e.query),new TargetData(o,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,i,s,ByteString.fromBase64String(e.resumeToken))}function __PRIVATE_toDbTarget(e,i){const s=__PRIVATE_toDbTimestamp(i.snapshotVersion),o=__PRIVATE_toDbTimestamp(i.lastLimboFreeSnapshotVersion);let _;_=__PRIVATE_targetIsDocumentTarget(i.target)?__PRIVATE_toDocumentsTarget(e.ct,i.target):__PRIVATE_toQueryTarget(e.ct,i.target)._t;const h=i.resumeToken.toBase64();return{targetId:i.targetId,canonicalId:__PRIVATE_canonifyTarget(i.target),readTime:s,resumeToken:h,lastListenSequenceNumber:i.sequenceNumber,lastLimboFreeSnapshotVersion:o,query:_}}function __PRIVATE_fromBundledQuery(e){const i=__PRIVATE_convertQueryTargetToQuery({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?__PRIVATE_queryWithLimit(i,i.limit,"L"):i}function __PRIVATE_fromDbDocumentOverlay(e,i){return new Overlay(i.largestBatchId,__PRIVATE_fromMutation(e.ct,i.overlayMutation))}function __PRIVATE_toDbDocumentOverlayKey(e,i){const s=i.path.lastSegment();return[e,__PRIVATE_encodeResourcePath(i.path.popLast()),s]}function __PRIVATE_toDbIndexState(e,i,s,o){return{indexId:e,uid:i,sequenceNumber:s,readTime:__PRIVATE_toDbTimestamp(o.readTime),documentKey:__PRIVATE_encodeResourcePath(o.documentKey.path),largestBatchId:o.largestBatchId}}class __PRIVATE_IndexedDbBundleCache{getBundleMetadata(e,i){return __PRIVATE_bundlesStore(e).get(i).next((e=>{if(e)return function __PRIVATE_fromDbBundle(e){return{id:e.bundleId,createTime:__PRIVATE_fromDbTimestamp(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,i){return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e){return{bundleId:e.id,createTime:__PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)),version:e.version}}(i))}getNamedQuery(e,i){return __PRIVATE_namedQueriesStore(e).get(i).next((e=>{if(e)return function __PRIVATE_fromDbNamedQuery(e){return{name:e.name,query:__PRIVATE_fromBundledQuery(e.bundledQuery),readTime:__PRIVATE_fromDbTimestamp(e.readTime)}}(e)}))}saveNamedQuery(e,i){return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e){return{name:e.name,readTime:__PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)),bundledQuery:e.bundledQuery}}(i))}}function __PRIVATE_bundlesStore(e){return __PRIVATE_getStore(e,"bundles")}function __PRIVATE_namedQueriesStore(e){return __PRIVATE_getStore(e,"namedQueries")}class __PRIVATE_IndexedDbDocumentOverlayCache{constructor(e,i){this.serializer=e,this.userId=i}static lt(e,i){const s=i.uid||"";return new __PRIVATE_IndexedDbDocumentOverlayCache(e,s)}getOverlay(e,i){return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId,i)).next((e=>e?__PRIVATE_fromDbDocumentOverlay(this.serializer,e):null))}getOverlays(e,i){const s=__PRIVATE_newOverlayMap();return PersistencePromise.forEach(i,(i=>this.getOverlay(e,i).next((e=>{null!==e&&s.set(i,e)})))).next((()=>s))}saveOverlays(e,i,s){const o=[];return s.forEach(((s,_)=>{const h=new Overlay(i,_);o.push(this.ht(e,h))})),PersistencePromise.waitFor(o)}removeOverlaysForBatchId(e,i,s){const o=new Set;i.forEach((e=>o.add(__PRIVATE_encodeResourcePath(e.getCollectionPath()))));const _=[];return o.forEach((i=>{const o=IDBKeyRange.bound([this.userId,i,s],[this.userId,i,s+1],!1,!0);_.push(__PRIVATE_documentOverlayStore(e).j("collectionPathOverlayIndex",o))})),PersistencePromise.waitFor(_)}getOverlaysForCollection(e,i,s){const o=__PRIVATE_newOverlayMap(),_=__PRIVATE_encodeResourcePath(i),h=IDBKeyRange.bound([this.userId,_,s],[this.userId,_,Number.POSITIVE_INFINITY],!0);return __PRIVATE_documentOverlayStore(e).U("collectionPathOverlayIndex",h).next((e=>{for(const i of e){const e=__PRIVATE_fromDbDocumentOverlay(this.serializer,i);o.set(e.getKey(),e)}return o}))}getOverlaysForCollectionGroup(e,i,s,o){const _=__PRIVATE_newOverlayMap();let h;const d=IDBKeyRange.bound([this.userId,i,s],[this.userId,i,Number.POSITIVE_INFINITY],!0);return __PRIVATE_documentOverlayStore(e).J({index:"collectionGroupOverlayIndex",range:d},((e,i,s)=>{const d=__PRIVATE_fromDbDocumentOverlay(this.serializer,i);_.size()<o||d.largestBatchId===h?(_.set(d.getKey(),d),h=d.largestBatchId):s.done()})).next((()=>_))}ht(e,i){return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e,i,s){const[o,_,h]=__PRIVATE_toDbDocumentOverlayKey(i,s.mutation.key);return{userId:i,collectionPath:_,documentId:h,collectionGroup:s.mutation.key.getCollectionGroup(),largestBatchId:s.largestBatchId,overlayMutation:toMutation(e.ct,s.mutation)}}(this.serializer,this.userId,i))}}function __PRIVATE_documentOverlayStore(e){return __PRIVATE_getStore(e,"documentOverlays")}class __PRIVATE_IndexedDbGlobalsCache{Pt(e){return __PRIVATE_getStore(e,"globals")}getSessionToken(e){return this.Pt(e).get("sessionToken").next((e=>{const i=null==e?void 0:e.value;return i?ByteString.fromUint8Array(i):ByteString.EMPTY_BYTE_STRING}))}setSessionToken(e,i){return this.Pt(e).put({name:"sessionToken",value:i.toUint8Array()})}}class __PRIVATE_FirestoreIndexValueWriter{constructor(){}It(e,i){this.Tt(e,i),i.Et()}Tt(e,i){if("nullValue"in e)this.dt(i,5);else if("booleanValue"in e)this.dt(i,10),i.At(e.booleanValue?1:0);else if("integerValue"in e)this.dt(i,15),i.At(__PRIVATE_normalizeNumber(e.integerValue));else if("doubleValue"in e){const s=__PRIVATE_normalizeNumber(e.doubleValue);isNaN(s)?this.dt(i,13):(this.dt(i,15),__PRIVATE_isNegativeZero(s)?i.At(0):i.At(s))}else if("timestampValue"in e){let s=e.timestampValue;this.dt(i,20),"string"==typeof s&&(s=__PRIVATE_normalizeTimestamp(s)),i.Rt(`${s.seconds||""}`),i.At(s.nanos||0)}else if("stringValue"in e)this.Vt(e.stringValue,i),this.ft(i);else if("bytesValue"in e)this.dt(i,30),i.gt(__PRIVATE_normalizeByteString(e.bytesValue)),this.ft(i);else if("referenceValue"in e)this.yt(e.referenceValue,i);else if("geoPointValue"in e){const s=e.geoPointValue;this.dt(i,45),i.At(s.latitude||0),i.At(s.longitude||0)}else"mapValue"in e?__PRIVATE_isMaxValue(e)?this.dt(i,Number.MAX_SAFE_INTEGER):__PRIVATE_isVectorValue(e)?this.wt(e.mapValue,i):(this.St(e.mapValue,i),this.ft(i)):"arrayValue"in e?(this.bt(e.arrayValue,i),this.ft(i)):fail()}Vt(e,i){this.dt(i,25),this.Dt(e,i)}Dt(e,i){i.Rt(e)}St(e,i){const s=e.fields||{};this.dt(i,55);for(const e of Object.keys(s))this.Vt(e,i),this.Tt(s[e],i)}wt(e,i){var s,o;const _=e.fields||{};this.dt(i,53);const h="value",d=(null===(o=null===(s=_[h].arrayValue)||void 0===s?void 0:s.values)||void 0===o?void 0:o.length)||0;this.dt(i,15),i.At(__PRIVATE_normalizeNumber(d)),this.Vt(h,i),this.Tt(_[h],i)}bt(e,i){const s=e.values||[];this.dt(i,50);for(const e of s)this.Tt(e,i)}yt(e,i){this.dt(i,37),DocumentKey.fromName(e).path.forEach((e=>{this.dt(i,60),this.Dt(e,i)}))}dt(e,i){e.At(i)}ft(e){e.At(2)}}function __PRIVATE_numberOfLeadingZerosInByte(e){if(0===e)return 8;let i=0;return e>>4==0&&(i+=4,e<<=4),e>>6==0&&(i+=2,e<<=2),e>>7==0&&(i+=1),i}function __PRIVATE_unsignedNumLength(e){const i=64-function __PRIVATE_numberOfLeadingZeros(e){let i=0;for(let s=0;s<8;++s){const o=__PRIVATE_numberOfLeadingZerosInByte(255&e[s]);if(i+=o,8!==o)break}return i}(e);return Math.ceil(i/8)}__PRIVATE_FirestoreIndexValueWriter.vt=new __PRIVATE_FirestoreIndexValueWriter;class __PRIVATE_OrderedCodeWriter{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ct(e){const i=e[Symbol.iterator]();let s=i.next();for(;!s.done;)this.Ft(s.value),s=i.next();this.Mt()}xt(e){const i=e[Symbol.iterator]();let s=i.next();for(;!s.done;)this.Ot(s.value),s=i.next();this.Nt()}Lt(e){for(const i of e){const e=i.charCodeAt(0);if(e<128)this.Ft(e);else if(e<2048)this.Ft(960|e>>>6),this.Ft(128|63&e);else if(i<"\ud800"||"\udbff"<i)this.Ft(480|e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e);else{const e=i.codePointAt(0);this.Ft(240|e>>>18),this.Ft(128|63&e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e)}}this.Mt()}Bt(e){for(const i of e){const e=i.charCodeAt(0);if(e<128)this.Ot(e);else if(e<2048)this.Ot(960|e>>>6),this.Ot(128|63&e);else if(i<"\ud800"||"\udbff"<i)this.Ot(480|e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e);else{const e=i.codePointAt(0);this.Ot(240|e>>>18),this.Ot(128|63&e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e)}}this.Nt()}kt(e){const i=this.qt(e),s=__PRIVATE_unsignedNumLength(i);this.Qt(1+s),this.buffer[this.position++]=255&s;for(let e=i.length-s;e<i.length;++e)this.buffer[this.position++]=255&i[e]}Kt(e){const i=this.qt(e),s=__PRIVATE_unsignedNumLength(i);this.Qt(1+s),this.buffer[this.position++]=~(255&s);for(let e=i.length-s;e<i.length;++e)this.buffer[this.position++]=~(255&i[e])}$t(){this.Ut(255),this.Ut(255)}Wt(){this.Gt(255),this.Gt(255)}reset(){this.position=0}seed(e){this.Qt(e.length),this.buffer.set(e,this.position),this.position+=e.length}zt(){return this.buffer.slice(0,this.position)}qt(e){const i=function __PRIVATE_doubleToLongBits(e){const i=new DataView(new ArrayBuffer(8));return i.setFloat64(0,e,!1),new Uint8Array(i.buffer)}(e),s=0!=(128&i[0]);i[0]^=s?255:128;for(let e=1;e<i.length;++e)i[e]^=s?255:0;return i}Ft(e){const i=255&e;0===i?(this.Ut(0),this.Ut(255)):255===i?(this.Ut(255),this.Ut(0)):this.Ut(i)}Ot(e){const i=255&e;0===i?(this.Gt(0),this.Gt(255)):255===i?(this.Gt(255),this.Gt(0)):this.Gt(e)}Mt(){this.Ut(0),this.Ut(1)}Nt(){this.Gt(0),this.Gt(1)}Ut(e){this.Qt(1),this.buffer[this.position++]=e}Gt(e){this.Qt(1),this.buffer[this.position++]=~e}Qt(e){const i=e+this.position;if(i<=this.buffer.length)return;let s=2*this.buffer.length;s<i&&(s=i);const o=new Uint8Array(s);o.set(this.buffer),this.buffer=o}}class __PRIVATE_AscendingIndexByteEncoder{constructor(e){this.jt=e}gt(e){this.jt.Ct(e)}Rt(e){this.jt.Lt(e)}At(e){this.jt.kt(e)}Et(){this.jt.$t()}}class __PRIVATE_DescendingIndexByteEncoder{constructor(e){this.jt=e}gt(e){this.jt.xt(e)}Rt(e){this.jt.Bt(e)}At(e){this.jt.Kt(e)}Et(){this.jt.Wt()}}class __PRIVATE_IndexByteEncoder{constructor(){this.jt=new __PRIVATE_OrderedCodeWriter,this.Ht=new __PRIVATE_AscendingIndexByteEncoder(this.jt),this.Jt=new __PRIVATE_DescendingIndexByteEncoder(this.jt)}seed(e){this.jt.seed(e)}Yt(e){return 0===e?this.Ht:this.Jt}zt(){return this.jt.zt()}reset(){this.jt.reset()}}class __PRIVATE_IndexEntry{constructor(e,i,s,o){this.indexId=e,this.documentKey=i,this.arrayValue=s,this.directionalValue=o}Zt(){const e=this.directionalValue.length,i=0===e||255===this.directionalValue[e-1]?e+1:e,s=new Uint8Array(i);return s.set(this.directionalValue,0),i!==e?s.set([0],this.directionalValue.length):++s[s.length-1],new __PRIVATE_IndexEntry(this.indexId,this.documentKey,this.arrayValue,s)}}function __PRIVATE_indexEntryComparator(e,i){let s=e.indexId-i.indexId;return 0!==s?s:(s=__PRIVATE_compareByteArrays(e.arrayValue,i.arrayValue),0!==s?s:(s=__PRIVATE_compareByteArrays(e.directionalValue,i.directionalValue),0!==s?s:DocumentKey.comparator(e.documentKey,i.documentKey)))}function __PRIVATE_compareByteArrays(e,i){for(let s=0;s<e.length&&s<i.length;++s){const o=e[s]-i[s];if(0!==o)return o}return e.length-i.length}class __PRIVATE_TargetIndexMatcher{constructor(e){this.Xt=new SortedSet(((e,i)=>FieldPath$1.comparator(e.field,i.field))),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.en=e.orderBy,this.tn=[];for(const i of e.filters){const e=i;e.isInequality()?this.Xt=this.Xt.add(e):this.tn.push(e)}}get nn(){return this.Xt.size>1}rn(e){if(__PRIVATE_hardAssert(e.collectionGroup===this.collectionId),this.nn)return!1;const i=__PRIVATE_fieldIndexGetArraySegment(e);if(void 0!==i&&!this.sn(i))return!1;const s=__PRIVATE_fieldIndexGetDirectionalSegments(e);let o=new Set,_=0,h=0;for(;_<s.length&&this.sn(s[_]);++_)o=o.add(s[_].fieldPath.canonicalString());if(_===s.length)return!0;if(this.Xt.size>0){const e=this.Xt.getIterator().getNext();if(!o.has(e.field.canonicalString())){const i=s[_];if(!this.on(e,i)||!this._n(this.en[h++],i))return!1}++_}for(;_<s.length;++_){const e=s[_];if(h>=this.en.length||!this._n(this.en[h++],e))return!1}return!0}an(){if(this.nn)return null;let e=new SortedSet(FieldPath$1.comparator);const i=[];for(const s of this.tn)if(!s.field.isKeyField())if("array-contains"===s.op||"array-contains-any"===s.op)i.push(new IndexSegment(s.field,2));else{if(e.has(s.field))continue;e=e.add(s.field),i.push(new IndexSegment(s.field,0))}for(const s of this.en)s.field.isKeyField()||e.has(s.field)||(e=e.add(s.field),i.push(new IndexSegment(s.field,"asc"===s.dir?0:1)));return new FieldIndex(FieldIndex.UNKNOWN_ID,this.collectionId,i,IndexState.empty())}sn(e){for(const i of this.tn)if(this.on(i,e))return!0;return!1}on(e,i){if(void 0===e||!e.field.isEqual(i.fieldPath))return!1;const s="array-contains"===e.op||"array-contains-any"===e.op;return 2===i.kind===s}_n(e,i){return!!e.field.isEqual(i.fieldPath)&&(0===i.kind&&"asc"===e.dir||1===i.kind&&"desc"===e.dir)}}function __PRIVATE_computeInExpansion(e){var i,s;if(__PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter),e instanceof FieldFilter){if(e instanceof __PRIVATE_InFilter){const o=(null===(s=null===(i=e.value.arrayValue)||void 0===i?void 0:i.values)||void 0===s?void 0:s.map((i=>FieldFilter.create(e.field,"==",i))))||[];return CompositeFilter.create(o,"or")}return e}const o=e.filters.map((e=>__PRIVATE_computeInExpansion(e)));return CompositeFilter.create(o,e.op)}function __PRIVATE_getDnfTerms(e){if(0===e.getFilters().length)return[];const i=__PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(i)),__PRIVATE_isSingleFieldFilter(i)||__PRIVATE_isFlatConjunction(i)?[i]:i.getFilters()}function __PRIVATE_isSingleFieldFilter(e){return e instanceof FieldFilter}function __PRIVATE_isFlatConjunction(e){return e instanceof CompositeFilter&&__PRIVATE_compositeFilterIsFlatConjunction(e)}function __PRIVATE_isDisjunctiveNormalForm(e){return __PRIVATE_isSingleFieldFilter(e)||__PRIVATE_isFlatConjunction(e)||function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e){if(e instanceof CompositeFilter&&__PRIVATE_compositeFilterIsDisjunction(e)){for(const i of e.getFilters())if(!__PRIVATE_isSingleFieldFilter(i)&&!__PRIVATE_isFlatConjunction(i))return!1;return!0}return!1}(e)}function __PRIVATE_computeDistributedNormalForm(e){if(__PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter),e instanceof FieldFilter)return e;if(1===e.filters.length)return __PRIVATE_computeDistributedNormalForm(e.filters[0]);const i=e.filters.map((e=>__PRIVATE_computeDistributedNormalForm(e)));let s=CompositeFilter.create(i,e.op);return s=__PRIVATE_applyAssociation(s),__PRIVATE_isDisjunctiveNormalForm(s)?s:(__PRIVATE_hardAssert(s instanceof CompositeFilter),__PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(s)),__PRIVATE_hardAssert(s.filters.length>1),s.filters.reduce(((e,i)=>__PRIVATE_applyDistribution(e,i))))}function __PRIVATE_applyDistribution(e,i){let s;return __PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter),__PRIVATE_hardAssert(i instanceof FieldFilter||i instanceof CompositeFilter),s=e instanceof FieldFilter?i instanceof FieldFilter?function __PRIVATE_applyDistributionFieldFilters(e,i){return CompositeFilter.create([e,i],"and")}(e,i):__PRIVATE_applyDistributionFieldAndCompositeFilters(e,i):i instanceof FieldFilter?__PRIVATE_applyDistributionFieldAndCompositeFilters(i,e):function __PRIVATE_applyDistributionCompositeFilters(e,i){if(__PRIVATE_hardAssert(e.filters.length>0&&i.filters.length>0),__PRIVATE_compositeFilterIsConjunction(e)&&__PRIVATE_compositeFilterIsConjunction(i))return __PRIVATE_compositeFilterWithAddedFilters(e,i.getFilters());const s=__PRIVATE_compositeFilterIsDisjunction(e)?e:i,o=__PRIVATE_compositeFilterIsDisjunction(e)?i:e,_=s.filters.map((e=>__PRIVATE_applyDistribution(e,o)));return CompositeFilter.create(_,"or")}(e,i),__PRIVATE_applyAssociation(s)}function __PRIVATE_applyDistributionFieldAndCompositeFilters(e,i){if(__PRIVATE_compositeFilterIsConjunction(i))return __PRIVATE_compositeFilterWithAddedFilters(i,e.getFilters());{const s=i.filters.map((i=>__PRIVATE_applyDistribution(e,i)));return CompositeFilter.create(s,"or")}}function __PRIVATE_applyAssociation(e){if(__PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter),e instanceof FieldFilter)return e;const i=e.getFilters();if(1===i.length)return __PRIVATE_applyAssociation(i[0]);if(__PRIVATE_compositeFilterIsFlat(e))return e;const s=i.map((e=>__PRIVATE_applyAssociation(e))),o=[];return s.forEach((i=>{i instanceof FieldFilter?o.push(i):i instanceof CompositeFilter&&(i.op===e.op?o.push(...i.filters):o.push(i))})),1===o.length?o[0]:CompositeFilter.create(o,e.op)}class __PRIVATE_MemoryIndexManager{constructor(){this.un=new __PRIVATE_MemoryCollectionParentIndex}addToCollectionParentIndex(e,i){return this.un.add(i),PersistencePromise.resolve()}getCollectionParents(e,i){return PersistencePromise.resolve(this.un.getEntries(i))}addFieldIndex(e,i){return PersistencePromise.resolve()}deleteFieldIndex(e,i){return PersistencePromise.resolve()}deleteAllFieldIndexes(e){return PersistencePromise.resolve()}createTargetIndexes(e,i){return PersistencePromise.resolve()}getDocumentsMatchingTarget(e,i){return PersistencePromise.resolve(null)}getIndexType(e,i){return PersistencePromise.resolve(0)}getFieldIndexes(e,i){return PersistencePromise.resolve([])}getNextCollectionGroupToUpdate(e){return PersistencePromise.resolve(null)}getMinOffset(e,i){return PersistencePromise.resolve(IndexOffset.min())}getMinOffsetFromCollectionGroup(e,i){return PersistencePromise.resolve(IndexOffset.min())}updateCollectionGroup(e,i,s){return PersistencePromise.resolve()}updateIndexEntries(e,i){return PersistencePromise.resolve()}}class __PRIVATE_MemoryCollectionParentIndex{constructor(){this.index={}}add(e){const i=e.lastSegment(),s=e.popLast(),o=this.index[i]||new SortedSet(ResourcePath.comparator),_=!o.has(s);return this.index[i]=o.add(s),_}has(e){const i=e.lastSegment(),s=e.popLast(),o=this.index[i];return o&&o.has(s)}getEntries(e){return(this.index[e]||new SortedSet(ResourcePath.comparator)).toArray()}}const et=new Uint8Array(0);class __PRIVATE_IndexedDbIndexManager{constructor(e,i){this.databaseId=i,this.cn=new __PRIVATE_MemoryCollectionParentIndex,this.ln=new ObjectMap((e=>__PRIVATE_canonifyTarget(e)),((e,i)=>__PRIVATE_targetEquals(e,i))),this.uid=e.uid||""}addToCollectionParentIndex(e,i){if(!this.cn.has(i)){const s=i.lastSegment(),o=i.popLast();e.addOnCommittedListener((()=>{this.cn.add(i)}));const _={collectionId:s,parent:__PRIVATE_encodeResourcePath(o)};return __PRIVATE_collectionParentsStore(e).put(_)}return PersistencePromise.resolve()}getCollectionParents(e,i){const s=[],o=IDBKeyRange.bound([i,""],[__PRIVATE_immediateSuccessor(i),""],!1,!0);return __PRIVATE_collectionParentsStore(e).U(o).next((e=>{for(const o of e){if(o.collectionId!==i)break;s.push(__PRIVATE_decodeResourcePath(o.parent))}return s}))}addFieldIndex(e,i){const s=__PRIVATE_indexConfigurationStore(e),o=function __PRIVATE_toDbIndexConfiguration(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map((e=>[e.fieldPath.canonicalString(),e.kind]))}}(i);delete o.indexId;const _=s.add(o);if(i.indexState){const s=__PRIVATE_indexStateStore(e);return _.next((e=>{s.put(__PRIVATE_toDbIndexState(e,this.uid,i.indexState.sequenceNumber,i.indexState.offset))}))}return _.next()}deleteFieldIndex(e,i){const s=__PRIVATE_indexConfigurationStore(e),o=__PRIVATE_indexStateStore(e),_=__PRIVATE_indexEntriesStore(e);return s.delete(i.indexId).next((()=>o.delete(IDBKeyRange.bound([i.indexId],[i.indexId+1],!1,!0)))).next((()=>_.delete(IDBKeyRange.bound([i.indexId],[i.indexId+1],!1,!0))))}deleteAllFieldIndexes(e){const i=__PRIVATE_indexConfigurationStore(e),s=__PRIVATE_indexEntriesStore(e),o=__PRIVATE_indexStateStore(e);return i.j().next((()=>s.j())).next((()=>o.j()))}createTargetIndexes(e,i){return PersistencePromise.forEach(this.hn(i),(i=>this.getIndexType(e,i).next((s=>{if(0===s||1===s){const s=new __PRIVATE_TargetIndexMatcher(i).an();if(null!=s)return this.addFieldIndex(e,s)}}))))}getDocumentsMatchingTarget(e,i){const s=__PRIVATE_indexEntriesStore(e);let o=!0;const _=new Map;return PersistencePromise.forEach(this.hn(i),(i=>this.Pn(e,i).next((e=>{o&&(o=!!e),_.set(i,e)})))).next((()=>{if(o){let e=__PRIVATE_documentKeySet();const o=[];return PersistencePromise.forEach(_,((_,h)=>{__PRIVATE_logDebug("IndexedDbIndexManager",`Using index ${function __PRIVATE_fieldIndexToString(e){return`id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(",")}`}(_)} to execute ${__PRIVATE_canonifyTarget(i)}`);const d=function __PRIVATE_targetGetArrayValues(e,i){const s=__PRIVATE_fieldIndexGetArraySegment(i);if(void 0===s)return null;for(const i of __PRIVATE_targetGetFieldFiltersForPath(e,s.fieldPath))switch(i.op){case"array-contains-any":return i.value.arrayValue.values||[];case"array-contains":return[i.value]}return null}(h,_),f=function __PRIVATE_targetGetNotInValues(e,i){const s=new Map;for(const o of __PRIVATE_fieldIndexGetDirectionalSegments(i))for(const i of __PRIVATE_targetGetFieldFiltersForPath(e,o.fieldPath))switch(i.op){case"==":case"in":s.set(o.fieldPath.canonicalString(),i.value);break;case"not-in":case"!=":return s.set(o.fieldPath.canonicalString(),i.value),Array.from(s.values())}return null}(h,_),g=function __PRIVATE_targetGetLowerBound(e,i){const s=[];let o=!0;for(const _ of __PRIVATE_fieldIndexGetDirectionalSegments(i)){const i=0===_.kind?__PRIVATE_targetGetAscendingBound(e,_.fieldPath,e.startAt):__PRIVATE_targetGetDescendingBound(e,_.fieldPath,e.startAt);s.push(i.value),o&&(o=i.inclusive)}return new Bound(s,o)}(h,_),b=function __PRIVATE_targetGetUpperBound(e,i){const s=[];let o=!0;for(const _ of __PRIVATE_fieldIndexGetDirectionalSegments(i)){const i=0===_.kind?__PRIVATE_targetGetDescendingBound(e,_.fieldPath,e.endAt):__PRIVATE_targetGetAscendingBound(e,_.fieldPath,e.endAt);s.push(i.value),o&&(o=i.inclusive)}return new Bound(s,o)}(h,_),w=this.In(_,h,g),O=this.In(_,h,b),q=this.Tn(_,h,f),j=this.En(_.indexId,d,w,g.inclusive,O,b.inclusive,q);return PersistencePromise.forEach(j,(_=>s.G(_,i.limit).next((i=>{i.forEach((i=>{const s=DocumentKey.fromSegments(i.documentKey);e.has(s)||(e=e.add(s),o.push(s))}))}))))})).next((()=>o))}return PersistencePromise.resolve(null)}))}hn(e){let i=this.ln.get(e);return i||(i=0===e.filters.length?[e]:__PRIVATE_getDnfTerms(CompositeFilter.create(e.filters,"and")).map((i=>__PRIVATE_newTarget(e.path,e.collectionGroup,e.orderBy,i.getFilters(),e.limit,e.startAt,e.endAt))),this.ln.set(e,i),i)}En(e,i,s,o,_,h,d){const f=(null!=i?i.length:1)*Math.max(s.length,_.length),g=f/(null!=i?i.length:1),b=[];for(let w=0;w<f;++w){const f=i?this.dn(i[w/g]):et,O=this.An(e,f,s[w%g],o),q=this.Rn(e,f,_[w%g],h),j=d.map((i=>this.An(e,f,i,!0)));b.push(...this.createRange(O,q,j))}return b}An(e,i,s,o){const _=new __PRIVATE_IndexEntry(e,DocumentKey.empty(),i,s);return o?_:_.Zt()}Rn(e,i,s,o){const _=new __PRIVATE_IndexEntry(e,DocumentKey.empty(),i,s);return o?_.Zt():_}Pn(e,i){const s=new __PRIVATE_TargetIndexMatcher(i),o=null!=i.collectionGroup?i.collectionGroup:i.path.lastSegment();return this.getFieldIndexes(e,o).next((e=>{let i=null;for(const o of e)s.rn(o)&&(!i||o.fields.length>i.fields.length)&&(i=o);return i}))}getIndexType(e,i){let s=2;const o=this.hn(i);return PersistencePromise.forEach(o,(i=>this.Pn(e,i).next((e=>{e?0!==s&&e.fields.length<function __PRIVATE_targetGetSegmentCount(e){let i=new SortedSet(FieldPath$1.comparator),s=!1;for(const o of e.filters)for(const e of o.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?s=!0:i=i.add(e.field));for(const s of e.orderBy)s.field.isKeyField()||(i=i.add(s.field));return i.size+(s?1:0)}(i)&&(s=1):s=0})))).next((()=>function __PRIVATE_targetHasLimit(e){return null!==e.limit}(i)&&o.length>1&&2===s?1:s))}Vn(e,i){const s=new __PRIVATE_IndexByteEncoder;for(const o of __PRIVATE_fieldIndexGetDirectionalSegments(e)){const e=i.data.field(o.fieldPath);if(null==e)return null;const _=s.Yt(o.kind);__PRIVATE_FirestoreIndexValueWriter.vt.It(e,_)}return s.zt()}dn(e){const i=new __PRIVATE_IndexByteEncoder;return __PRIVATE_FirestoreIndexValueWriter.vt.It(e,i.Yt(0)),i.zt()}mn(e,i){const s=new __PRIVATE_IndexByteEncoder;return __PRIVATE_FirestoreIndexValueWriter.vt.It(__PRIVATE_refValue(this.databaseId,i),s.Yt(function __PRIVATE_fieldIndexGetKeyOrder(e){const i=__PRIVATE_fieldIndexGetDirectionalSegments(e);return 0===i.length?0:i[i.length-1].kind}(e))),s.zt()}Tn(e,i,s){if(null===s)return[];let o=[];o.push(new __PRIVATE_IndexByteEncoder);let _=0;for(const h of __PRIVATE_fieldIndexGetDirectionalSegments(e)){const e=s[_++];for(const s of o)if(this.fn(i,h.fieldPath)&&isArray(e))o=this.gn(o,h,e);else{const i=s.Yt(h.kind);__PRIVATE_FirestoreIndexValueWriter.vt.It(e,i)}}return this.pn(o)}In(e,i,s){return this.Tn(e,i,s.position)}pn(e){const i=[];for(let s=0;s<e.length;++s)i[s]=e[s].zt();return i}gn(e,i,s){const o=[...e],_=[];for(const e of s.arrayValue.values||[])for(const s of o){const o=new __PRIVATE_IndexByteEncoder;o.seed(s.zt()),__PRIVATE_FirestoreIndexValueWriter.vt.It(e,o.Yt(i.kind)),_.push(o)}return _}fn(e,i){return!!e.filters.find((e=>e instanceof FieldFilter&&e.field.isEqual(i)&&("in"===e.op||"not-in"===e.op)))}getFieldIndexes(e,i){const s=__PRIVATE_indexConfigurationStore(e),o=__PRIVATE_indexStateStore(e);return(i?s.U("collectionGroupIndex",IDBKeyRange.bound(i,i)):s.U()).next((e=>{const i=[];return PersistencePromise.forEach(e,(e=>o.get([e.indexId,this.uid]).next((s=>{i.push(function __PRIVATE_fromDbIndexConfiguration(e,i){const s=i?new IndexState(i.sequenceNumber,new IndexOffset(__PRIVATE_fromDbTimestamp(i.readTime),new DocumentKey(__PRIVATE_decodeResourcePath(i.documentKey)),i.largestBatchId)):IndexState.empty(),o=e.fields.map((([e,i])=>new IndexSegment(FieldPath$1.fromServerFormat(e),i)));return new FieldIndex(e.indexId,e.collectionGroup,o,s)}(e,s))})))).next((()=>i))}))}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next((e=>0===e.length?null:(e.sort(((e,i)=>{const s=e.indexState.sequenceNumber-i.indexState.sequenceNumber;return 0!==s?s:__PRIVATE_primitiveComparator(e.collectionGroup,i.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,i,s){const o=__PRIVATE_indexConfigurationStore(e),_=__PRIVATE_indexStateStore(e);return this.yn(e).next((e=>o.U("collectionGroupIndex",IDBKeyRange.bound(i,i)).next((i=>PersistencePromise.forEach(i,(i=>_.put(__PRIVATE_toDbIndexState(i.indexId,this.uid,e,s))))))))}updateIndexEntries(e,i){const s=new Map;return PersistencePromise.forEach(i,((i,o)=>{const _=s.get(i.collectionGroup);return(_?PersistencePromise.resolve(_):this.getFieldIndexes(e,i.collectionGroup)).next((_=>(s.set(i.collectionGroup,_),PersistencePromise.forEach(_,(s=>this.wn(e,i,s).next((i=>{const _=this.Sn(o,s);return i.isEqual(_)?PersistencePromise.resolve():this.bn(e,o,s,i,_)})))))))}))}Dn(e,i,s,o){return __PRIVATE_indexEntriesStore(e).put({indexId:o.indexId,uid:this.uid,arrayValue:o.arrayValue,directionalValue:o.directionalValue,orderedDocumentKey:this.mn(s,i.key),documentKey:i.key.path.toArray()})}vn(e,i,s,o){return __PRIVATE_indexEntriesStore(e).delete([o.indexId,this.uid,o.arrayValue,o.directionalValue,this.mn(s,i.key),i.key.path.toArray()])}wn(e,i,s){const o=__PRIVATE_indexEntriesStore(e);let _=new SortedSet(__PRIVATE_indexEntryComparator);return o.J({index:"documentKeyIndex",range:IDBKeyRange.only([s.indexId,this.uid,this.mn(s,i)])},((e,o)=>{_=_.add(new __PRIVATE_IndexEntry(s.indexId,i,o.arrayValue,o.directionalValue))})).next((()=>_))}Sn(e,i){let s=new SortedSet(__PRIVATE_indexEntryComparator);const o=this.Vn(i,e);if(null==o)return s;const _=__PRIVATE_fieldIndexGetArraySegment(i);if(null!=_){const h=e.data.field(_.fieldPath);if(isArray(h))for(const _ of h.arrayValue.values||[])s=s.add(new __PRIVATE_IndexEntry(i.indexId,e.key,this.dn(_),o))}else s=s.add(new __PRIVATE_IndexEntry(i.indexId,e.key,et,o));return s}bn(e,i,s,o,_){__PRIVATE_logDebug("IndexedDbIndexManager","Updating index entries for document '%s'",i.key);const h=[];return function __PRIVATE_diffSortedSets(e,i,s,o,_){const h=e.getIterator(),d=i.getIterator();let f=__PRIVATE_advanceIterator(h),g=__PRIVATE_advanceIterator(d);for(;f||g;){let e=!1,i=!1;if(f&&g){const o=s(f,g);o<0?i=!0:o>0&&(e=!0)}else null!=f?i=!0:e=!0;e?(o(g),g=__PRIVATE_advanceIterator(d)):i?(_(f),f=__PRIVATE_advanceIterator(h)):(f=__PRIVATE_advanceIterator(h),g=__PRIVATE_advanceIterator(d))}}(o,_,__PRIVATE_indexEntryComparator,(o=>{h.push(this.Dn(e,i,s,o))}),(o=>{h.push(this.vn(e,i,s,o))})),PersistencePromise.waitFor(h)}yn(e){let i=1;return __PRIVATE_indexStateStore(e).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((e,s,o)=>{o.done(),i=s.sequenceNumber+1})).next((()=>i))}createRange(e,i,s){s=s.sort(((e,i)=>__PRIVATE_indexEntryComparator(e,i))).filter(((e,i,s)=>!i||0!==__PRIVATE_indexEntryComparator(e,s[i-1])));const o=[];o.push(e);for(const _ of s){const s=__PRIVATE_indexEntryComparator(_,e),h=__PRIVATE_indexEntryComparator(_,i);if(0===s)o[0]=e.Zt();else if(s>0&&h<0)o.push(_),o.push(_.Zt());else if(h>0)break}o.push(i);const _=[];for(let e=0;e<o.length;e+=2){if(this.Cn(o[e],o[e+1]))return[];const i=[o[e].indexId,this.uid,o[e].arrayValue,o[e].directionalValue,et,[]],s=[o[e+1].indexId,this.uid,o[e+1].arrayValue,o[e+1].directionalValue,et,[]];_.push(IDBKeyRange.bound(i,s))}return _}Cn(e,i){return __PRIVATE_indexEntryComparator(e,i)>0}getMinOffsetFromCollectionGroup(e,i){return this.getFieldIndexes(e,i).next(__PRIVATE_getMinOffsetFromFieldIndexes)}getMinOffset(e,i){return PersistencePromise.mapArray(this.hn(i),(i=>this.Pn(e,i).next((e=>e||fail())))).next(__PRIVATE_getMinOffsetFromFieldIndexes)}}function __PRIVATE_collectionParentsStore(e){return __PRIVATE_getStore(e,"collectionParents")}function __PRIVATE_indexEntriesStore(e){return __PRIVATE_getStore(e,"indexEntries")}function __PRIVATE_indexConfigurationStore(e){return __PRIVATE_getStore(e,"indexConfiguration")}function __PRIVATE_indexStateStore(e){return __PRIVATE_getStore(e,"indexState")}function __PRIVATE_getMinOffsetFromFieldIndexes(e){__PRIVATE_hardAssert(0!==e.length);let i=e[0].indexState.offset,s=i.largestBatchId;for(let o=1;o<e.length;o++){const _=e[o].indexState.offset;__PRIVATE_indexOffsetComparator(_,i)<0&&(i=_),s<_.largestBatchId&&(s=_.largestBatchId)}return new IndexOffset(i.readTime,i.documentKey,s)}const tt={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class LruParams{constructor(e,i,s){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=i,this.maximumSequenceNumbersToCollect=s}static withCacheSize(e){return new LruParams(e,LruParams.DEFAULT_COLLECTION_PERCENTILE,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function removeMutationBatch(e,i,s){const o=e.store("mutations"),_=e.store("documentMutations"),h=[],d=IDBKeyRange.only(s.batchId);let f=0;const g=o.J({range:d},((e,i,s)=>(f++,s.delete())));h.push(g.next((()=>{__PRIVATE_hardAssert(1===f)})));const b=[];for(const e of s.mutations){const o=__PRIVATE_newDbDocumentMutationKey(i,e.key.path,s.batchId);h.push(_.delete(o)),b.push(e.key)}return PersistencePromise.waitFor(h).next((()=>b))}function __PRIVATE_dbDocumentSize(e){if(!e)return 0;let i;if(e.document)i=e.document;else if(e.unknownDocument)i=e.unknownDocument;else{if(!e.noDocument)throw fail();i=e.noDocument}return JSON.stringify(i).length}LruParams.DEFAULT_COLLECTION_PERCENTILE=10,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,LruParams.DEFAULT=new LruParams(41943040,LruParams.DEFAULT_COLLECTION_PERCENTILE,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),LruParams.DISABLED=new LruParams(-1,0,0);class __PRIVATE_IndexedDbMutationQueue{constructor(e,i,s,o){this.userId=e,this.serializer=i,this.indexManager=s,this.referenceDelegate=o,this.Fn={}}static lt(e,i,s,o){__PRIVATE_hardAssert(""!==e.uid);const _=e.isAuthenticated()?e.uid:"";return new __PRIVATE_IndexedDbMutationQueue(_,i,s,o)}checkEmpty(e){let i=!0;const s=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return __PRIVATE_mutationsStore(e).J({index:"userMutationsIndex",range:s},((e,s,o)=>{i=!1,o.done()})).next((()=>i))}addMutationBatch(e,i,s,o){const _=__PRIVATE_documentMutationsStore(e),h=__PRIVATE_mutationsStore(e);return h.add({}).next((d=>{__PRIVATE_hardAssert("number"==typeof d);const f=new MutationBatch(d,i,s,o),g=function __PRIVATE_toDbMutationBatch(e,i,s){const o=s.baseMutations.map((i=>toMutation(e.ct,i))),_=s.mutations.map((i=>toMutation(e.ct,i)));return{userId:i,batchId:s.batchId,localWriteTimeMs:s.localWriteTime.toMillis(),baseMutations:o,mutations:_}}(this.serializer,this.userId,f),b=[];let w=new SortedSet(((e,i)=>__PRIVATE_primitiveComparator(e.canonicalString(),i.canonicalString())));for(const e of o){const i=__PRIVATE_newDbDocumentMutationKey(this.userId,e.key.path,d);w=w.add(e.key.path.popLast()),b.push(h.put(g)),b.push(_.put(i,ge))}return w.forEach((i=>{b.push(this.indexManager.addToCollectionParentIndex(e,i))})),e.addOnCommittedListener((()=>{this.Fn[d]=f.keys()})),PersistencePromise.waitFor(b).next((()=>f))}))}lookupMutationBatch(e,i){return __PRIVATE_mutationsStore(e).get(i).next((e=>e?(__PRIVATE_hardAssert(e.userId===this.userId),__PRIVATE_fromDbMutationBatch(this.serializer,e)):null))}Mn(e,i){return this.Fn[i]?PersistencePromise.resolve(this.Fn[i]):this.lookupMutationBatch(e,i).next((e=>{if(e){const s=e.keys();return this.Fn[i]=s,s}return null}))}getNextMutationBatchAfterBatchId(e,i){const s=i+1,o=IDBKeyRange.lowerBound([this.userId,s]);let _=null;return __PRIVATE_mutationsStore(e).J({index:"userMutationsIndex",range:o},((e,i,o)=>{i.userId===this.userId&&(__PRIVATE_hardAssert(i.batchId>=s),_=__PRIVATE_fromDbMutationBatch(this.serializer,i)),o.done()})).next((()=>_))}getHighestUnacknowledgedBatchId(e){const i=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let s=-1;return __PRIVATE_mutationsStore(e).J({index:"userMutationsIndex",range:i,reverse:!0},((e,i,o)=>{s=i.batchId,o.done()})).next((()=>s))}getAllMutationBatches(e){const i=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return __PRIVATE_mutationsStore(e).U("userMutationsIndex",i).next((e=>e.map((e=>__PRIVATE_fromDbMutationBatch(this.serializer,e)))))}getAllMutationBatchesAffectingDocumentKey(e,i){const s=__PRIVATE_newDbDocumentMutationPrefixForPath(this.userId,i.path),o=IDBKeyRange.lowerBound(s),_=[];return __PRIVATE_documentMutationsStore(e).J({range:o},((s,o,h)=>{const[d,f,g]=s,b=__PRIVATE_decodeResourcePath(f);if(d===this.userId&&i.path.isEqual(b))return __PRIVATE_mutationsStore(e).get(g).next((e=>{if(!e)throw fail();__PRIVATE_hardAssert(e.userId===this.userId),_.push(__PRIVATE_fromDbMutationBatch(this.serializer,e))}));h.done()})).next((()=>_))}getAllMutationBatchesAffectingDocumentKeys(e,i){let s=new SortedSet(__PRIVATE_primitiveComparator);const o=[];return i.forEach((i=>{const _=__PRIVATE_newDbDocumentMutationPrefixForPath(this.userId,i.path),h=IDBKeyRange.lowerBound(_),d=__PRIVATE_documentMutationsStore(e).J({range:h},((e,o,_)=>{const[h,d,f]=e,g=__PRIVATE_decodeResourcePath(d);h===this.userId&&i.path.isEqual(g)?s=s.add(f):_.done()}));o.push(d)})),PersistencePromise.waitFor(o).next((()=>this.xn(e,s)))}getAllMutationBatchesAffectingQuery(e,i){const s=i.path,o=s.length+1,_=__PRIVATE_newDbDocumentMutationPrefixForPath(this.userId,s),h=IDBKeyRange.lowerBound(_);let d=new SortedSet(__PRIVATE_primitiveComparator);return __PRIVATE_documentMutationsStore(e).J({range:h},((e,i,_)=>{const[h,f,g]=e,b=__PRIVATE_decodeResourcePath(f);h===this.userId&&s.isPrefixOf(b)?b.length===o&&(d=d.add(g)):_.done()})).next((()=>this.xn(e,d)))}xn(e,i){const s=[],o=[];return i.forEach((i=>{o.push(__PRIVATE_mutationsStore(e).get(i).next((e=>{if(null===e)throw fail();__PRIVATE_hardAssert(e.userId===this.userId),s.push(__PRIVATE_fromDbMutationBatch(this.serializer,e))})))})),PersistencePromise.waitFor(o).next((()=>s))}removeMutationBatch(e,i){return removeMutationBatch(e._e,this.userId,i).next((s=>(e.addOnCommittedListener((()=>{this.On(i.batchId)})),PersistencePromise.forEach(s,(i=>this.referenceDelegate.markPotentiallyOrphaned(e,i))))))}On(e){delete this.Fn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next((i=>{if(!i)return PersistencePromise.resolve();const s=IDBKeyRange.lowerBound(function __PRIVATE_newDbDocumentMutationPrefixForUser(e){return[e]}(this.userId)),o=[];return __PRIVATE_documentMutationsStore(e).J({range:s},((e,i,s)=>{if(e[0]===this.userId){const i=__PRIVATE_decodeResourcePath(e[1]);o.push(i)}else s.done()})).next((()=>{__PRIVATE_hardAssert(0===o.length)}))}))}containsKey(e,i){return __PRIVATE_mutationQueueContainsKey(e,this.userId,i)}Nn(e){return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function __PRIVATE_mutationQueueContainsKey(e,i,s){const o=__PRIVATE_newDbDocumentMutationPrefixForPath(i,s.path),_=o[1],h=IDBKeyRange.lowerBound(o);let d=!1;return __PRIVATE_documentMutationsStore(e).J({range:h,H:!0},((e,s,o)=>{const[h,f,g]=e;h===i&&f===_&&(d=!0),o.done()})).next((()=>d))}function __PRIVATE_mutationsStore(e){return __PRIVATE_getStore(e,"mutations")}function __PRIVATE_documentMutationsStore(e){return __PRIVATE_getStore(e,"documentMutations")}function __PRIVATE_mutationQueuesStore(e){return __PRIVATE_getStore(e,"mutationQueues")}class __PRIVATE_TargetIdGenerator{constructor(e){this.Ln=e}next(){return this.Ln+=2,this.Ln}static Bn(){return new __PRIVATE_TargetIdGenerator(0)}static kn(){return new __PRIVATE_TargetIdGenerator(-1)}}class __PRIVATE_IndexedDbTargetCache{constructor(e,i){this.referenceDelegate=e,this.serializer=i}allocateTargetId(e){return this.qn(e).next((i=>{const s=new __PRIVATE_TargetIdGenerator(i.highestTargetId);return i.highestTargetId=s.next(),this.Qn(e,i).next((()=>i.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.qn(e).next((e=>SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(e){return this.qn(e).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(e,i,s){return this.qn(e).next((o=>(o.highestListenSequenceNumber=i,s&&(o.lastRemoteSnapshotVersion=s.toTimestamp()),i>o.highestListenSequenceNumber&&(o.highestListenSequenceNumber=i),this.Qn(e,o))))}addTargetData(e,i){return this.Kn(e,i).next((()=>this.qn(e).next((s=>(s.targetCount+=1,this.$n(i,s),this.Qn(e,s))))))}updateTargetData(e,i){return this.Kn(e,i)}removeTargetData(e,i){return this.removeMatchingKeysForTargetId(e,i.targetId).next((()=>__PRIVATE_targetsStore(e).delete(i.targetId))).next((()=>this.qn(e))).next((i=>(__PRIVATE_hardAssert(i.targetCount>0),i.targetCount-=1,this.Qn(e,i))))}removeTargets(e,i,s){let o=0;const _=[];return __PRIVATE_targetsStore(e).J(((h,d)=>{const f=__PRIVATE_fromDbTarget(d);f.sequenceNumber<=i&&null===s.get(f.targetId)&&(o++,_.push(this.removeTargetData(e,f)))})).next((()=>PersistencePromise.waitFor(_))).next((()=>o))}forEachTarget(e,i){return __PRIVATE_targetsStore(e).J(((e,s)=>{const o=__PRIVATE_fromDbTarget(s);i(o)}))}qn(e){return __PRIVATE_globalTargetStore(e).get("targetGlobalKey").next((e=>(__PRIVATE_hardAssert(null!==e),e)))}Qn(e,i){return __PRIVATE_globalTargetStore(e).put("targetGlobalKey",i)}Kn(e,i){return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer,i))}$n(e,i){let s=!1;return e.targetId>i.highestTargetId&&(i.highestTargetId=e.targetId,s=!0),e.sequenceNumber>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=e.sequenceNumber,s=!0),s}getTargetCount(e){return this.qn(e).next((e=>e.targetCount))}getTargetData(e,i){const s=__PRIVATE_canonifyTarget(i),o=IDBKeyRange.bound([s,Number.NEGATIVE_INFINITY],[s,Number.POSITIVE_INFINITY]);let _=null;return __PRIVATE_targetsStore(e).J({range:o,index:"queryTargetsIndex"},((e,s,o)=>{const h=__PRIVATE_fromDbTarget(s);__PRIVATE_targetEquals(i,h.target)&&(_=h,o.done())})).next((()=>_))}addMatchingKeys(e,i,s){const o=[],_=__PRIVATE_documentTargetStore(e);return i.forEach((i=>{const h=__PRIVATE_encodeResourcePath(i.path);o.push(_.put({targetId:s,path:h})),o.push(this.referenceDelegate.addReference(e,s,i))})),PersistencePromise.waitFor(o)}removeMatchingKeys(e,i,s){const o=__PRIVATE_documentTargetStore(e);return PersistencePromise.forEach(i,(i=>{const _=__PRIVATE_encodeResourcePath(i.path);return PersistencePromise.waitFor([o.delete([s,_]),this.referenceDelegate.removeReference(e,s,i)])}))}removeMatchingKeysForTargetId(e,i){const s=__PRIVATE_documentTargetStore(e),o=IDBKeyRange.bound([i],[i+1],!1,!0);return s.delete(o)}getMatchingKeysForTargetId(e,i){const s=IDBKeyRange.bound([i],[i+1],!1,!0),o=__PRIVATE_documentTargetStore(e);let _=__PRIVATE_documentKeySet();return o.J({range:s,H:!0},((e,i,s)=>{const o=__PRIVATE_decodeResourcePath(e[1]),h=new DocumentKey(o);_=_.add(h)})).next((()=>_))}containsKey(e,i){const s=__PRIVATE_encodeResourcePath(i.path),o=IDBKeyRange.bound([s],[__PRIVATE_immediateSuccessor(s)],!1,!0);let _=0;return __PRIVATE_documentTargetStore(e).J({index:"documentTargetsIndex",H:!0,range:o},(([e,i],s,o)=>{0!==e&&(_++,o.done())})).next((()=>_>0))}ot(e,i){return __PRIVATE_targetsStore(e).get(i).next((e=>e?__PRIVATE_fromDbTarget(e):null))}}function __PRIVATE_targetsStore(e){return __PRIVATE_getStore(e,"targets")}function __PRIVATE_globalTargetStore(e){return __PRIVATE_getStore(e,"targetGlobal")}function __PRIVATE_documentTargetStore(e){return __PRIVATE_getStore(e,"targetDocuments")}function __PRIVATE_bufferEntryComparator([e,i],[s,o]){const _=__PRIVATE_primitiveComparator(e,s);return 0===_?__PRIVATE_primitiveComparator(i,o):_}class __PRIVATE_RollingSequenceNumberBuffer{constructor(e){this.Un=e,this.buffer=new SortedSet(__PRIVATE_bufferEntryComparator),this.Wn=0}Gn(){return++this.Wn}zn(e){const i=[e,this.Gn()];if(this.buffer.size<this.Un)this.buffer=this.buffer.add(i);else{const e=this.buffer.last();__PRIVATE_bufferEntryComparator(i,e)<0&&(this.buffer=this.buffer.delete(e).add(i))}}get maxValue(){return this.buffer.last()[0]}}class __PRIVATE_LruScheduler{constructor(e,i,s){this.garbageCollector=e,this.asyncQueue=i,this.localStore=s,this.jn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Hn(6e4)}stop(){this.jn&&(this.jn.cancel(),this.jn=null)}get started(){return null!==this.jn}Hn(e){__PRIVATE_logDebug("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.jn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.jn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){__PRIVATE_isIndexedDbTransactionError(e)?__PRIVATE_logDebug("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}await this.Hn(3e5)}))}}class __PRIVATE_LruGarbageCollectorImpl{constructor(e,i){this.Jn=e,this.params=i}calculateTargetCount(e,i){return this.Jn.Yn(e).next((e=>Math.floor(i/100*e)))}nthSequenceNumber(e,i){if(0===i)return PersistencePromise.resolve(__PRIVATE_ListenSequence.oe);const s=new __PRIVATE_RollingSequenceNumberBuffer(i);return this.Jn.forEachTarget(e,(e=>s.zn(e.sequenceNumber))).next((()=>this.Jn.Zn(e,(e=>s.zn(e))))).next((()=>s.maxValue))}removeTargets(e,i,s){return this.Jn.removeTargets(e,i,s)}removeOrphanedDocuments(e,i){return this.Jn.removeOrphanedDocuments(e,i)}collect(e,i){return-1===this.params.cacheSizeCollectionThreshold?(__PRIVATE_logDebug("LruGarbageCollector","Garbage collection skipped; disabled"),PersistencePromise.resolve(tt)):this.getCacheSize(e).next((s=>s<this.params.cacheSizeCollectionThreshold?(__PRIVATE_logDebug("LruGarbageCollector",`Garbage collection skipped; Cache size ${s} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),tt):this.Xn(e,i)))}getCacheSize(e){return this.Jn.getCacheSize(e)}Xn(e,i){let s,o,_,h,d,g,b;const w=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((i=>(i>this.params.maximumSequenceNumbersToCollect?(__PRIVATE_logDebug("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${i}`),o=this.params.maximumSequenceNumbersToCollect):o=i,h=Date.now(),this.nthSequenceNumber(e,o)))).next((o=>(s=o,d=Date.now(),this.removeTargets(e,s,i)))).next((i=>(_=i,g=Date.now(),this.removeOrphanedDocuments(e,s)))).next((e=>(b=Date.now(),__PRIVATE_getLogLevel()<=f.DEBUG&&__PRIVATE_logDebug("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${h-w}ms\n\tDetermined least recently used ${o} in `+(d-h)+"ms\n"+`\tRemoved ${_} targets in `+(g-d)+"ms\n"+`\tRemoved ${e} documents in `+(b-g)+"ms\n"+`Total Duration: ${b-w}ms`),PersistencePromise.resolve({didRun:!0,sequenceNumbersCollected:o,targetsRemoved:_,documentsRemoved:e}))))}}function __PRIVATE_newLruGarbageCollector(e,i){return new __PRIVATE_LruGarbageCollectorImpl(e,i)}class __PRIVATE_IndexedDbLruDelegateImpl{constructor(e,i){this.db=e,this.garbageCollector=__PRIVATE_newLruGarbageCollector(this,i)}Yn(e){const i=this.er(e);return this.db.getTargetCache().getTargetCount(e).next((e=>i.next((i=>e+i))))}er(e){let i=0;return this.Zn(e,(e=>{i++})).next((()=>i))}forEachTarget(e,i){return this.db.getTargetCache().forEachTarget(e,i)}Zn(e,i){return this.tr(e,((e,s)=>i(s)))}addReference(e,i,s){return __PRIVATE_writeSentinelKey(e,s)}removeReference(e,i,s){return __PRIVATE_writeSentinelKey(e,s)}removeTargets(e,i,s){return this.db.getTargetCache().removeTargets(e,i,s)}markPotentiallyOrphaned(e,i){return __PRIVATE_writeSentinelKey(e,i)}nr(e,i){return function __PRIVATE_mutationQueuesContainKey(e,i){let s=!1;return __PRIVATE_mutationQueuesStore(e).Y((o=>__PRIVATE_mutationQueueContainsKey(e,o,i).next((e=>(e&&(s=!0),PersistencePromise.resolve(!e)))))).next((()=>s))}(e,i)}removeOrphanedDocuments(e,i){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),o=[];let _=0;return this.tr(e,((h,d)=>{if(d<=i){const i=this.nr(e,h).next((i=>{if(!i)return _++,s.getEntry(e,h).next((()=>(s.removeEntry(h,SnapshotVersion.min()),__PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e){return[0,__PRIVATE_encodeResourcePath(e.path)]}(h)))))}));o.push(i)}})).next((()=>PersistencePromise.waitFor(o))).next((()=>s.apply(e))).next((()=>_))}removeTarget(e,i){const s=i.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,s)}updateLimboDocument(e,i){return __PRIVATE_writeSentinelKey(e,i)}tr(e,i){const s=__PRIVATE_documentTargetStore(e);let o,_=__PRIVATE_ListenSequence.oe;return s.J({index:"documentTargetsIndex"},(([e,s],{path:h,sequenceNumber:d})=>{0===e?(_!==__PRIVATE_ListenSequence.oe&&i(new DocumentKey(__PRIVATE_decodeResourcePath(o)),_),_=d,o=h):_=__PRIVATE_ListenSequence.oe})).next((()=>{_!==__PRIVATE_ListenSequence.oe&&i(new DocumentKey(__PRIVATE_decodeResourcePath(o)),_)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function __PRIVATE_writeSentinelKey(e,i){return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e,i){return{targetId:0,path:__PRIVATE_encodeResourcePath(e.path),sequenceNumber:i}}(i,e.currentSequenceNumber))}class RemoteDocumentChangeBuffer{constructor(){this.changes=new ObjectMap((e=>e.toString()),((e,i)=>e.isEqual(i))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,i){this.assertNotApplied(),this.changes.set(e,MutableDocument.newInvalidDocument(e).setReadTime(i))}getEntry(e,i){this.assertNotApplied();const s=this.changes.get(i);return void 0!==s?PersistencePromise.resolve(s):this.getFromCache(e,i)}getEntries(e,i){return this.getAllFromCache(e,i)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class __PRIVATE_IndexedDbRemoteDocumentCacheImpl{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,i,s){return __PRIVATE_remoteDocumentsStore(e).put(s)}removeEntry(e,i,s){return __PRIVATE_remoteDocumentsStore(e).delete(function __PRIVATE_dbReadTimeKey(e,i){const s=e.path.toArray();return[s.slice(0,s.length-2),s[s.length-2],__PRIVATE_toDbTimestampKey(i),s[s.length-1]]}(i,s))}updateMetadata(e,i){return this.getMetadata(e).next((s=>(s.byteSize+=i,this.rr(e,s))))}getEntry(e,i){let s=MutableDocument.newInvalidDocument(i);return __PRIVATE_remoteDocumentsStore(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(__PRIVATE_dbKey(i))},((e,o)=>{s=this.ir(i,o)})).next((()=>s))}sr(e,i){let s={size:0,document:MutableDocument.newInvalidDocument(i)};return __PRIVATE_remoteDocumentsStore(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(__PRIVATE_dbKey(i))},((e,o)=>{s={document:this.ir(i,o),size:__PRIVATE_dbDocumentSize(o)}})).next((()=>s))}getEntries(e,i){let s=__PRIVATE_mutableDocumentMap();return this._r(e,i,((e,i)=>{const o=this.ir(e,i);s=s.insert(e,o)})).next((()=>s))}ar(e,i){let s=__PRIVATE_mutableDocumentMap(),o=new SortedMap(DocumentKey.comparator);return this._r(e,i,((e,i)=>{const _=this.ir(e,i);s=s.insert(e,_),o=o.insert(e,__PRIVATE_dbDocumentSize(i))})).next((()=>({documents:s,ur:o})))}_r(e,i,s){if(i.isEmpty())return PersistencePromise.resolve();let o=new SortedSet(__PRIVATE_dbKeyComparator);i.forEach((e=>o=o.add(e)));const _=IDBKeyRange.bound(__PRIVATE_dbKey(o.first()),__PRIVATE_dbKey(o.last())),h=o.getIterator();let d=h.getNext();return __PRIVATE_remoteDocumentsStore(e).J({index:"documentKeyIndex",range:_},((e,i,o)=>{const _=DocumentKey.fromSegments([...i.prefixPath,i.collectionGroup,i.documentId]);for(;d&&__PRIVATE_dbKeyComparator(d,_)<0;)s(d,null),d=h.getNext();d&&d.isEqual(_)&&(s(d,i),d=h.hasNext()?h.getNext():null),d?o.$(__PRIVATE_dbKey(d)):o.done()})).next((()=>{for(;d;)s(d,null),d=h.hasNext()?h.getNext():null}))}getDocumentsMatchingQuery(e,i,s,o,_){const h=i.path,d=[h.popLast().toArray(),h.lastSegment(),__PRIVATE_toDbTimestampKey(s.readTime),s.documentKey.path.isEmpty()?"":s.documentKey.path.lastSegment()],f=[h.popLast().toArray(),h.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return __PRIVATE_remoteDocumentsStore(e).U(IDBKeyRange.bound(d,f,!0)).next((e=>{null==_||_.incrementDocumentReadCount(e.length);let s=__PRIVATE_mutableDocumentMap();for(const _ of e){const e=this.ir(DocumentKey.fromSegments(_.prefixPath.concat(_.collectionGroup,_.documentId)),_);e.isFoundDocument()&&(__PRIVATE_queryMatches(i,e)||o.has(e.key))&&(s=s.insert(e.key,e))}return s}))}getAllFromCollectionGroup(e,i,s,o){let _=__PRIVATE_mutableDocumentMap();const h=__PRIVATE_dbCollectionGroupKey(i,s),d=__PRIVATE_dbCollectionGroupKey(i,IndexOffset.max());return __PRIVATE_remoteDocumentsStore(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(h,d,!0)},((e,i,s)=>{const h=this.ir(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);_=_.insert(h.key,h),_.size===o&&s.done()})).next((()=>_))}newChangeBuffer(e){return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return __PRIVATE_documentGlobalStore(e).get("remoteDocumentGlobalKey").next((e=>(__PRIVATE_hardAssert(!!e),e)))}rr(e,i){return __PRIVATE_documentGlobalStore(e).put("remoteDocumentGlobalKey",i)}ir(e,i){if(i){const e=function __PRIVATE_fromDbRemoteDocument(e,i){let s;if(i.document)s=__PRIVATE_fromDocument(e.ct,i.document,!!i.hasCommittedMutations);else if(i.noDocument){const e=DocumentKey.fromSegments(i.noDocument.path),o=__PRIVATE_fromDbTimestamp(i.noDocument.readTime);s=MutableDocument.newNoDocument(e,o),i.hasCommittedMutations&&s.setHasCommittedMutations()}else{if(!i.unknownDocument)return fail();{const e=DocumentKey.fromSegments(i.unknownDocument.path),o=__PRIVATE_fromDbTimestamp(i.unknownDocument.version);s=MutableDocument.newUnknownDocument(e,o)}}return i.readTime&&s.setReadTime(function __PRIVATE_fromDbTimestampKey(e){const i=new Timestamp(e[0],e[1]);return SnapshotVersion.fromTimestamp(i)}(i.readTime)),s}(this.serializer,i);if(!e.isNoDocument()||!e.version.isEqual(SnapshotVersion.min()))return e}return MutableDocument.newInvalidDocument(e)}}function __PRIVATE_newIndexedDbRemoteDocumentCache(e){return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e)}class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer{constructor(e,i){super(),this.cr=e,this.trackRemovals=i,this.lr=new ObjectMap((e=>e.toString()),((e,i)=>e.isEqual(i)))}applyChanges(e){const i=[];let s=0,o=new SortedSet(((e,i)=>__PRIVATE_primitiveComparator(e.canonicalString(),i.canonicalString())));return this.changes.forEach(((_,h)=>{const d=this.lr.get(_);if(i.push(this.cr.removeEntry(e,_,d.readTime)),h.isValidDocument()){const f=__PRIVATE_toDbRemoteDocument(this.cr.serializer,h);o=o.add(_.path.popLast());const g=__PRIVATE_dbDocumentSize(f);s+=g-d.size,i.push(this.cr.addEntry(e,_,f))}else if(s-=d.size,this.trackRemovals){const s=__PRIVATE_toDbRemoteDocument(this.cr.serializer,h.convertToNoDocument(SnapshotVersion.min()));i.push(this.cr.addEntry(e,_,s))}})),o.forEach((s=>{i.push(this.cr.indexManager.addToCollectionParentIndex(e,s))})),i.push(this.cr.updateMetadata(e,s)),PersistencePromise.waitFor(i)}getFromCache(e,i){return this.cr.sr(e,i).next((e=>(this.lr.set(i,{size:e.size,readTime:e.document.readTime}),e.document)))}getAllFromCache(e,i){return this.cr.ar(e,i).next((({documents:e,ur:i})=>(i.forEach(((i,s)=>{this.lr.set(i,{size:s,readTime:e.get(i).readTime})})),e)))}}function __PRIVATE_documentGlobalStore(e){return __PRIVATE_getStore(e,"remoteDocumentGlobal")}function __PRIVATE_remoteDocumentsStore(e){return __PRIVATE_getStore(e,"remoteDocumentsV14")}function __PRIVATE_dbKey(e){const i=e.path.toArray();return[i.slice(0,i.length-2),i[i.length-2],i[i.length-1]]}function __PRIVATE_dbCollectionGroupKey(e,i){const s=i.documentKey.path.toArray();return[e,__PRIVATE_toDbTimestampKey(i.readTime),s.slice(0,s.length-2),s.length>0?s[s.length-1]:""]}function __PRIVATE_dbKeyComparator(e,i){const s=e.path.toArray(),o=i.path.toArray();let _=0;for(let e=0;e<s.length-2&&e<o.length-2;++e)if(_=__PRIVATE_primitiveComparator(s[e],o[e]),_)return _;return _=__PRIVATE_primitiveComparator(s.length,o.length),_||(_=__PRIVATE_primitiveComparator(s[s.length-2],o[o.length-2]),_||__PRIVATE_primitiveComparator(s[s.length-1],o[o.length-1]))}class OverlayedDocument{constructor(e,i){this.overlayedDocument=e,this.mutatedFields=i}}class LocalDocumentsView{constructor(e,i,s,o){this.remoteDocumentCache=e,this.mutationQueue=i,this.documentOverlayCache=s,this.indexManager=o}getDocument(e,i){let s=null;return this.documentOverlayCache.getOverlay(e,i).next((o=>(s=o,this.remoteDocumentCache.getEntry(e,i)))).next((e=>(null!==s&&__PRIVATE_mutationApplyToLocalView(s.mutation,e,FieldMask.empty(),Timestamp.now()),e)))}getDocuments(e,i){return this.remoteDocumentCache.getEntries(e,i).next((i=>this.getLocalViewOfDocuments(e,i,__PRIVATE_documentKeySet()).next((()=>i))))}getLocalViewOfDocuments(e,i,s=__PRIVATE_documentKeySet()){const o=__PRIVATE_newOverlayMap();return this.populateOverlays(e,o,i).next((()=>this.computeViews(e,i,o,s).next((e=>{let i=documentMap();return e.forEach(((e,s)=>{i=i.insert(e,s.overlayedDocument)})),i}))))}getOverlayedDocuments(e,i){const s=__PRIVATE_newOverlayMap();return this.populateOverlays(e,s,i).next((()=>this.computeViews(e,i,s,__PRIVATE_documentKeySet())))}populateOverlays(e,i,s){const o=[];return s.forEach((e=>{i.has(e)||o.push(e)})),this.documentOverlayCache.getOverlays(e,o).next((e=>{e.forEach(((e,s)=>{i.set(e,s)}))}))}computeViews(e,i,s,o){let _=__PRIVATE_mutableDocumentMap();const h=__PRIVATE_newDocumentKeyMap(),d=function __PRIVATE_newOverlayedDocumentMap(){return __PRIVATE_newDocumentKeyMap()}();return i.forEach(((e,i)=>{const d=s.get(i.key);o.has(i.key)&&(void 0===d||d.mutation instanceof __PRIVATE_PatchMutation)?_=_.insert(i.key,i):void 0!==d?(h.set(i.key,d.mutation.getFieldMask()),__PRIVATE_mutationApplyToLocalView(d.mutation,i,d.mutation.getFieldMask(),Timestamp.now())):h.set(i.key,FieldMask.empty())})),this.recalculateAndSaveOverlays(e,_).next((e=>(e.forEach(((e,i)=>h.set(e,i))),i.forEach(((e,i)=>{var s;return d.set(e,new OverlayedDocument(i,null!==(s=h.get(e))&&void 0!==s?s:null))})),d)))}recalculateAndSaveOverlays(e,i){const s=__PRIVATE_newDocumentKeyMap();let o=new SortedMap(((e,i)=>e-i)),_=__PRIVATE_documentKeySet();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,i).next((e=>{for(const _ of e)_.keys().forEach((e=>{const h=i.get(e);if(null===h)return;let d=s.get(e)||FieldMask.empty();d=_.applyToLocalView(h,d),s.set(e,d);const f=(o.get(_.batchId)||__PRIVATE_documentKeySet()).add(e);o=o.insert(_.batchId,f)}))})).next((()=>{const h=[],d=o.getReverseIterator();for(;d.hasNext();){const o=d.getNext(),f=o.key,g=o.value,b=__PRIVATE_newMutationMap();g.forEach((e=>{if(!_.has(e)){const o=__PRIVATE_calculateOverlayMutation(i.get(e),s.get(e));null!==o&&b.set(e,o),_=_.add(e)}})),h.push(this.documentOverlayCache.saveOverlays(e,f,b))}return PersistencePromise.waitFor(h)})).next((()=>s))}recalculateAndSaveOverlaysForDocumentKeys(e,i){return this.remoteDocumentCache.getEntries(e,i).next((i=>this.recalculateAndSaveOverlays(e,i)))}getDocumentsMatchingQuery(e,i,s,o){return function __PRIVATE_isDocumentQuery$1(e){return DocumentKey.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(i)?this.getDocumentsMatchingDocumentQuery(e,i.path):__PRIVATE_isCollectionGroupQuery(i)?this.getDocumentsMatchingCollectionGroupQuery(e,i,s,o):this.getDocumentsMatchingCollectionQuery(e,i,s,o)}getNextDocuments(e,i,s,o){return this.remoteDocumentCache.getAllFromCollectionGroup(e,i,s,o).next((_=>{const h=o-_.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,i,s.largestBatchId,o-_.size):PersistencePromise.resolve(__PRIVATE_newOverlayMap());let d=-1,f=_;return h.next((i=>PersistencePromise.forEach(i,((i,s)=>(d<s.largestBatchId&&(d=s.largestBatchId),_.get(i)?PersistencePromise.resolve():this.remoteDocumentCache.getEntry(e,i).next((e=>{f=f.insert(i,e)}))))).next((()=>this.populateOverlays(e,i,_))).next((()=>this.computeViews(e,f,i,__PRIVATE_documentKeySet()))).next((e=>({batchId:d,changes:__PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)})))))}))}getDocumentsMatchingDocumentQuery(e,i){return this.getDocument(e,new DocumentKey(i)).next((e=>{let i=documentMap();return e.isFoundDocument()&&(i=i.insert(e.key,e)),i}))}getDocumentsMatchingCollectionGroupQuery(e,i,s,o){const _=i.collectionGroup;let h=documentMap();return this.indexManager.getCollectionParents(e,_).next((d=>PersistencePromise.forEach(d,(d=>{const f=function __PRIVATE_asCollectionQueryAtPath(e,i){return new __PRIVATE_QueryImpl(i,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(i,d.child(_));return this.getDocumentsMatchingCollectionQuery(e,f,s,o).next((e=>{e.forEach(((e,i)=>{h=h.insert(e,i)}))}))})).next((()=>h))))}getDocumentsMatchingCollectionQuery(e,i,s,o){let _;return this.documentOverlayCache.getOverlaysForCollection(e,i.path,s.largestBatchId).next((h=>(_=h,this.remoteDocumentCache.getDocumentsMatchingQuery(e,i,s,_,o)))).next((e=>{_.forEach(((i,s)=>{const o=s.getKey();null===e.get(o)&&(e=e.insert(o,MutableDocument.newInvalidDocument(o)))}));let s=documentMap();return e.forEach(((e,o)=>{const h=_.get(e);void 0!==h&&__PRIVATE_mutationApplyToLocalView(h.mutation,o,FieldMask.empty(),Timestamp.now()),__PRIVATE_queryMatches(i,o)&&(s=s.insert(e,o))})),s}))}}class __PRIVATE_MemoryBundleCache{constructor(e){this.serializer=e,this.hr=new Map,this.Pr=new Map}getBundleMetadata(e,i){return PersistencePromise.resolve(this.hr.get(i))}saveBundleMetadata(e,i){return this.hr.set(i.id,function __PRIVATE_fromBundleMetadata(e){return{id:e.id,version:e.version,createTime:__PRIVATE_fromVersion(e.createTime)}}(i)),PersistencePromise.resolve()}getNamedQuery(e,i){return PersistencePromise.resolve(this.Pr.get(i))}saveNamedQuery(e,i){return this.Pr.set(i.name,function __PRIVATE_fromProtoNamedQuery(e){return{name:e.name,query:__PRIVATE_fromBundledQuery(e.bundledQuery),readTime:__PRIVATE_fromVersion(e.readTime)}}(i)),PersistencePromise.resolve()}}class __PRIVATE_MemoryDocumentOverlayCache{constructor(){this.overlays=new SortedMap(DocumentKey.comparator),this.Ir=new Map}getOverlay(e,i){return PersistencePromise.resolve(this.overlays.get(i))}getOverlays(e,i){const s=__PRIVATE_newOverlayMap();return PersistencePromise.forEach(i,(i=>this.getOverlay(e,i).next((e=>{null!==e&&s.set(i,e)})))).next((()=>s))}saveOverlays(e,i,s){return s.forEach(((s,o)=>{this.ht(e,i,o)})),PersistencePromise.resolve()}removeOverlaysForBatchId(e,i,s){const o=this.Ir.get(s);return void 0!==o&&(o.forEach((e=>this.overlays=this.overlays.remove(e))),this.Ir.delete(s)),PersistencePromise.resolve()}getOverlaysForCollection(e,i,s){const o=__PRIVATE_newOverlayMap(),_=i.length+1,h=new DocumentKey(i.child("")),d=this.overlays.getIteratorFrom(h);for(;d.hasNext();){const e=d.getNext().value,h=e.getKey();if(!i.isPrefixOf(h.path))break;h.path.length===_&&e.largestBatchId>s&&o.set(e.getKey(),e)}return PersistencePromise.resolve(o)}getOverlaysForCollectionGroup(e,i,s,o){let _=new SortedMap(((e,i)=>e-i));const h=this.overlays.getIterator();for(;h.hasNext();){const e=h.getNext().value;if(e.getKey().getCollectionGroup()===i&&e.largestBatchId>s){let i=_.get(e.largestBatchId);null===i&&(i=__PRIVATE_newOverlayMap(),_=_.insert(e.largestBatchId,i)),i.set(e.getKey(),e)}}const d=__PRIVATE_newOverlayMap(),f=_.getIterator();for(;f.hasNext()&&(f.getNext().value.forEach(((e,i)=>d.set(e,i))),!(d.size()>=o)););return PersistencePromise.resolve(d)}ht(e,i,s){const o=this.overlays.get(s.key);if(null!==o){const e=this.Ir.get(o.largestBatchId).delete(s.key);this.Ir.set(o.largestBatchId,e)}this.overlays=this.overlays.insert(s.key,new Overlay(i,s));let _=this.Ir.get(i);void 0===_&&(_=__PRIVATE_documentKeySet(),this.Ir.set(i,_)),this.Ir.set(i,_.add(s.key))}}class __PRIVATE_MemoryGlobalsCache{constructor(){this.sessionToken=ByteString.EMPTY_BYTE_STRING}getSessionToken(e){return PersistencePromise.resolve(this.sessionToken)}setSessionToken(e,i){return this.sessionToken=i,PersistencePromise.resolve()}}class __PRIVATE_ReferenceSet{constructor(){this.Tr=new SortedSet(__PRIVATE_DocReference.Er),this.dr=new SortedSet(__PRIVATE_DocReference.Ar)}isEmpty(){return this.Tr.isEmpty()}addReference(e,i){const s=new __PRIVATE_DocReference(e,i);this.Tr=this.Tr.add(s),this.dr=this.dr.add(s)}Rr(e,i){e.forEach((e=>this.addReference(e,i)))}removeReference(e,i){this.Vr(new __PRIVATE_DocReference(e,i))}mr(e,i){e.forEach((e=>this.removeReference(e,i)))}gr(e){const i=new DocumentKey(new ResourcePath([])),s=new __PRIVATE_DocReference(i,e),o=new __PRIVATE_DocReference(i,e+1),_=[];return this.dr.forEachInRange([s,o],(e=>{this.Vr(e),_.push(e.key)})),_}pr(){this.Tr.forEach((e=>this.Vr(e)))}Vr(e){this.Tr=this.Tr.delete(e),this.dr=this.dr.delete(e)}yr(e){const i=new DocumentKey(new ResourcePath([])),s=new __PRIVATE_DocReference(i,e),o=new __PRIVATE_DocReference(i,e+1);let _=__PRIVATE_documentKeySet();return this.dr.forEachInRange([s,o],(e=>{_=_.add(e.key)})),_}containsKey(e){const i=new __PRIVATE_DocReference(e,0),s=this.Tr.firstAfterOrEqual(i);return null!==s&&e.isEqual(s.key)}}class __PRIVATE_DocReference{constructor(e,i){this.key=e,this.wr=i}static Er(e,i){return DocumentKey.comparator(e.key,i.key)||__PRIVATE_primitiveComparator(e.wr,i.wr)}static Ar(e,i){return __PRIVATE_primitiveComparator(e.wr,i.wr)||DocumentKey.comparator(e.key,i.key)}}class __PRIVATE_MemoryMutationQueue{constructor(e,i){this.indexManager=e,this.referenceDelegate=i,this.mutationQueue=[],this.Sr=1,this.br=new SortedSet(__PRIVATE_DocReference.Er)}checkEmpty(e){return PersistencePromise.resolve(0===this.mutationQueue.length)}addMutationBatch(e,i,s,o){const _=this.Sr;this.Sr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const h=new MutationBatch(_,i,s,o);this.mutationQueue.push(h);for(const i of o)this.br=this.br.add(new __PRIVATE_DocReference(i.key,_)),this.indexManager.addToCollectionParentIndex(e,i.key.path.popLast());return PersistencePromise.resolve(h)}lookupMutationBatch(e,i){return PersistencePromise.resolve(this.Dr(i))}getNextMutationBatchAfterBatchId(e,i){const s=i+1,o=this.vr(s),_=o<0?0:o;return PersistencePromise.resolve(this.mutationQueue.length>_?this.mutationQueue[_]:null)}getHighestUnacknowledgedBatchId(){return PersistencePromise.resolve(0===this.mutationQueue.length?-1:this.Sr-1)}getAllMutationBatches(e){return PersistencePromise.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,i){const s=new __PRIVATE_DocReference(i,0),o=new __PRIVATE_DocReference(i,Number.POSITIVE_INFINITY),_=[];return this.br.forEachInRange([s,o],(e=>{const i=this.Dr(e.wr);_.push(i)})),PersistencePromise.resolve(_)}getAllMutationBatchesAffectingDocumentKeys(e,i){let s=new SortedSet(__PRIVATE_primitiveComparator);return i.forEach((e=>{const i=new __PRIVATE_DocReference(e,0),o=new __PRIVATE_DocReference(e,Number.POSITIVE_INFINITY);this.br.forEachInRange([i,o],(e=>{s=s.add(e.wr)}))})),PersistencePromise.resolve(this.Cr(s))}getAllMutationBatchesAffectingQuery(e,i){const s=i.path,o=s.length+1;let _=s;DocumentKey.isDocumentKey(_)||(_=_.child(""));const h=new __PRIVATE_DocReference(new DocumentKey(_),0);let d=new SortedSet(__PRIVATE_primitiveComparator);return this.br.forEachWhile((e=>{const i=e.key.path;return!!s.isPrefixOf(i)&&(i.length===o&&(d=d.add(e.wr)),!0)}),h),PersistencePromise.resolve(this.Cr(d))}Cr(e){const i=[];return e.forEach((e=>{const s=this.Dr(e);null!==s&&i.push(s)})),i}removeMutationBatch(e,i){__PRIVATE_hardAssert(0===this.Fr(i.batchId,"removed")),this.mutationQueue.shift();let s=this.br;return PersistencePromise.forEach(i.mutations,(o=>{const _=new __PRIVATE_DocReference(o.key,i.batchId);return s=s.delete(_),this.referenceDelegate.markPotentiallyOrphaned(e,o.key)})).next((()=>{this.br=s}))}On(e){}containsKey(e,i){const s=new __PRIVATE_DocReference(i,0),o=this.br.firstAfterOrEqual(s);return PersistencePromise.resolve(i.isEqual(o&&o.key))}performConsistencyCheck(e){return this.mutationQueue.length,PersistencePromise.resolve()}Fr(e,i){return this.vr(e)}vr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Dr(e){const i=this.vr(e);return i<0||i>=this.mutationQueue.length?null:this.mutationQueue[i]}}class __PRIVATE_MemoryRemoteDocumentCacheImpl{constructor(e){this.Mr=e,this.docs=function __PRIVATE_documentEntryMap(){return new SortedMap(DocumentKey.comparator)}(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,i){const s=i.key,o=this.docs.get(s),_=o?o.size:0,h=this.Mr(i);return this.docs=this.docs.insert(s,{document:i.mutableCopy(),size:h}),this.size+=h-_,this.indexManager.addToCollectionParentIndex(e,s.path.popLast())}removeEntry(e){const i=this.docs.get(e);i&&(this.docs=this.docs.remove(e),this.size-=i.size)}getEntry(e,i){const s=this.docs.get(i);return PersistencePromise.resolve(s?s.document.mutableCopy():MutableDocument.newInvalidDocument(i))}getEntries(e,i){let s=__PRIVATE_mutableDocumentMap();return i.forEach((e=>{const i=this.docs.get(e);s=s.insert(e,i?i.document.mutableCopy():MutableDocument.newInvalidDocument(e))})),PersistencePromise.resolve(s)}getDocumentsMatchingQuery(e,i,s,o){let _=__PRIVATE_mutableDocumentMap();const h=i.path,d=new DocumentKey(h.child("")),f=this.docs.getIteratorFrom(d);for(;f.hasNext();){const{key:e,value:{document:d}}=f.getNext();if(!h.isPrefixOf(e.path))break;e.path.length>h.length+1||__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(d),s)<=0||(o.has(d.key)||__PRIVATE_queryMatches(i,d))&&(_=_.insert(d.key,d.mutableCopy()))}return PersistencePromise.resolve(_)}getAllFromCollectionGroup(e,i,s,o){fail()}Or(e,i){return PersistencePromise.forEach(this.docs,(e=>i(e)))}newChangeBuffer(e){return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this)}getSize(e){return PersistencePromise.resolve(this.size)}}class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer{constructor(e){super(),this.cr=e}applyChanges(e){const i=[];return this.changes.forEach(((s,o)=>{o.isValidDocument()?i.push(this.cr.addEntry(e,o)):this.cr.removeEntry(s)})),PersistencePromise.waitFor(i)}getFromCache(e,i){return this.cr.getEntry(e,i)}getAllFromCache(e,i){return this.cr.getEntries(e,i)}}class __PRIVATE_MemoryTargetCache{constructor(e){this.persistence=e,this.Nr=new ObjectMap((e=>__PRIVATE_canonifyTarget(e)),__PRIVATE_targetEquals),this.lastRemoteSnapshotVersion=SnapshotVersion.min(),this.highestTargetId=0,this.Lr=0,this.Br=new __PRIVATE_ReferenceSet,this.targetCount=0,this.kr=__PRIVATE_TargetIdGenerator.Bn()}forEachTarget(e,i){return this.Nr.forEach(((e,s)=>i(s))),PersistencePromise.resolve()}getLastRemoteSnapshotVersion(e){return PersistencePromise.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return PersistencePromise.resolve(this.Lr)}allocateTargetId(e){return this.highestTargetId=this.kr.next(),PersistencePromise.resolve(this.highestTargetId)}setTargetsMetadata(e,i,s){return s&&(this.lastRemoteSnapshotVersion=s),i>this.Lr&&(this.Lr=i),PersistencePromise.resolve()}Kn(e){this.Nr.set(e.target,e);const i=e.targetId;i>this.highestTargetId&&(this.kr=new __PRIVATE_TargetIdGenerator(i),this.highestTargetId=i),e.sequenceNumber>this.Lr&&(this.Lr=e.sequenceNumber)}addTargetData(e,i){return this.Kn(i),this.targetCount+=1,PersistencePromise.resolve()}updateTargetData(e,i){return this.Kn(i),PersistencePromise.resolve()}removeTargetData(e,i){return this.Nr.delete(i.target),this.Br.gr(i.targetId),this.targetCount-=1,PersistencePromise.resolve()}removeTargets(e,i,s){let o=0;const _=[];return this.Nr.forEach(((h,d)=>{d.sequenceNumber<=i&&null===s.get(d.targetId)&&(this.Nr.delete(h),_.push(this.removeMatchingKeysForTargetId(e,d.targetId)),o++)})),PersistencePromise.waitFor(_).next((()=>o))}getTargetCount(e){return PersistencePromise.resolve(this.targetCount)}getTargetData(e,i){const s=this.Nr.get(i)||null;return PersistencePromise.resolve(s)}addMatchingKeys(e,i,s){return this.Br.Rr(i,s),PersistencePromise.resolve()}removeMatchingKeys(e,i,s){this.Br.mr(i,s);const o=this.persistence.referenceDelegate,_=[];return o&&i.forEach((i=>{_.push(o.markPotentiallyOrphaned(e,i))})),PersistencePromise.waitFor(_)}removeMatchingKeysForTargetId(e,i){return this.Br.gr(i),PersistencePromise.resolve()}getMatchingKeysForTargetId(e,i){const s=this.Br.yr(i);return PersistencePromise.resolve(s)}containsKey(e,i){return PersistencePromise.resolve(this.Br.containsKey(i))}}class __PRIVATE_MemoryPersistence{constructor(e,i){this.qr={},this.overlays={},this.Qr=new __PRIVATE_ListenSequence(0),this.Kr=!1,this.Kr=!0,this.$r=new __PRIVATE_MemoryGlobalsCache,this.referenceDelegate=e(this),this.Ur=new __PRIVATE_MemoryTargetCache(this),this.indexManager=new __PRIVATE_MemoryIndexManager,this.remoteDocumentCache=function __PRIVATE_newMemoryRemoteDocumentCache(e){return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e)}((e=>this.referenceDelegate.Wr(e))),this.serializer=new __PRIVATE_LocalSerializer(i),this.Gr=new __PRIVATE_MemoryBundleCache(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Kr=!1,Promise.resolve()}get started(){return this.Kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let i=this.overlays[e.toKey()];return i||(i=new __PRIVATE_MemoryDocumentOverlayCache,this.overlays[e.toKey()]=i),i}getMutationQueue(e,i){let s=this.qr[e.toKey()];return s||(s=new __PRIVATE_MemoryMutationQueue(i,this.referenceDelegate),this.qr[e.toKey()]=s),s}getGlobalsCache(){return this.$r}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Gr}runTransaction(e,i,s){__PRIVATE_logDebug("MemoryPersistence","Starting transaction:",e);const o=new __PRIVATE_MemoryTransaction(this.Qr.next());return this.referenceDelegate.zr(),s(o).next((e=>this.referenceDelegate.jr(o).next((()=>e)))).toPromise().then((e=>(o.raiseOnCommittedEvent(),e)))}Hr(e,i){return PersistencePromise.or(Object.values(this.qr).map((s=>()=>s.containsKey(e,i))))}}class __PRIVATE_MemoryTransaction extends PersistenceTransaction{constructor(e){super(),this.currentSequenceNumber=e}}class __PRIVATE_MemoryEagerDelegate{constructor(e){this.persistence=e,this.Jr=new __PRIVATE_ReferenceSet,this.Yr=null}static Zr(e){return new __PRIVATE_MemoryEagerDelegate(e)}get Xr(){if(this.Yr)return this.Yr;throw fail()}addReference(e,i,s){return this.Jr.addReference(s,i),this.Xr.delete(s.toString()),PersistencePromise.resolve()}removeReference(e,i,s){return this.Jr.removeReference(s,i),this.Xr.add(s.toString()),PersistencePromise.resolve()}markPotentiallyOrphaned(e,i){return this.Xr.add(i.toString()),PersistencePromise.resolve()}removeTarget(e,i){this.Jr.gr(i.targetId).forEach((e=>this.Xr.add(e.toString())));const s=this.persistence.getTargetCache();return s.getMatchingKeysForTargetId(e,i.targetId).next((e=>{e.forEach((e=>this.Xr.add(e.toString())))})).next((()=>s.removeTargetData(e,i)))}zr(){this.Yr=new Set}jr(e){const i=this.persistence.getRemoteDocumentCache().newChangeBuffer();return PersistencePromise.forEach(this.Xr,(s=>{const o=DocumentKey.fromPath(s);return this.ei(e,o).next((e=>{e||i.removeEntry(o,SnapshotVersion.min())}))})).next((()=>(this.Yr=null,i.apply(e))))}updateLimboDocument(e,i){return this.ei(e,i).next((e=>{e?this.Xr.delete(i.toString()):this.Xr.add(i.toString())}))}Wr(e){return 0}ei(e,i){return PersistencePromise.or([()=>PersistencePromise.resolve(this.Jr.containsKey(i)),()=>this.persistence.getTargetCache().containsKey(e,i),()=>this.persistence.Hr(e,i)])}}class __PRIVATE_MemoryLruDelegate{constructor(e,i){this.persistence=e,this.ti=new ObjectMap((e=>__PRIVATE_encodeResourcePath(e.path)),((e,i)=>e.isEqual(i))),this.garbageCollector=__PRIVATE_newLruGarbageCollector(this,i)}static Zr(e,i){return new __PRIVATE_MemoryLruDelegate(e,i)}zr(){}jr(e){return PersistencePromise.resolve()}forEachTarget(e,i){return this.persistence.getTargetCache().forEachTarget(e,i)}Yn(e){const i=this.er(e);return this.persistence.getTargetCache().getTargetCount(e).next((e=>i.next((i=>e+i))))}er(e){let i=0;return this.Zn(e,(e=>{i++})).next((()=>i))}Zn(e,i){return PersistencePromise.forEach(this.ti,((s,o)=>this.nr(e,s,o).next((e=>e?PersistencePromise.resolve():i(o)))))}removeTargets(e,i,s){return this.persistence.getTargetCache().removeTargets(e,i,s)}removeOrphanedDocuments(e,i){let s=0;const o=this.persistence.getRemoteDocumentCache(),_=o.newChangeBuffer();return o.Or(e,(o=>this.nr(e,o,i).next((e=>{e||(s++,_.removeEntry(o,SnapshotVersion.min()))})))).next((()=>_.apply(e))).next((()=>s))}markPotentiallyOrphaned(e,i){return this.ti.set(i,e.currentSequenceNumber),PersistencePromise.resolve()}removeTarget(e,i){const s=i.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,s)}addReference(e,i,s){return this.ti.set(s,e.currentSequenceNumber),PersistencePromise.resolve()}removeReference(e,i,s){return this.ti.set(s,e.currentSequenceNumber),PersistencePromise.resolve()}updateLimboDocument(e,i){return this.ti.set(i,e.currentSequenceNumber),PersistencePromise.resolve()}Wr(e){let i=e.key.toString().length;return e.isFoundDocument()&&(i+=__PRIVATE_estimateByteSize(e.data.value)),i}nr(e,i,s){return PersistencePromise.or([()=>this.persistence.Hr(e,i),()=>this.persistence.getTargetCache().containsKey(e,i),()=>{const e=this.ti.get(i);return PersistencePromise.resolve(void 0!==e&&e>s)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class __PRIVATE_SchemaConverter{constructor(e){this.serializer=e}O(e,i,s,o){const _=new __PRIVATE_SimpleDbTransaction("createOrUpgrade",i);s<1&&o>=1&&(function __PRIVATE_createPrimaryClientStore(e){e.createObjectStore("owner")}(e),function __PRIVATE_createMutationQueue(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",fe,{unique:!0}),e.createObjectStore("documentMutations")}(e),__PRIVATE_createQueryCache(e),function __PRIVATE_createLegacyRemoteDocumentCache(e){e.createObjectStore("remoteDocuments")}(e));let h=PersistencePromise.resolve();return s<3&&o>=3&&(0!==s&&(function __PRIVATE_dropQueryCache(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),__PRIVATE_createQueryCache(e)),h=h.next((()=>function __PRIVATE_writeEmptyTargetGlobalEntry(e){const i=e.store("targetGlobal"),s={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:SnapshotVersion.min().toTimestamp(),targetCount:0};return i.put("targetGlobalKey",s)}(_)))),s<4&&o>=4&&(0!==s&&(h=h.next((()=>function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e,i){return i.store("mutations").U().next((s=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",fe,{unique:!0});const o=i.store("mutations"),_=s.map((e=>o.put(e)));return PersistencePromise.waitFor(_)}))}(e,_)))),h=h.next((()=>{!function __PRIVATE_createClientMetadataStore(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)}))),s<5&&o>=5&&(h=h.next((()=>this.ni(_)))),s<6&&o>=6&&(h=h.next((()=>(function __PRIVATE_createDocumentGlobalStore(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.ri(_))))),s<7&&o>=7&&(h=h.next((()=>this.ii(_)))),s<8&&o>=8&&(h=h.next((()=>this.si(e,_)))),s<9&&o>=9&&(h=h.next((()=>{!function __PRIVATE_dropRemoteDocumentChangesStore(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)}))),s<10&&o>=10&&(h=h.next((()=>this.oi(_)))),s<11&&o>=11&&(h=h.next((()=>{!function __PRIVATE_createBundlesStore(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function __PRIVATE_createNamedQueriesStore(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)}))),s<12&&o>=12&&(h=h.next((()=>{!function __PRIVATE_createDocumentOverlayStore(e){const i=e.createObjectStore("documentOverlays",{keyPath:Se});i.createIndex("collectionPathOverlayIndex",we,{unique:!1}),i.createIndex("collectionGroupOverlayIndex",De,{unique:!1})}(e)}))),s<13&&o>=13&&(h=h.next((()=>function __PRIVATE_createRemoteDocumentCache(e){const i=e.createObjectStore("remoteDocumentsV14",{keyPath:Ie});i.createIndex("documentKeyIndex",Te),i.createIndex("collectionGroupIndex",pe)}(e))).next((()=>this._i(e,_))).next((()=>e.deleteObjectStore("remoteDocuments")))),s<14&&o>=14&&(h=h.next((()=>this.ai(e,_)))),s<15&&o>=15&&(h=h.next((()=>function __PRIVATE_createFieldIndex(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:ye}).createIndex("sequenceNumberIndex",Ve,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:ve}).createIndex("documentKeyIndex",be,{unique:!1})}(e)))),s<16&&o>=16&&(h=h.next((()=>{i.objectStore("indexState").clear()})).next((()=>{i.objectStore("indexEntries").clear()}))),s<17&&o>=17&&(h=h.next((()=>{!function __PRIVATE_createGlobalsStore(e){e.createObjectStore("globals",{keyPath:"name"})}(e)}))),h}ri(e){let i=0;return e.store("remoteDocuments").J(((e,s)=>{i+=__PRIVATE_dbDocumentSize(s)})).next((()=>{const s={byteSize:i};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",s)}))}ni(e){const i=e.store("mutationQueues"),s=e.store("mutations");return i.U().next((i=>PersistencePromise.forEach(i,(i=>{const o=IDBKeyRange.bound([i.userId,-1],[i.userId,i.lastAcknowledgedBatchId]);return s.U("userMutationsIndex",o).next((s=>PersistencePromise.forEach(s,(s=>{__PRIVATE_hardAssert(s.userId===i.userId);const o=__PRIVATE_fromDbMutationBatch(this.serializer,s);return removeMutationBatch(e,i.userId,o).next((()=>{}))}))))}))))}ii(e){const i=e.store("targetDocuments"),s=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next((e=>{const o=[];return s.J(((s,_)=>{const h=new ResourcePath(s),d=function __PRIVATE_sentinelKey(e){return[0,__PRIVATE_encodeResourcePath(e)]}(h);o.push(i.get(d).next((s=>s?PersistencePromise.resolve():(s=>i.put({targetId:0,path:__PRIVATE_encodeResourcePath(s),sequenceNumber:e.highestListenSequenceNumber}))(h))))})).next((()=>PersistencePromise.waitFor(o)))}))}si(e,i){e.createObjectStore("collectionParents",{keyPath:Re});const s=i.store("collectionParents"),o=new __PRIVATE_MemoryCollectionParentIndex,addEntry=e=>{if(o.add(e)){const i=e.lastSegment(),o=e.popLast();return s.put({collectionId:i,parent:__PRIVATE_encodeResourcePath(o)})}};return i.store("remoteDocuments").J({H:!0},((e,i)=>{const s=new ResourcePath(e);return addEntry(s.popLast())})).next((()=>i.store("documentMutations").J({H:!0},(([e,i,s],o)=>{const _=__PRIVATE_decodeResourcePath(i);return addEntry(_.popLast())}))))}oi(e){const i=e.store("targets");return i.J(((e,s)=>{const o=__PRIVATE_fromDbTarget(s),_=__PRIVATE_toDbTarget(this.serializer,o);return i.put(_)}))}_i(e,i){const s=i.store("remoteDocuments"),o=[];return s.J(((e,s)=>{const _=i.store("remoteDocumentsV14"),h=function __PRIVATE_extractKey(e){return e.document?new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)):e.noDocument?DocumentKey.fromSegments(e.noDocument.path):e.unknownDocument?DocumentKey.fromSegments(e.unknownDocument.path):fail()}(s).path.toArray(),d={prefixPath:h.slice(0,h.length-2),collectionGroup:h[h.length-2],documentId:h[h.length-1],readTime:s.readTime||[0,0],unknownDocument:s.unknownDocument,noDocument:s.noDocument,document:s.document,hasCommittedMutations:!!s.hasCommittedMutations};o.push(_.put(d))})).next((()=>PersistencePromise.waitFor(o)))}ai(e,i){const s=i.store("mutations"),o=__PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer),_=new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Zr,this.serializer.ct);return s.U().next((e=>{const s=new Map;return e.forEach((e=>{var i;let o=null!==(i=s.get(e.userId))&&void 0!==i?i:__PRIVATE_documentKeySet();__PRIVATE_fromDbMutationBatch(this.serializer,e).keys().forEach((e=>o=o.add(e))),s.set(e.userId,o)})),PersistencePromise.forEach(s,((e,s)=>{const h=new User(s),d=__PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer,h),f=_.getIndexManager(h),g=__PRIVATE_IndexedDbMutationQueue.lt(h,this.serializer,f,_.referenceDelegate);return new LocalDocumentsView(o,g,d,f).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(i,__PRIVATE_ListenSequence.oe),e).next()}))}))}}function __PRIVATE_createQueryCache(e){e.createObjectStore("targetDocuments",{keyPath:Pe}).createIndex("documentTargetsIndex",Ae,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Ee,{unique:!0}),e.createObjectStore("targetGlobal")}const nt="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 __PRIVATE_IndexedDbPersistence{constructor(e,i,s,o,_,h,d,f,g,b,w=17){if(this.allowTabSynchronization=e,this.persistenceKey=i,this.clientId=s,this.ui=_,this.window=h,this.document=d,this.ci=g,this.li=b,this.hi=w,this.Qr=null,this.Kr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Pi=null,this.inForeground=!1,this.Ii=null,this.Ti=null,this.Ei=Number.NEGATIVE_INFINITY,this.di=e=>Promise.resolve(),!__PRIVATE_IndexedDbPersistence.D())throw new FirestoreError(_e.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new __PRIVATE_IndexedDbLruDelegateImpl(this,o),this.Ai=i+"main",this.serializer=new __PRIVATE_LocalSerializer(f),this.Ri=new __PRIVATE_SimpleDb(this.Ai,this.hi,new __PRIVATE_SchemaConverter(this.serializer)),this.$r=new __PRIVATE_IndexedDbGlobalsCache,this.Ur=new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate,this.serializer),this.remoteDocumentCache=__PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer),this.Gr=new __PRIVATE_IndexedDbBundleCache,this.window&&this.window.localStorage?this.Vi=this.window.localStorage:(this.Vi=null,!1===b&&__PRIVATE_logError("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.mi().then((()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new FirestoreError(_e.FAILED_PRECONDITION,nt);return this.fi(),this.gi(),this.pi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(e=>this.Ur.getHighestSequenceNumber(e)))})).then((e=>{this.Qr=new __PRIVATE_ListenSequence(e,this.ci)})).then((()=>{this.Kr=!0})).catch((e=>(this.Ri&&this.Ri.close(),Promise.reject(e))))}yi(e){return this.di=async i=>{if(this.started)return e(i)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.Ri.L((async i=>{null===i.newVersion&&await e()}))}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.ui.enqueueAndForget((async()=>{this.started&&await this.mi()})))}mi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",(e=>__PRIVATE_clientMetadataStore(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.wi(e).next((e=>{e||(this.isPrimary=!1,this.ui.enqueueRetryable((()=>this.di(!1))))}))})).next((()=>this.Si(e))).next((i=>this.isPrimary&&!i?this.bi(e).next((()=>!1)):!!i&&this.Di(e).next((()=>!0)))))).catch((e=>{if(__PRIVATE_isIndexedDbTransactionError(e))return __PRIVATE_logDebug("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return __PRIVATE_logDebug("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1})).then((e=>{this.isPrimary!==e&&this.ui.enqueueRetryable((()=>this.di(e))),this.isPrimary=e}))}wi(e){return __PRIVATE_primaryClientStore(e).get("owner").next((e=>PersistencePromise.resolve(this.vi(e))))}Ci(e){return __PRIVATE_clientMetadataStore(e).delete(this.clientId)}async Fi(){if(this.isPrimary&&!this.Mi(this.Ei,18e5)){this.Ei=Date.now();const e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(e=>{const i=__PRIVATE_getStore(e,"clientMetadata");return i.U().next((e=>{const s=this.xi(e,18e5),o=e.filter((e=>-1===s.indexOf(e)));return PersistencePromise.forEach(o,(e=>i.delete(e.clientId))).next((()=>o))}))})).catch((()=>[]));if(this.Vi)for(const i of e)this.Vi.removeItem(this.Oi(i.clientId))}}pi(){this.Ti=this.ui.enqueueAfterDelay("client_metadata_refresh",4e3,(()=>this.mi().then((()=>this.Fi())).then((()=>this.pi()))))}vi(e){return!!e&&e.ownerId===this.clientId}Si(e){return this.li?PersistencePromise.resolve(!0):__PRIVATE_primaryClientStore(e).get("owner").next((i=>{if(null!==i&&this.Mi(i.leaseTimestampMs,5e3)&&!this.Ni(i.ownerId)){if(this.vi(i)&&this.networkEnabled)return!0;if(!this.vi(i)){if(!i.allowTabSynchronization)throw new FirestoreError(_e.FAILED_PRECONDITION,nt);return!1}}return!(!this.networkEnabled||!this.inForeground)||__PRIVATE_clientMetadataStore(e).U().next((e=>void 0===this.xi(e,5e3).find((e=>{if(this.clientId!==e.clientId){const i=!this.networkEnabled&&e.networkEnabled,s=!this.inForeground&&e.inForeground,o=this.networkEnabled===e.networkEnabled;if(i||s&&o)return!0}return!1}))))})).next((e=>(this.isPrimary!==e&&__PRIVATE_logDebug("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e)))}async shutdown(){this.Kr=!1,this.Li(),this.Ti&&(this.Ti.cancel(),this.Ti=null),this.Bi(),this.ki(),await this.Ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],(e=>{const i=new __PRIVATE_IndexedDbTransaction(e,__PRIVATE_ListenSequence.oe);return this.bi(i).next((()=>this.Ci(i)))})),this.Ri.close(),this.qi()}xi(e,i){return e.filter((e=>this.Mi(e.updateTimeMs,i)&&!this.Ni(e.clientId)))}Qi(){return this.runTransaction("getActiveClients","readonly",(e=>__PRIVATE_clientMetadataStore(e).U().next((e=>this.xi(e,18e5).map((e=>e.clientId))))))}get started(){return this.Kr}getGlobalsCache(){return this.$r}getMutationQueue(e,i){return __PRIVATE_IndexedDbMutationQueue.lt(e,this.serializer,i,this.referenceDelegate)}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new __PRIVATE_IndexedDbIndexManager(e,this.serializer.ct.databaseId)}getDocumentOverlayCache(e){return __PRIVATE_IndexedDbDocumentOverlayCache.lt(this.serializer,e)}getBundleCache(){return this.Gr}runTransaction(e,i,s){__PRIVATE_logDebug("IndexedDbPersistence","Starting transaction:",e);const o="readonly"===i?"readonly":"readwrite",_=function __PRIVATE_getObjectStores(e){return 17===e?Oe:16===e?ke:15===e?Ne:14===e?Me:13===e?xe:12===e?Fe:11===e?Ce:void fail()}(this.hi);let h;return this.Ri.runTransaction(e,o,_,(o=>(h=new __PRIVATE_IndexedDbTransaction(o,this.Qr?this.Qr.next():__PRIVATE_ListenSequence.oe),"readwrite-primary"===i?this.wi(h).next((e=>!!e||this.Si(h))).next((i=>{if(!i)throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.ui.enqueueRetryable((()=>this.di(!1))),new FirestoreError(_e.FAILED_PRECONDITION,de);return s(h)})).next((e=>this.Di(h).next((()=>e)))):this.Ki(h).next((()=>s(h)))))).then((e=>(h.raiseOnCommittedEvent(),e)))}Ki(e){return __PRIVATE_primaryClientStore(e).get("owner").next((e=>{if(null!==e&&this.Mi(e.leaseTimestampMs,5e3)&&!this.Ni(e.ownerId)&&!this.vi(e)&&!(this.li||this.allowTabSynchronization&&e.allowTabSynchronization))throw new FirestoreError(_e.FAILED_PRECONDITION,nt)}))}Di(e){const i={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return __PRIVATE_primaryClientStore(e).put("owner",i)}static D(){return __PRIVATE_SimpleDb.D()}bi(e){const i=__PRIVATE_primaryClientStore(e);return i.get("owner").next((e=>this.vi(e)?(__PRIVATE_logDebug("IndexedDbPersistence","Releasing primary lease."),i.delete("owner")):PersistencePromise.resolve()))}Mi(e,i){const s=Date.now();return!(e<s-i||e>s&&(__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${s}`),1))}fi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ii=()=>{this.ui.enqueueAndForget((()=>(this.inForeground="visible"===this.document.visibilityState,this.mi())))},this.document.addEventListener("visibilitychange",this.Ii),this.inForeground="visible"===this.document.visibilityState)}Bi(){this.Ii&&(this.document.removeEventListener("visibilitychange",this.Ii),this.Ii=null)}gi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Pi=()=>{this.Li();const e=/(?:Version|Mobile)\/1[456]/;isSafari()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.ui.enterRestrictedMode(!0),this.ui.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener("pagehide",this.Pi))}ki(){this.Pi&&(this.window.removeEventListener("pagehide",this.Pi),this.Pi=null)}Ni(e){var i;try{const s=null!==(null===(i=this.Vi)||void 0===i?void 0:i.getItem(this.Oi(e)));return __PRIVATE_logDebug("IndexedDbPersistence",`Client '${e}' ${s?"is":"is not"} zombied in LocalStorage`),s}catch(e){return __PRIVATE_logError("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Li(){if(this.Vi)try{this.Vi.setItem(this.Oi(this.clientId),String(Date.now()))}catch(e){__PRIVATE_logError("Failed to set zombie client id.",e)}}qi(){if(this.Vi)try{this.Vi.removeItem(this.Oi(this.clientId))}catch(e){}}Oi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function __PRIVATE_primaryClientStore(e){return __PRIVATE_getStore(e,"owner")}function __PRIVATE_clientMetadataStore(e){return __PRIVATE_getStore(e,"clientMetadata")}function __PRIVATE_indexedDbStoragePrefix(e,i){let s=e.projectId;return e.isDefaultDatabase||(s+="."+e.database),"firestore/"+i+"/"+s+"/"}class __PRIVATE_LocalViewChanges{constructor(e,i,s,o){this.targetId=e,this.fromCache=i,this.$i=s,this.Ui=o}static Wi(e,i){let s=__PRIVATE_documentKeySet(),o=__PRIVATE_documentKeySet();for(const e of i.docChanges)switch(e.type){case 0:s=s.add(e.doc.key);break;case 1:o=o.add(e.doc.key)}return new __PRIVATE_LocalViewChanges(e,i.fromCache,s,o)}}class QueryContext{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class __PRIVATE_QueryEngine{constructor(){this.Gi=!1,this.zi=!1,this.ji=100,this.Hi=function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument(){return isSafari()?8:__PRIVATE_getAndroidVersion(getUA())>0?6:4}()}initialize(e,i){this.Ji=e,this.indexManager=i,this.Gi=!0}getDocumentsMatchingQuery(e,i,s,o){const _={result:null};return this.Yi(e,i).next((e=>{_.result=e})).next((()=>{if(!_.result)return this.Zi(e,i,o,s).next((e=>{_.result=e}))})).next((()=>{if(_.result)return;const s=new QueryContext;return this.Xi(e,i,s).next((o=>{if(_.result=o,this.zi)return this.es(e,i,s,o.size)}))})).next((()=>_.result))}es(e,i,s,o){return s.documentReadCount<this.ji?(__PRIVATE_getLogLevel()<=f.DEBUG&&__PRIVATE_logDebug("QueryEngine","SDK will not create cache indexes for query:",__PRIVATE_stringifyQuery(i),"since it only creates cache indexes for collection contains","more than or equal to",this.ji,"documents"),PersistencePromise.resolve()):(__PRIVATE_getLogLevel()<=f.DEBUG&&__PRIVATE_logDebug("QueryEngine","Query:",__PRIVATE_stringifyQuery(i),"scans",s.documentReadCount,"local documents and returns",o,"documents as results."),s.documentReadCount>this.Hi*o?(__PRIVATE_getLogLevel()<=f.DEBUG&&__PRIVATE_logDebug("QueryEngine","The SDK decides to create cache indexes for query:",__PRIVATE_stringifyQuery(i),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,__PRIVATE_queryToTarget(i))):PersistencePromise.resolve())}Yi(e,i){if(__PRIVATE_queryMatchesAllDocuments(i))return PersistencePromise.resolve(null);let s=__PRIVATE_queryToTarget(i);return this.indexManager.getIndexType(e,s).next((o=>0===o?null:(null!==i.limit&&1===o&&(i=__PRIVATE_queryWithLimit(i,null,"F"),s=__PRIVATE_queryToTarget(i)),this.indexManager.getDocumentsMatchingTarget(e,s).next((o=>{const _=__PRIVATE_documentKeySet(...o);return this.Ji.getDocuments(e,_).next((o=>this.indexManager.getMinOffset(e,s).next((s=>{const h=this.ts(i,o);return this.ns(i,h,_,s.readTime)?this.Yi(e,__PRIVATE_queryWithLimit(i,null,"F")):this.rs(e,h,i,s)}))))})))))}Zi(e,i,s,o){return __PRIVATE_queryMatchesAllDocuments(i)||o.isEqual(SnapshotVersion.min())?PersistencePromise.resolve(null):this.Ji.getDocuments(e,s).next((_=>{const h=this.ts(i,_);return this.ns(i,h,s,o)?PersistencePromise.resolve(null):(__PRIVATE_getLogLevel()<=f.DEBUG&&__PRIVATE_logDebug("QueryEngine","Re-using previous result from %s to execute query: %s",o.toString(),__PRIVATE_stringifyQuery(i)),this.rs(e,h,i,__PRIVATE_newIndexOffsetSuccessorFromReadTime(o,-1)).next((e=>e)))}))}ts(e,i){let s=new SortedSet(__PRIVATE_newQueryComparator(e));return i.forEach(((i,o)=>{__PRIVATE_queryMatches(e,o)&&(s=s.add(o))})),s}ns(e,i,s,o){if(null===e.limit)return!1;if(s.size!==i.size)return!0;const _="F"===e.limitType?i.last():i.first();return!!_&&(_.hasPendingWrites||_.version.compareTo(o)>0)}Xi(e,i,s){return __PRIVATE_getLogLevel()<=f.DEBUG&&__PRIVATE_logDebug("QueryEngine","Using full collection scan to execute query:",__PRIVATE_stringifyQuery(i)),this.Ji.getDocumentsMatchingQuery(e,i,IndexOffset.min(),s)}rs(e,i,s,o){return this.Ji.getDocumentsMatchingQuery(e,s,o).next((e=>(i.forEach((i=>{e=e.insert(i.key,i)})),e)))}}class __PRIVATE_LocalStoreImpl{constructor(e,i,s,o){this.persistence=e,this.ss=i,this.serializer=o,this.os=new SortedMap(__PRIVATE_primitiveComparator),this._s=new ObjectMap((e=>__PRIVATE_canonifyTarget(e)),__PRIVATE_targetEquals),this.us=new Map,this.cs=e.getRemoteDocumentCache(),this.Ur=e.getTargetCache(),this.Gr=e.getBundleCache(),this.ls(s)}ls(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new LocalDocumentsView(this.cs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.cs.setIndexManager(this.indexManager),this.ss.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(i=>e.collect(i,this.os)))}}function __PRIVATE_newLocalStore(e,i,s,o){return new __PRIVATE_LocalStoreImpl(e,i,s,o)}async function __PRIVATE_localStoreHandleUserChange(e,i){const s=__PRIVATE_debugCast(e);return await s.persistence.runTransaction("Handle user change","readonly",(e=>{let o;return s.mutationQueue.getAllMutationBatches(e).next((_=>(o=_,s.ls(i),s.mutationQueue.getAllMutationBatches(e)))).next((i=>{const _=[],h=[];let d=__PRIVATE_documentKeySet();for(const e of o){_.push(e.batchId);for(const i of e.mutations)d=d.add(i.key)}for(const e of i){h.push(e.batchId);for(const i of e.mutations)d=d.add(i.key)}return s.localDocuments.getDocuments(e,d).next((e=>({hs:e,removedBatchIds:_,addedBatchIds:h})))}))}))}function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e){const i=__PRIVATE_debugCast(e);return i.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>i.Ur.getLastRemoteSnapshotVersion(e)))}function __PRIVATE_populateDocumentChangeBuffer(e,i,s){let o=__PRIVATE_documentKeySet(),_=__PRIVATE_documentKeySet();return s.forEach((e=>o=o.add(e))),i.getEntries(e,o).next((e=>{let o=__PRIVATE_mutableDocumentMap();return s.forEach(((s,h)=>{const d=e.get(s);h.isFoundDocument()!==d.isFoundDocument()&&(_=_.add(s)),h.isNoDocument()&&h.version.isEqual(SnapshotVersion.min())?(i.removeEntry(s,h.readTime),o=o.insert(s,h)):!d.isValidDocument()||h.version.compareTo(d.version)>0||0===h.version.compareTo(d.version)&&d.hasPendingWrites?(i.addEntry(h),o=o.insert(s,h)):__PRIVATE_logDebug("LocalStore","Ignoring outdated watch update for ",s,". Current version:",d.version," Watch version:",h.version)})),{Ps:o,Is:_}}))}function __PRIVATE_localStoreGetNextMutationBatch(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===i&&(i=-1),s.mutationQueue.getNextMutationBatchAfterBatchId(e,i))))}function __PRIVATE_localStoreAllocateTarget(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("Allocate target","readwrite",(e=>{let o;return s.Ur.getTargetData(e,i).next((_=>_?(o=_,PersistencePromise.resolve(o)):s.Ur.allocateTargetId(e).next((_=>(o=new TargetData(i,_,"TargetPurposeListen",e.currentSequenceNumber),s.Ur.addTargetData(e,o).next((()=>o)))))))})).then((e=>{const o=s.os.get(e.targetId);return(null===o||e.snapshotVersion.compareTo(o.snapshotVersion)>0)&&(s.os=s.os.insert(e.targetId,e),s._s.set(i,e.targetId)),e}))}async function __PRIVATE_localStoreReleaseTarget(e,i,s){const o=__PRIVATE_debugCast(e),_=o.os.get(i),h=s?"readwrite":"readwrite-primary";try{s||await o.persistence.runTransaction("Release target",h,(e=>o.persistence.referenceDelegate.removeTarget(e,_)))}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug("LocalStore",`Failed to update sequence numbers for target ${i}: ${e}`)}o.os=o.os.remove(i),o._s.delete(_.target)}function __PRIVATE_localStoreExecuteQuery(e,i,s){const o=__PRIVATE_debugCast(e);let _=SnapshotVersion.min(),h=__PRIVATE_documentKeySet();return o.persistence.runTransaction("Execute query","readwrite",(e=>function __PRIVATE_localStoreGetTargetData(e,i,s){const o=__PRIVATE_debugCast(e),_=o._s.get(s);return void 0!==_?PersistencePromise.resolve(o.os.get(_)):o.Ur.getTargetData(i,s)}(o,e,__PRIVATE_queryToTarget(i)).next((i=>{if(i)return _=i.lastLimboFreeSnapshotVersion,o.Ur.getMatchingKeysForTargetId(e,i.targetId).next((e=>{h=e}))})).next((()=>o.ss.getDocumentsMatchingQuery(e,i,s?_:SnapshotVersion.min(),s?h:__PRIVATE_documentKeySet()))).next((e=>(__PRIVATE_setMaxReadTime(o,__PRIVATE_queryCollectionGroup(i),e),{documents:e,Ts:h})))))}function __PRIVATE_localStoreGetCachedTarget(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_debugCast(s.Ur),_=s.os.get(i);return _?Promise.resolve(_.target):s.persistence.runTransaction("Get target data","readonly",(e=>o.ot(e,i).next((e=>e?e.target:null))))}function __PRIVATE_localStoreGetNewDocumentChanges(e,i){const s=__PRIVATE_debugCast(e),o=s.us.get(i)||SnapshotVersion.min();return s.persistence.runTransaction("Get new document changes","readonly",(e=>s.cs.getAllFromCollectionGroup(e,i,__PRIVATE_newIndexOffsetSuccessorFromReadTime(o,-1),Number.MAX_SAFE_INTEGER))).then((e=>(__PRIVATE_setMaxReadTime(s,i,e),e)))}function __PRIVATE_setMaxReadTime(e,i,s){let o=e.us.get(i)||SnapshotVersion.min();s.forEach(((e,i)=>{i.readTime.compareTo(o)>0&&(o=i.readTime)})),e.us.set(i,o)}async function __PRIVATE_localStoreSaveNamedQuery(e,i,s=__PRIVATE_documentKeySet()){const o=await __PRIVATE_localStoreAllocateTarget(e,__PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(i.bundledQuery))),_=__PRIVATE_debugCast(e);return _.persistence.runTransaction("Save named query","readwrite",(e=>{const h=__PRIVATE_fromVersion(i.readTime);if(o.snapshotVersion.compareTo(h)>=0)return _.Gr.saveNamedQuery(e,i);const d=o.withResumeToken(ByteString.EMPTY_BYTE_STRING,h);return _.os=_.os.insert(d.targetId,d),_.Ur.updateTargetData(e,d).next((()=>_.Ur.removeMatchingKeysForTargetId(e,o.targetId))).next((()=>_.Ur.addMatchingKeys(e,s,o.targetId))).next((()=>_.Gr.saveNamedQuery(e,i)))}))}function createWebStorageClientStateKey(e,i){return`firestore_clients_${e}_${i}`}function createWebStorageMutationBatchKey(e,i,s){let o=`firestore_mutations_${e}_${s}`;return i.isAuthenticated()&&(o+=`_${i.uid}`),o}function createWebStorageQueryTargetMetadataKey(e,i){return`firestore_targets_${e}_${i}`}class __PRIVATE_MutationMetadata{constructor(e,i,s,o){this.user=e,this.batchId=i,this.state=s,this.error=o}static Rs(e,i,s){const o=JSON.parse(s);let _,h="object"==typeof o&&-1!==["pending","acknowledged","rejected"].indexOf(o.state)&&(void 0===o.error||"object"==typeof o.error);return h&&o.error&&(h="string"==typeof o.error.message&&"string"==typeof o.error.code,h&&(_=new FirestoreError(o.error.code,o.error.message))),h?new __PRIVATE_MutationMetadata(e,i,o.state,_):(__PRIVATE_logError("SharedClientState",`Failed to parse mutation state for ID '${i}': ${s}`),null)}Vs(){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 __PRIVATE_QueryTargetMetadata{constructor(e,i,s){this.targetId=e,this.state=i,this.error=s}static Rs(e,i){const s=JSON.parse(i);let o,_="object"==typeof s&&-1!==["not-current","current","rejected"].indexOf(s.state)&&(void 0===s.error||"object"==typeof s.error);return _&&s.error&&(_="string"==typeof s.error.message&&"string"==typeof s.error.code,_&&(o=new FirestoreError(s.error.code,s.error.message))),_?new __PRIVATE_QueryTargetMetadata(e,s.state,o):(__PRIVATE_logError("SharedClientState",`Failed to parse target state for ID '${e}': ${i}`),null)}Vs(){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 __PRIVATE_RemoteClientState{constructor(e,i){this.clientId=e,this.activeTargetIds=i}static Rs(e,i){const s=JSON.parse(i);let o="object"==typeof s&&s.activeTargetIds instanceof Array,_=__PRIVATE_targetIdSet();for(let e=0;o&&e<s.activeTargetIds.length;++e)o=isSafeInteger(s.activeTargetIds[e]),_=_.add(s.activeTargetIds[e]);return o?new __PRIVATE_RemoteClientState(e,_):(__PRIVATE_logError("SharedClientState",`Failed to parse client data for instance '${e}': ${i}`),null)}}class __PRIVATE_SharedOnlineState{constructor(e,i){this.clientId=e,this.onlineState=i}static Rs(e){const i=JSON.parse(e);return"object"==typeof i&&-1!==["Unknown","Online","Offline"].indexOf(i.onlineState)&&"string"==typeof i.clientId?new __PRIVATE_SharedOnlineState(i.clientId,i.onlineState):(__PRIVATE_logError("SharedClientState",`Failed to parse online state: ${e}`),null)}}class __PRIVATE_LocalClientState{constructor(){this.activeTargetIds=__PRIVATE_targetIdSet()}fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Vs(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class __PRIVATE_WebStorageSharedClientState{constructor(e,i,s,o,_){this.window=e,this.ui=i,this.persistenceKey=s,this.ps=o,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ys=this.ws.bind(this),this.Ss=new SortedMap(__PRIVATE_primitiveComparator),this.started=!1,this.bs=[];const h=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=_,this.Ds=createWebStorageClientStateKey(this.persistenceKey,this.ps),this.vs=function createWebStorageSequenceNumberKey(e){return`firestore_sequence_number_${e}`}(this.persistenceKey),this.Ss=this.Ss.insert(this.ps,new __PRIVATE_LocalClientState),this.Cs=new RegExp(`^firestore_clients_${h}_([^_]*)$`),this.Fs=new RegExp(`^firestore_mutations_${h}_(\\d+)(?:_(.*))?$`),this.Ms=new RegExp(`^firestore_targets_${h}_(\\d+)$`),this.xs=function createWebStorageOnlineStateKey(e){return`firestore_online_state_${e}`}(this.persistenceKey),this.Os=function createBundleLoadedKey(e){return`firestore_bundle_loaded_v2_${e}`}(this.persistenceKey),this.window.addEventListener("storage",this.ys)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Qi();for(const i of e){if(i===this.ps)continue;const e=this.getItem(createWebStorageClientStateKey(this.persistenceKey,i));if(e){const s=__PRIVATE_RemoteClientState.Rs(i,e);s&&(this.Ss=this.Ss.insert(s.clientId,s))}}this.Ns();const i=this.storage.getItem(this.xs);if(i){const e=this.Ls(i);e&&this.Bs(e)}for(const e of this.bs)this.ws(e);this.bs=[],this.window.addEventListener("pagehide",(()=>this.shutdown())),this.started=!0}writeSequenceNumber(e){this.setItem(this.vs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ks(this.Ss)}isActiveQueryTarget(e){let i=!1;return this.Ss.forEach(((s,o)=>{o.activeTargetIds.has(e)&&(i=!0)})),i}addPendingMutation(e){this.qs(e,"pending")}updateMutationState(e,i,s){this.qs(e,i,s),this.Qs(e)}addLocalQueryTarget(e,i=!0){let s="not-current";if(this.isActiveQueryTarget(e)){const i=this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey,e));if(i){const o=__PRIVATE_QueryTargetMetadata.Rs(e,i);o&&(s=o.state)}}return i&&this.Ks.fs(e),this.Ns(),s}removeLocalQueryTarget(e){this.Ks.gs(e),this.Ns()}isLocalQueryTarget(e){return this.Ks.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey,e))}updateQueryState(e,i,s){this.$s(e,i,s)}handleUserChange(e,i,s){i.forEach((e=>{this.Qs(e)})),this.currentUser=e,s.forEach((e=>{this.addPendingMutation(e)}))}setOnlineState(e){this.Us(e)}notifyBundleLoaded(e){this.Ws(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ys),this.removeItem(this.Ds),this.started=!1)}getItem(e){const i=this.storage.getItem(e);return __PRIVATE_logDebug("SharedClientState","READ",e,i),i}setItem(e,i){__PRIVATE_logDebug("SharedClientState","SET",e,i),this.storage.setItem(e,i)}removeItem(e){__PRIVATE_logDebug("SharedClientState","REMOVE",e),this.storage.removeItem(e)}ws(e){const i=e;if(i.storageArea===this.storage){if(__PRIVATE_logDebug("SharedClientState","EVENT",i.key,i.newValue),i.key===this.Ds)return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.ui.enqueueRetryable((async()=>{if(this.started){if(null!==i.key)if(this.Cs.test(i.key)){if(null==i.newValue){const e=this.Gs(i.key);return this.zs(e,null)}{const e=this.js(i.key,i.newValue);if(e)return this.zs(e.clientId,e)}}else if(this.Fs.test(i.key)){if(null!==i.newValue){const e=this.Hs(i.key,i.newValue);if(e)return this.Js(e)}}else if(this.Ms.test(i.key)){if(null!==i.newValue){const e=this.Ys(i.key,i.newValue);if(e)return this.Zs(e)}}else if(i.key===this.xs){if(null!==i.newValue){const e=this.Ls(i.newValue);if(e)return this.Bs(e)}}else if(i.key===this.vs){const e=function __PRIVATE_fromWebStorageSequenceNumber(e){let i=__PRIVATE_ListenSequence.oe;if(null!=e)try{const s=JSON.parse(e);__PRIVATE_hardAssert("number"==typeof s),i=s}catch(e){__PRIVATE_logError("SharedClientState","Failed to read sequence number from WebStorage",e)}return i}(i.newValue);e!==__PRIVATE_ListenSequence.oe&&this.sequenceNumberHandler(e)}else if(i.key===this.Os){const e=this.Xs(i.newValue);await Promise.all(e.map((e=>this.syncEngine.eo(e))))}}else this.bs.push(i)}))}}get Ks(){return this.Ss.get(this.ps)}Ns(){this.setItem(this.Ds,this.Ks.Vs())}qs(e,i,s){const o=new __PRIVATE_MutationMetadata(this.currentUser,e,i,s),_=createWebStorageMutationBatchKey(this.persistenceKey,this.currentUser,e);this.setItem(_,o.Vs())}Qs(e){const i=createWebStorageMutationBatchKey(this.persistenceKey,this.currentUser,e);this.removeItem(i)}Us(e){const i={clientId:this.ps,onlineState:e};this.storage.setItem(this.xs,JSON.stringify(i))}$s(e,i,s){const o=createWebStorageQueryTargetMetadataKey(this.persistenceKey,e),_=new __PRIVATE_QueryTargetMetadata(e,i,s);this.setItem(o,_.Vs())}Ws(e){const i=JSON.stringify(Array.from(e));this.setItem(this.Os,i)}Gs(e){const i=this.Cs.exec(e);return i?i[1]:null}js(e,i){const s=this.Gs(e);return __PRIVATE_RemoteClientState.Rs(s,i)}Hs(e,i){const s=this.Fs.exec(e),o=Number(s[1]),_=void 0!==s[2]?s[2]:null;return __PRIVATE_MutationMetadata.Rs(new User(_),o,i)}Ys(e,i){const s=this.Ms.exec(e),o=Number(s[1]);return __PRIVATE_QueryTargetMetadata.Rs(o,i)}Ls(e){return __PRIVATE_SharedOnlineState.Rs(e)}Xs(e){return JSON.parse(e)}async Js(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.no(e.batchId,e.state,e.error);__PRIVATE_logDebug("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Zs(e){return this.syncEngine.ro(e.targetId,e.state,e.error)}zs(e,i){const s=i?this.Ss.insert(e,i):this.Ss.remove(e),o=this.ks(this.Ss),_=this.ks(s),h=[],d=[];return _.forEach((e=>{o.has(e)||h.push(e)})),o.forEach((e=>{_.has(e)||d.push(e)})),this.syncEngine.io(h,d).then((()=>{this.Ss=s}))}Bs(e){this.Ss.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ks(e){let i=__PRIVATE_targetIdSet();return e.forEach(((e,s)=>{i=i.unionWith(s.activeTargetIds)})),i}}class __PRIVATE_MemorySharedClientState{constructor(){this.so=new __PRIVATE_LocalClientState,this.oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,i,s){}addLocalQueryTarget(e,i=!0){return i&&this.so.fs(e),this.oo[e]||"not-current"}updateQueryState(e,i,s){this.oo[e]=i}removeLocalQueryTarget(e){this.so.gs(e)}isLocalQueryTarget(e){return this.so.activeTargetIds.has(e)}clearQueryState(e){delete this.oo[e]}getAllActiveQueryTargets(){return this.so.activeTargetIds}isActiveQueryTarget(e){return this.so.activeTargetIds.has(e)}start(){return this.so=new __PRIVATE_LocalClientState,Promise.resolve()}handleUserChange(e,i,s){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class __PRIVATE_NoopConnectivityMonitor{_o(e){}shutdown(){}}class __PRIVATE_BrowserConnectivityMonitor{constructor(){this.ao=()=>this.uo(),this.co=()=>this.lo(),this.ho=[],this.Po()}_o(e){this.ho.push(e)}shutdown(){window.removeEventListener("online",this.ao),window.removeEventListener("offline",this.co)}Po(){window.addEventListener("online",this.ao),window.addEventListener("offline",this.co)}uo(){__PRIVATE_logDebug("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ho)e(0)}lo(){__PRIVATE_logDebug("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ho)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let rt=null;function __PRIVATE_generateUniqueDebugId(){return null===rt?rt=function __PRIVATE_generateInitialUniqueDebugId(){return 268435456+Math.round(2147483648*Math.random())}():rt++,"0x"+rt.toString(16)}const it={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class __PRIVATE_StreamBridge{constructor(e){this.Io=e.Io,this.To=e.To}Eo(e){this.Ao=e}Ro(e){this.Vo=e}mo(e){this.fo=e}onMessage(e){this.po=e}close(){this.To()}send(e){this.Io(e)}yo(){this.Ao()}wo(){this.Vo()}So(e){this.fo(e)}bo(e){this.po(e)}}const st="WebChannelConnection";class __PRIVATE_WebChannelConnection extends class __PRIVATE_RestConnection{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const i=e.ssl?"https":"http",s=encodeURIComponent(this.databaseId.projectId),o=encodeURIComponent(this.databaseId.database);this.Do=i+"://"+e.host,this.vo=`projects/${s}/databases/${o}`,this.Co="(default)"===this.databaseId.database?`project_id=${s}`:`project_id=${s}&database_id=${o}`}get Fo(){return!1}Mo(e,i,s,o,_){const h=__PRIVATE_generateUniqueDebugId(),d=this.xo(e,i.toUriEncodedString());__PRIVATE_logDebug("RestConnection",`Sending RPC '${e}' ${h}:`,d,s);const f={"google-cloud-resource-prefix":this.vo,"x-goog-request-params":this.Co};return this.Oo(f,o,_),this.No(e,d,f,s).then((i=>(__PRIVATE_logDebug("RestConnection",`Received RPC '${e}' ${h}: `,i),i)),(i=>{throw __PRIVATE_logWarn("RestConnection",`RPC '${e}' ${h} failed with error: `,i,"url: ",d,"request:",s),i}))}Lo(e,i,s,o,_,h){return this.Mo(e,i,s,o,_)}Oo(e,i,s){e["X-Goog-Api-Client"]=function __PRIVATE_getGoogApiClientValue(){return"gl-js/ fire/"+ce}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),i&&i.headers.forEach(((i,s)=>e[s]=i)),s&&s.headers.forEach(((i,s)=>e[s]=i))}xo(e,i){const s=it[e];return`${this.Do}/v1/${i}:${s}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}No(e,i,s,o){const _=__PRIVATE_generateUniqueDebugId();return new Promise(((h,d)=>{const f=new $;f.setWithCredentials(!0),f.listenOnce(te.COMPLETE,(()=>{try{switch(f.getLastErrorCode()){case ne.NO_ERROR:const i=f.getResponseJson();__PRIVATE_logDebug(st,`XHR for RPC '${e}' ${_} received:`,JSON.stringify(i)),h(i);break;case ne.TIMEOUT:__PRIVATE_logDebug(st,`RPC '${e}' ${_} timed out`),d(new FirestoreError(_e.DEADLINE_EXCEEDED,"Request time out"));break;case ne.HTTP_ERROR:const s=f.getStatus();if(__PRIVATE_logDebug(st,`RPC '${e}' ${_} failed with status:`,s,"response text:",f.getResponseText()),s>0){let e=f.getResponseJson();Array.isArray(e)&&(e=e[0]);const i=null==e?void 0:e.error;if(i&&i.status&&i.message){const e=function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e){const i=e.toLowerCase().replace(/_/g,"-");return Object.values(_e).indexOf(i)>=0?i:_e.UNKNOWN}(i.status);d(new FirestoreError(e,i.message))}else d(new FirestoreError(_e.UNKNOWN,"Server responded with status "+f.getStatus()))}else d(new FirestoreError(_e.UNAVAILABLE,"Connection failed."));break;default:fail()}}finally{__PRIVATE_logDebug(st,`RPC '${e}' ${_} completed.`)}}));const g=JSON.stringify(o);__PRIVATE_logDebug(st,`RPC '${e}' ${_} sending request:`,o),f.send(i,"POST",g,s,15)}))}Bo(e,i,s){const o=__PRIVATE_generateUniqueDebugId(),_=[this.Do,"/","google.firestore.v1.Firestore","/",e,"/channel"],h=oe(),d=se(),f={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},g=this.longPollingOptions.timeoutSeconds;void 0!==g&&(f.longPollingTimeout=Math.round(1e3*g)),this.useFetchStreams&&(f.useFetchStreams=!0),this.Oo(f.initMessageHeaders,i,s),f.encodeInitMessageHeaders=!0;const b=_.join("");__PRIVATE_logDebug(st,`Creating RPC '${e}' stream ${o}: ${b}`,f);const w=h.createWebChannel(b,f);let O=!1,q=!1;const j=new __PRIVATE_StreamBridge({Io:i=>{q?__PRIVATE_logDebug(st,`Not sending because RPC '${e}' stream ${o} is closed:`,i):(O||(__PRIVATE_logDebug(st,`Opening RPC '${e}' stream ${o} transport.`),w.open(),O=!0),__PRIVATE_logDebug(st,`RPC '${e}' stream ${o} sending:`,i),w.send(i))},To:()=>w.close()}),__PRIVATE_unguardedEventListen=(e,i,s)=>{e.listen(i,(e=>{try{s(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return __PRIVATE_unguardedEventListen(w,ee.EventType.OPEN,(()=>{q||(__PRIVATE_logDebug(st,`RPC '${e}' stream ${o} transport opened.`),j.yo())})),__PRIVATE_unguardedEventListen(w,ee.EventType.CLOSE,(()=>{q||(q=!0,__PRIVATE_logDebug(st,`RPC '${e}' stream ${o} transport closed`),j.So())})),__PRIVATE_unguardedEventListen(w,ee.EventType.ERROR,(i=>{q||(q=!0,__PRIVATE_logWarn(st,`RPC '${e}' stream ${o} transport errored:`,i),j.So(new FirestoreError(_e.UNAVAILABLE,"The operation could not be completed")))})),__PRIVATE_unguardedEventListen(w,ee.EventType.MESSAGE,(i=>{var s;if(!q){const _=i.data[0];__PRIVATE_hardAssert(!!_);const h=_,d=h.error||(null===(s=h[0])||void 0===s?void 0:s.error);if(d){__PRIVATE_logDebug(st,`RPC '${e}' stream ${o} received error:`,d);const i=d.status;let s=function __PRIVATE_mapCodeFromRpcStatus(e){const i=We[e];if(void 0!==i)return __PRIVATE_mapCodeFromRpcCode(i)}(i),_=d.message;void 0===s&&(s=_e.INTERNAL,_="Unknown error status: "+i+" with message "+d.message),q=!0,j.So(new FirestoreError(s,_)),w.close()}else __PRIVATE_logDebug(st,`RPC '${e}' stream ${o} received:`,_),j.bo(_)}})),__PRIVATE_unguardedEventListen(d,ie.STAT_EVENT,(i=>{i.stat===re.PROXY?__PRIVATE_logDebug(st,`RPC '${e}' stream ${o} detected buffering proxy`):i.stat===re.NOPROXY&&__PRIVATE_logDebug(st,`RPC '${e}' stream ${o} detected no buffering proxy`)})),setTimeout((()=>{j.wo()}),0),j}}function __PRIVATE_getWindow(){return"undefined"!=typeof window?window:null}function getDocument(){return"undefined"!=typeof document?document:null}function __PRIVATE_newSerializer(e){return new JsonProtoSerializer(e,!0)}class __PRIVATE_ExponentialBackoff{constructor(e,i,s=1e3,o=1.5,_=6e4){this.ui=e,this.timerId=i,this.ko=s,this.qo=o,this.Qo=_,this.Ko=0,this.$o=null,this.Uo=Date.now(),this.reset()}reset(){this.Ko=0}Wo(){this.Ko=this.Qo}Go(e){this.cancel();const i=Math.floor(this.Ko+this.zo()),s=Math.max(0,Date.now()-this.Uo),o=Math.max(0,i-s);o>0&&__PRIVATE_logDebug("ExponentialBackoff",`Backing off for ${o} ms (base delay: ${this.Ko} ms, delay with jitter: ${i} ms, last attempt: ${s} ms ago)`),this.$o=this.ui.enqueueAfterDelay(this.timerId,o,(()=>(this.Uo=Date.now(),e()))),this.Ko*=this.qo,this.Ko<this.ko&&(this.Ko=this.ko),this.Ko>this.Qo&&(this.Ko=this.Qo)}jo(){null!==this.$o&&(this.$o.skipDelay(),this.$o=null)}cancel(){null!==this.$o&&(this.$o.cancel(),this.$o=null)}zo(){return(Math.random()-.5)*this.Ko}}class __PRIVATE_PersistentStream{constructor(e,i,s,o,_,h,d,f){this.ui=e,this.Ho=s,this.Jo=o,this.connection=_,this.authCredentialsProvider=h,this.appCheckCredentialsProvider=d,this.listener=f,this.state=0,this.Yo=0,this.Zo=null,this.Xo=null,this.stream=null,this.e_=0,this.t_=new __PRIVATE_ExponentialBackoff(e,i)}n_(){return 1===this.state||5===this.state||this.r_()}r_(){return 2===this.state||3===this.state}start(){this.e_=0,4!==this.state?this.auth():this.i_()}async stop(){this.n_()&&await this.close(0)}s_(){this.state=0,this.t_.reset()}o_(){this.r_()&&null===this.Zo&&(this.Zo=this.ui.enqueueAfterDelay(this.Ho,6e4,(()=>this.__())))}a_(e){this.u_(),this.stream.send(e)}async __(){if(this.r_())return this.close(0)}u_(){this.Zo&&(this.Zo.cancel(),this.Zo=null)}c_(){this.Xo&&(this.Xo.cancel(),this.Xo=null)}async close(e,i){this.u_(),this.c_(),this.t_.cancel(),this.Yo++,4!==e?this.t_.reset():i&&i.code===_e.RESOURCE_EXHAUSTED?(__PRIVATE_logError(i.toString()),__PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."),this.t_.Wo()):i&&i.code===_e.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.l_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.mo(i)}l_(){}auth(){this.state=1;const e=this.h_(this.Yo),i=this.Yo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,s])=>{this.Yo===i&&this.P_(e,s)}),(i=>{e((()=>{const e=new FirestoreError(_e.UNKNOWN,"Fetching auth token failed: "+i.message);return this.I_(e)}))}))}P_(e,i){const s=this.h_(this.Yo);this.stream=this.T_(e,i),this.stream.Eo((()=>{s((()=>this.listener.Eo()))})),this.stream.Ro((()=>{s((()=>(this.state=2,this.Xo=this.ui.enqueueAfterDelay(this.Jo,1e4,(()=>(this.r_()&&(this.state=3),Promise.resolve()))),this.listener.Ro())))})),this.stream.mo((e=>{s((()=>this.I_(e)))})),this.stream.onMessage((e=>{s((()=>1==++this.e_?this.E_(e):this.onNext(e)))}))}i_(){this.state=5,this.t_.Go((async()=>{this.state=0,this.start()}))}I_(e){return __PRIVATE_logDebug("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}h_(e){return i=>{this.ui.enqueueAndForget((()=>this.Yo===e?i():(__PRIVATE_logDebug("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream{constructor(e,i,s,o,_,h){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",i,s,o,h),this.serializer=_}T_(e,i){return this.connection.Bo("Listen",e,i)}E_(e){return this.onNext(e)}onNext(e){this.t_.reset();const i=function __PRIVATE_fromWatchChange(e,i){let s;if("targetChange"in i){i.targetChange;const o=function __PRIVATE_fromWatchTargetChangeState(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:fail()}(i.targetChange.targetChangeType||"NO_CHANGE"),_=i.targetChange.targetIds||[],h=function __PRIVATE_fromBytes(e,i){return e.useProto3Json?(__PRIVATE_hardAssert(void 0===i||"string"==typeof i),ByteString.fromBase64String(i||"")):(__PRIVATE_hardAssert(void 0===i||i instanceof Buffer||i instanceof Uint8Array),ByteString.fromUint8Array(i||new Uint8Array))}(e,i.targetChange.resumeToken),d=i.targetChange.cause,f=d&&function __PRIVATE_fromRpcStatus(e){const i=void 0===e.code?_e.UNKNOWN:__PRIVATE_mapCodeFromRpcCode(e.code);return new FirestoreError(i,e.message||"")}(d);s=new __PRIVATE_WatchTargetChange(o,_,h,f||null)}else if("documentChange"in i){i.documentChange;const o=i.documentChange;o.document,o.document.name,o.document.updateTime;const _=fromName(e,o.document.name),h=__PRIVATE_fromVersion(o.document.updateTime),d=o.document.createTime?__PRIVATE_fromVersion(o.document.createTime):SnapshotVersion.min(),f=new ObjectValue({mapValue:{fields:o.document.fields}}),g=MutableDocument.newFoundDocument(_,h,d,f),b=o.targetIds||[],w=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange(b,w,g.key,g)}else if("documentDelete"in i){i.documentDelete;const o=i.documentDelete;o.document;const _=fromName(e,o.document),h=o.readTime?__PRIVATE_fromVersion(o.readTime):SnapshotVersion.min(),d=MutableDocument.newNoDocument(_,h),f=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange([],f,d.key,d)}else if("documentRemove"in i){i.documentRemove;const o=i.documentRemove;o.document;const _=fromName(e,o.document),h=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange([],h,_,null)}else{if(!("filter"in i))return fail();{i.filter;const e=i.filter;e.targetId;const{count:o=0,unchangedNames:_}=e,h=new ExistenceFilter(o,_),d=e.targetId;s=new __PRIVATE_ExistenceFilterChange(d,h)}}return s}(this.serializer,e),s=function __PRIVATE_versionFromListenResponse(e){if(!("targetChange"in e))return SnapshotVersion.min();const i=e.targetChange;return i.targetIds&&i.targetIds.length?SnapshotVersion.min():i.readTime?__PRIVATE_fromVersion(i.readTime):SnapshotVersion.min()}(e);return this.listener.d_(i,s)}A_(e){const i={};i.database=__PRIVATE_getEncodedDatabaseId(this.serializer),i.addTarget=function __PRIVATE_toTarget(e,i){let s;const o=i.target;if(s=__PRIVATE_targetIsDocumentTarget(o)?{documents:__PRIVATE_toDocumentsTarget(e,o)}:{query:__PRIVATE_toQueryTarget(e,o)._t},s.targetId=i.targetId,i.resumeToken.approximateByteSize()>0){s.resumeToken=__PRIVATE_toBytes(e,i.resumeToken);const o=__PRIVATE_toInt32Proto(e,i.expectedCount);null!==o&&(s.expectedCount=o)}else if(i.snapshotVersion.compareTo(SnapshotVersion.min())>0){s.readTime=toTimestamp(e,i.snapshotVersion.toTimestamp());const o=__PRIVATE_toInt32Proto(e,i.expectedCount);null!==o&&(s.expectedCount=o)}return s}(this.serializer,e);const s=function __PRIVATE_toListenRequestLabels(e,i){const s=function __PRIVATE_toLabel(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 fail()}}(i.purpose);return null==s?null:{"goog-listen-tags":s}}(this.serializer,e);s&&(i.labels=s),this.a_(i)}R_(e){const i={};i.database=__PRIVATE_getEncodedDatabaseId(this.serializer),i.removeTarget=e,this.a_(i)}}class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream{constructor(e,i,s,o,_,h){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",i,s,o,h),this.serializer=_}get V_(){return this.e_>0}start(){this.lastStreamToken=void 0,super.start()}l_(){this.V_&&this.m_([])}T_(e,i){return this.connection.Bo("Write",e,i)}E_(e){return __PRIVATE_hardAssert(!!e.streamToken),this.lastStreamToken=e.streamToken,__PRIVATE_hardAssert(!e.writeResults||0===e.writeResults.length),this.listener.f_()}onNext(e){__PRIVATE_hardAssert(!!e.streamToken),this.lastStreamToken=e.streamToken,this.t_.reset();const i=function __PRIVATE_fromWriteResults(e,i){return e&&e.length>0?(__PRIVATE_hardAssert(void 0!==i),e.map((e=>function __PRIVATE_fromWriteResult(e,i){let s=e.updateTime?__PRIVATE_fromVersion(e.updateTime):__PRIVATE_fromVersion(i);return s.isEqual(SnapshotVersion.min())&&(s=__PRIVATE_fromVersion(i)),new MutationResult(s,e.transformResults||[])}(e,i)))):[]}(e.writeResults,e.commitTime),s=__PRIVATE_fromVersion(e.commitTime);return this.listener.g_(s,i)}p_(){const e={};e.database=__PRIVATE_getEncodedDatabaseId(this.serializer),this.a_(e)}m_(e){const i={streamToken:this.lastStreamToken,writes:e.map((e=>toMutation(this.serializer,e)))};this.a_(i)}}class __PRIVATE_DatastoreImpl extends class Datastore{}{constructor(e,i,s,o){super(),this.authCredentials=e,this.appCheckCredentials=i,this.connection=s,this.serializer=o,this.y_=!1}w_(){if(this.y_)throw new FirestoreError(_e.FAILED_PRECONDITION,"The client has already been terminated.")}Mo(e,i,s,o){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([_,h])=>this.connection.Mo(e,__PRIVATE_toResourcePath(i,s),o,_,h))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_e.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(_e.UNKNOWN,e.toString())}))}Lo(e,i,s,o,_){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([h,d])=>this.connection.Lo(e,__PRIVATE_toResourcePath(i,s),o,h,d,_))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_e.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(_e.UNKNOWN,e.toString())}))}terminate(){this.y_=!0,this.connection.terminate()}}class __PRIVATE_OnlineStateTracker{constructor(e,i){this.asyncQueue=e,this.onlineStateHandler=i,this.state="Unknown",this.S_=0,this.b_=null,this.D_=!0}v_(){0===this.S_&&(this.C_("Unknown"),this.b_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.b_=null,this.F_("Backend didn't respond within 10 seconds."),this.C_("Offline"),Promise.resolve()))))}M_(e){"Online"===this.state?this.C_("Unknown"):(this.S_++,this.S_>=1&&(this.x_(),this.F_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.C_("Offline")))}set(e){this.x_(),this.S_=0,"Online"===e&&(this.D_=!1),this.C_(e)}C_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}F_(e){const i=`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.D_?(__PRIVATE_logError(i),this.D_=!1):__PRIVATE_logDebug("OnlineStateTracker",i)}x_(){null!==this.b_&&(this.b_.cancel(),this.b_=null)}}class __PRIVATE_RemoteStoreImpl{constructor(e,i,s,o,_){this.localStore=e,this.datastore=i,this.asyncQueue=s,this.remoteSyncer={},this.O_=[],this.N_=new Map,this.L_=new Set,this.B_=[],this.k_=_,this.k_._o((e=>{s.enqueueAndForget((async()=>{__PRIVATE_canUseNetwork(this)&&(__PRIVATE_logDebug("RemoteStore","Restarting streams for network reachability change."),await async function __PRIVATE_restartNetwork(e){const i=__PRIVATE_debugCast(e);i.L_.add(4),await __PRIVATE_disableNetworkInternal(i),i.q_.set("Unknown"),i.L_.delete(4),await __PRIVATE_enableNetworkInternal(i)}(this))}))})),this.q_=new __PRIVATE_OnlineStateTracker(s,o)}}async function __PRIVATE_enableNetworkInternal(e){if(__PRIVATE_canUseNetwork(e))for(const i of e.B_)await i(!0)}async function __PRIVATE_disableNetworkInternal(e){for(const i of e.B_)await i(!1)}function __PRIVATE_remoteStoreListen(e,i){const s=__PRIVATE_debugCast(e);s.N_.has(i.targetId)||(s.N_.set(i.targetId,i),__PRIVATE_shouldStartWatchStream(s)?__PRIVATE_startWatchStream(s):__PRIVATE_ensureWatchStream(s).r_()&&__PRIVATE_sendWatchRequest(s,i))}function __PRIVATE_remoteStoreUnlisten(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_ensureWatchStream(s);s.N_.delete(i),o.r_()&&__PRIVATE_sendUnwatchRequest(s,i),0===s.N_.size&&(o.r_()?o.o_():__PRIVATE_canUseNetwork(s)&&s.q_.set("Unknown"))}function __PRIVATE_sendWatchRequest(e,i){if(e.Q_.xe(i.targetId),i.resumeToken.approximateByteSize()>0||i.snapshotVersion.compareTo(SnapshotVersion.min())>0){const s=e.remoteSyncer.getRemoteKeysForTarget(i.targetId).size;i=i.withExpectedCount(s)}__PRIVATE_ensureWatchStream(e).A_(i)}function __PRIVATE_sendUnwatchRequest(e,i){e.Q_.xe(i),__PRIVATE_ensureWatchStream(e).R_(i)}function __PRIVATE_startWatchStream(e){e.Q_=new __PRIVATE_WatchChangeAggregator({getRemoteKeysForTarget:i=>e.remoteSyncer.getRemoteKeysForTarget(i),ot:i=>e.N_.get(i)||null,tt:()=>e.datastore.serializer.databaseId}),__PRIVATE_ensureWatchStream(e).start(),e.q_.v_()}function __PRIVATE_shouldStartWatchStream(e){return __PRIVATE_canUseNetwork(e)&&!__PRIVATE_ensureWatchStream(e).n_()&&e.N_.size>0}function __PRIVATE_canUseNetwork(e){return 0===__PRIVATE_debugCast(e).L_.size}function __PRIVATE_cleanUpWatchStreamState(e){e.Q_=void 0}async function __PRIVATE_onWatchStreamConnected(e){e.q_.set("Online")}async function __PRIVATE_onWatchStreamOpen(e){e.N_.forEach(((i,s)=>{__PRIVATE_sendWatchRequest(e,i)}))}async function __PRIVATE_onWatchStreamClose(e,i){__PRIVATE_cleanUpWatchStreamState(e),__PRIVATE_shouldStartWatchStream(e)?(e.q_.M_(i),__PRIVATE_startWatchStream(e)):e.q_.set("Unknown")}async function __PRIVATE_onWatchStreamChange(e,i,s){if(e.q_.set("Online"),i instanceof __PRIVATE_WatchTargetChange&&2===i.state&&i.cause)try{await async function __PRIVATE_handleTargetError(e,i){const s=i.cause;for(const o of i.targetIds)e.N_.has(o)&&(await e.remoteSyncer.rejectListen(o,s),e.N_.delete(o),e.Q_.removeTarget(o))}(e,i)}catch(s){__PRIVATE_logDebug("RemoteStore","Failed to remove targets %s: %s ",i.targetIds.join(","),s),await __PRIVATE_disableNetworkUntilRecovery(e,s)}else if(i instanceof __PRIVATE_DocumentWatchChange?e.Q_.Ke(i):i instanceof __PRIVATE_ExistenceFilterChange?e.Q_.He(i):e.Q_.We(i),!s.isEqual(SnapshotVersion.min()))try{const i=await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);s.compareTo(i)>=0&&await function __PRIVATE_raiseWatchSnapshot(e,i){const s=e.Q_.rt(i);return s.targetChanges.forEach(((s,o)=>{if(s.resumeToken.approximateByteSize()>0){const _=e.N_.get(o);_&&e.N_.set(o,_.withResumeToken(s.resumeToken,i))}})),s.targetMismatches.forEach(((i,s)=>{const o=e.N_.get(i);if(!o)return;e.N_.set(i,o.withResumeToken(ByteString.EMPTY_BYTE_STRING,o.snapshotVersion)),__PRIVATE_sendUnwatchRequest(e,i);const _=new TargetData(o.target,i,s,o.sequenceNumber);__PRIVATE_sendWatchRequest(e,_)})),e.remoteSyncer.applyRemoteEvent(s)}(e,s)}catch(i){__PRIVATE_logDebug("RemoteStore","Failed to raise snapshot:",i),await __PRIVATE_disableNetworkUntilRecovery(e,i)}}async function __PRIVATE_disableNetworkUntilRecovery(e,i,s){if(!__PRIVATE_isIndexedDbTransactionError(i))throw i;e.L_.add(1),await __PRIVATE_disableNetworkInternal(e),e.q_.set("Offline"),s||(s=()=>__PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{__PRIVATE_logDebug("RemoteStore","Retrying IndexedDB access"),await s(),e.L_.delete(1),await __PRIVATE_enableNetworkInternal(e)}))}function __PRIVATE_executeWithRecovery(e,i){return i().catch((s=>__PRIVATE_disableNetworkUntilRecovery(e,s,i)))}async function __PRIVATE_fillWritePipeline(e){const i=__PRIVATE_debugCast(e),s=__PRIVATE_ensureWriteStream(i);let o=i.O_.length>0?i.O_[i.O_.length-1].batchId:-1;for(;__PRIVATE_canAddToWritePipeline(i);)try{const e=await __PRIVATE_localStoreGetNextMutationBatch(i.localStore,o);if(null===e){0===i.O_.length&&s.o_();break}o=e.batchId,__PRIVATE_addToWritePipeline(i,e)}catch(e){await __PRIVATE_disableNetworkUntilRecovery(i,e)}__PRIVATE_shouldStartWriteStream(i)&&__PRIVATE_startWriteStream(i)}function __PRIVATE_canAddToWritePipeline(e){return __PRIVATE_canUseNetwork(e)&&e.O_.length<10}function __PRIVATE_addToWritePipeline(e,i){e.O_.push(i);const s=__PRIVATE_ensureWriteStream(e);s.r_()&&s.V_&&s.m_(i.mutations)}function __PRIVATE_shouldStartWriteStream(e){return __PRIVATE_canUseNetwork(e)&&!__PRIVATE_ensureWriteStream(e).n_()&&e.O_.length>0}function __PRIVATE_startWriteStream(e){__PRIVATE_ensureWriteStream(e).start()}async function __PRIVATE_onWriteStreamOpen(e){__PRIVATE_ensureWriteStream(e).p_()}async function __PRIVATE_onWriteHandshakeComplete(e){const i=__PRIVATE_ensureWriteStream(e);for(const s of e.O_)i.m_(s.mutations)}async function __PRIVATE_onMutationResult(e,i,s){const o=e.O_.shift(),_=MutationBatchResult.from(o,i,s);await __PRIVATE_executeWithRecovery(e,(()=>e.remoteSyncer.applySuccessfulWrite(_))),await __PRIVATE_fillWritePipeline(e)}async function __PRIVATE_onWriteStreamClose(e,i){i&&__PRIVATE_ensureWriteStream(e).V_&&await async function __PRIVATE_handleWriteError(e,i){if(function __PRIVATE_isPermanentWriteError(e){return __PRIVATE_isPermanentError(e)&&e!==_e.ABORTED}(i.code)){const s=e.O_.shift();__PRIVATE_ensureWriteStream(e).s_(),await __PRIVATE_executeWithRecovery(e,(()=>e.remoteSyncer.rejectFailedWrite(s.batchId,i))),await __PRIVATE_fillWritePipeline(e)}}(e,i),__PRIVATE_shouldStartWriteStream(e)&&__PRIVATE_startWriteStream(e)}async function __PRIVATE_remoteStoreHandleCredentialChange(e,i){const s=__PRIVATE_debugCast(e);s.asyncQueue.verifyOperationInProgress(),__PRIVATE_logDebug("RemoteStore","RemoteStore received new credentials");const o=__PRIVATE_canUseNetwork(s);s.L_.add(3),await __PRIVATE_disableNetworkInternal(s),o&&s.q_.set("Unknown"),await s.remoteSyncer.handleCredentialChange(i),s.L_.delete(3),await __PRIVATE_enableNetworkInternal(s)}async function __PRIVATE_remoteStoreApplyPrimaryState(e,i){const s=__PRIVATE_debugCast(e);i?(s.L_.delete(2),await __PRIVATE_enableNetworkInternal(s)):i||(s.L_.add(2),await __PRIVATE_disableNetworkInternal(s),s.q_.set("Unknown"))}function __PRIVATE_ensureWatchStream(e){return e.K_||(e.K_=function __PRIVATE_newPersistentWatchStream(e,i,s){const o=__PRIVATE_debugCast(e);return o.w_(),new __PRIVATE_PersistentListenStream(i,o.connection,o.authCredentials,o.appCheckCredentials,o.serializer,s)}(e.datastore,e.asyncQueue,{Eo:__PRIVATE_onWatchStreamConnected.bind(null,e),Ro:__PRIVATE_onWatchStreamOpen.bind(null,e),mo:__PRIVATE_onWatchStreamClose.bind(null,e),d_:__PRIVATE_onWatchStreamChange.bind(null,e)}),e.B_.push((async i=>{i?(e.K_.s_(),__PRIVATE_shouldStartWatchStream(e)?__PRIVATE_startWatchStream(e):e.q_.set("Unknown")):(await e.K_.stop(),__PRIVATE_cleanUpWatchStreamState(e))}))),e.K_}function __PRIVATE_ensureWriteStream(e){return e.U_||(e.U_=function __PRIVATE_newPersistentWriteStream(e,i,s){const o=__PRIVATE_debugCast(e);return o.w_(),new __PRIVATE_PersistentWriteStream(i,o.connection,o.authCredentials,o.appCheckCredentials,o.serializer,s)}(e.datastore,e.asyncQueue,{Eo:()=>Promise.resolve(),Ro:__PRIVATE_onWriteStreamOpen.bind(null,e),mo:__PRIVATE_onWriteStreamClose.bind(null,e),f_:__PRIVATE_onWriteHandshakeComplete.bind(null,e),g_:__PRIVATE_onMutationResult.bind(null,e)}),e.B_.push((async i=>{i?(e.U_.s_(),await __PRIVATE_fillWritePipeline(e)):(await e.U_.stop(),e.O_.length>0&&(__PRIVATE_logDebug("RemoteStore",`Stopping write stream with ${e.O_.length} pending writes`),e.O_=[]))}))),e.U_}class DelayedOperation{constructor(e,i,s,o,_){this.asyncQueue=e,this.timerId=i,this.targetTimeMs=s,this.op=o,this.removalCallback=_,this.deferred=new __PRIVATE_Deferred,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,i,s,o,_){const h=Date.now()+s,d=new DelayedOperation(e,i,h,o,_);return d.start(s),d}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FirestoreError(_e.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 __PRIVATE_wrapInUserErrorIfRecoverable(e,i){if(__PRIVATE_logError("AsyncQueue",`${i}: ${e}`),__PRIVATE_isIndexedDbTransactionError(e))return new FirestoreError(_e.UNAVAILABLE,`${i}: ${e}`);throw e}class DocumentSet{constructor(e){this.comparator=e?(i,s)=>e(i,s)||DocumentKey.comparator(i.key,s.key):(e,i)=>DocumentKey.comparator(e.key,i.key),this.keyedMap=documentMap(),this.sortedSet=new SortedMap(this.comparator)}static emptySet(e){return new DocumentSet(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const i=this.keyedMap.get(e);return i?this.sortedSet.indexOf(i):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((i,s)=>(e(i),!1)))}add(e){const i=this.delete(e.key);return i.copy(i.keyedMap.insert(e.key,e),i.sortedSet.insert(e,null))}delete(e){const i=this.get(e);return i?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(i)):this}isEqual(e){if(!(e instanceof DocumentSet))return!1;if(this.size!==e.size)return!1;const i=this.sortedSet.getIterator(),s=e.sortedSet.getIterator();for(;i.hasNext();){const e=i.getNext().key,o=s.getNext().key;if(!e.isEqual(o))return!1}return!0}toString(){const e=[];return this.forEach((i=>{e.push(i.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,i){const s=new DocumentSet;return s.comparator=this.comparator,s.keyedMap=e,s.sortedSet=i,s}}class __PRIVATE_DocumentChangeSet{constructor(){this.W_=new SortedMap(DocumentKey.comparator)}track(e){const i=e.doc.key,s=this.W_.get(i);s?0!==e.type&&3===s.type?this.W_=this.W_.insert(i,e):3===e.type&&1!==s.type?this.W_=this.W_.insert(i,{type:s.type,doc:e.doc}):2===e.type&&2===s.type?this.W_=this.W_.insert(i,{type:2,doc:e.doc}):2===e.type&&0===s.type?this.W_=this.W_.insert(i,{type:0,doc:e.doc}):1===e.type&&0===s.type?this.W_=this.W_.remove(i):1===e.type&&2===s.type?this.W_=this.W_.insert(i,{type:1,doc:s.doc}):0===e.type&&1===s.type?this.W_=this.W_.insert(i,{type:2,doc:e.doc}):fail():this.W_=this.W_.insert(i,e)}G_(){const e=[];return this.W_.inorderTraversal(((i,s)=>{e.push(s)})),e}}class ViewSnapshot{constructor(e,i,s,o,_,h,d,f,g){this.query=e,this.docs=i,this.oldDocs=s,this.docChanges=o,this.mutatedKeys=_,this.fromCache=h,this.syncStateChanged=d,this.excludesMetadataChanges=f,this.hasCachedResults=g}static fromInitialDocuments(e,i,s,o,_){const h=[];return i.forEach((e=>{h.push({type:0,doc:e})})),new ViewSnapshot(e,i,DocumentSet.emptySet(i),h,s,o,!0,!1,_)}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)&&__PRIVATE_queryEquals(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const i=this.docChanges,s=e.docChanges;if(i.length!==s.length)return!1;for(let e=0;e<i.length;e++)if(i[e].type!==s[e].type||!i[e].doc.isEqual(s[e].doc))return!1;return!0}}class __PRIVATE_QueryListenersInfo{constructor(){this.z_=void 0,this.j_=[]}H_(){return this.j_.some((e=>e.J_()))}}class __PRIVATE_EventManagerImpl{constructor(){this.queries=__PRIVATE_newQueriesObjectMap(),this.onlineState="Unknown",this.Y_=new Set}terminate(){!function __PRIVATE_errorAllTargets(e,i){const s=__PRIVATE_debugCast(e),o=s.queries;s.queries=__PRIVATE_newQueriesObjectMap(),o.forEach(((e,s)=>{for(const e of s.j_)e.onError(i)}))}(this,new FirestoreError(_e.ABORTED,"Firestore shutting down"))}}function __PRIVATE_newQueriesObjectMap(){return new ObjectMap((e=>__PRIVATE_canonifyQuery(e)),__PRIVATE_queryEquals)}async function __PRIVATE_eventManagerListen(e,i){const s=__PRIVATE_debugCast(e);let o=3;const _=i.query;let h=s.queries.get(_);h?!h.H_()&&i.J_()&&(o=2):(h=new __PRIVATE_QueryListenersInfo,o=i.J_()?0:1);try{switch(o){case 0:h.z_=await s.onListen(_,!0);break;case 1:h.z_=await s.onListen(_,!1);break;case 2:await s.onFirstRemoteStoreListen(_)}}catch(e){const s=__PRIVATE_wrapInUserErrorIfRecoverable(e,`Initialization of query '${__PRIVATE_stringifyQuery(i.query)}' failed`);return void i.onError(s)}s.queries.set(_,h),h.j_.push(i),i.Z_(s.onlineState),h.z_&&i.X_(h.z_)&&__PRIVATE_raiseSnapshotsInSyncEvent(s)}async function __PRIVATE_eventManagerUnlisten(e,i){const s=__PRIVATE_debugCast(e),o=i.query;let _=3;const h=s.queries.get(o);if(h){const e=h.j_.indexOf(i);e>=0&&(h.j_.splice(e,1),0===h.j_.length?_=i.J_()?0:1:!h.H_()&&i.J_()&&(_=2))}switch(_){case 0:return s.queries.delete(o),s.onUnlisten(o,!0);case 1:return s.queries.delete(o),s.onUnlisten(o,!1);case 2:return s.onLastRemoteStoreUnlisten(o);default:return}}function __PRIVATE_eventManagerOnWatchChange(e,i){const s=__PRIVATE_debugCast(e);let o=!1;for(const e of i){const i=e.query,_=s.queries.get(i);if(_){for(const i of _.j_)i.X_(e)&&(o=!0);_.z_=e}}o&&__PRIVATE_raiseSnapshotsInSyncEvent(s)}function __PRIVATE_eventManagerOnWatchError(e,i,s){const o=__PRIVATE_debugCast(e),_=o.queries.get(i);if(_)for(const e of _.j_)e.onError(s);o.queries.delete(i)}function __PRIVATE_raiseSnapshotsInSyncEvent(e){e.Y_.forEach((e=>{e.next()}))}var ot,at;(at=ot||(ot={})).ea="default",at.Cache="cache";class __PRIVATE_QueryListener{constructor(e,i,s){this.query=e,this.ta=i,this.na=!1,this.ra=null,this.onlineState="Unknown",this.options=s||{}}X_(e){if(!this.options.includeMetadataChanges){const i=[];for(const s of e.docChanges)3!==s.type&&i.push(s);e=new ViewSnapshot(e.query,e.docs,e.oldDocs,i,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let i=!1;return this.na?this.ia(e)&&(this.ta.next(e),i=!0):this.sa(e,this.onlineState)&&(this.oa(e),i=!0),this.ra=e,i}onError(e){this.ta.error(e)}Z_(e){this.onlineState=e;let i=!1;return this.ra&&!this.na&&this.sa(this.ra,e)&&(this.oa(this.ra),i=!0),i}sa(e,i){if(!e.fromCache)return!0;if(!this.J_())return!0;const s="Offline"!==i;return(!this.options._a||!s)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===i)}ia(e){if(e.docChanges.length>0)return!0;const i=this.ra&&this.ra.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!i)&&!0===this.options.includeMetadataChanges}oa(e){e=ViewSnapshot.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.na=!0,this.ta.next(e)}J_(){return this.options.source!==ot.Cache}}class __PRIVATE_SizedBundleElement{constructor(e,i){this.aa=e,this.byteLength=i}ua(){return"metadata"in this.aa}}class __PRIVATE_BundleConverterImpl{constructor(e){this.serializer=e}Es(e){return fromName(this.serializer,e)}ds(e){return e.metadata.exists?__PRIVATE_fromDocument(this.serializer,e.document,!1):MutableDocument.newNoDocument(this.Es(e.metadata.name),this.As(e.metadata.readTime))}As(e){return __PRIVATE_fromVersion(e)}}class __PRIVATE_BundleLoader{constructor(e,i,s){this.ca=e,this.localStore=i,this.serializer=s,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=__PRIVATE_bundleInitialProgress(e)}la(e){this.progress.bytesLoaded+=e.byteLength;let i=this.progress.documentsLoaded;if(e.aa.namedQuery)this.queries.push(e.aa.namedQuery);else if(e.aa.documentMetadata){this.documents.push({metadata:e.aa.documentMetadata}),e.aa.documentMetadata.exists||++i;const s=ResourcePath.fromString(e.aa.documentMetadata.name);this.collectionGroups.add(s.get(s.length-2))}else e.aa.document&&(this.documents[this.documents.length-1].document=e.aa.document,++i);return i!==this.progress.documentsLoaded?(this.progress.documentsLoaded=i,Object.assign({},this.progress)):null}ha(e){const i=new Map,s=new __PRIVATE_BundleConverterImpl(this.serializer);for(const o of e)if(o.metadata.queries){const e=s.Es(o.metadata.name);for(const s of o.metadata.queries){const o=(i.get(s)||__PRIVATE_documentKeySet()).add(e);i.set(s,o)}}return i}async complete(){const e=await async function __PRIVATE_localStoreApplyBundledDocuments(e,i,s,o){const _=__PRIVATE_debugCast(e);let h=__PRIVATE_documentKeySet(),d=__PRIVATE_mutableDocumentMap();for(const e of s){const s=i.Es(e.metadata.name);e.document&&(h=h.add(s));const o=i.ds(e);o.setReadTime(i.As(e.metadata.readTime)),d=d.insert(s,o)}const f=_.cs.newChangeBuffer({trackRemovals:!0}),g=await __PRIVATE_localStoreAllocateTarget(_,function __PRIVATE_umbrellaTarget(e){return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`)))}(o));return _.persistence.runTransaction("Apply bundle documents","readwrite",(e=>__PRIVATE_populateDocumentChangeBuffer(e,f,d).next((i=>(f.apply(e),i))).next((i=>_.Ur.removeMatchingKeysForTargetId(e,g.targetId).next((()=>_.Ur.addMatchingKeys(e,h,g.targetId))).next((()=>_.localDocuments.getLocalViewOfDocuments(e,i.Ps,i.Is))).next((()=>i.Ps))))))}(this.localStore,new __PRIVATE_BundleConverterImpl(this.serializer),this.documents,this.ca.id),i=this.ha(this.documents);for(const e of this.queries)await __PRIVATE_localStoreSaveNamedQuery(this.localStore,e,i.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Pa:this.collectionGroups,Ia:e}}}function __PRIVATE_bundleInitialProgress(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class __PRIVATE_AddedLimboDocument{constructor(e){this.key=e}}class __PRIVATE_RemovedLimboDocument{constructor(e){this.key=e}}class __PRIVATE_View{constructor(e,i){this.query=e,this.Ta=i,this.Ea=null,this.hasCachedResults=!1,this.current=!1,this.da=__PRIVATE_documentKeySet(),this.mutatedKeys=__PRIVATE_documentKeySet(),this.Aa=__PRIVATE_newQueryComparator(e),this.Ra=new DocumentSet(this.Aa)}get Va(){return this.Ta}ma(e,i){const s=i?i.fa:new __PRIVATE_DocumentChangeSet,o=i?i.Ra:this.Ra;let _=i?i.mutatedKeys:this.mutatedKeys,h=o,d=!1;const f="F"===this.query.limitType&&o.size===this.query.limit?o.last():null,g="L"===this.query.limitType&&o.size===this.query.limit?o.first():null;if(e.inorderTraversal(((e,i)=>{const b=o.get(e),w=__PRIVATE_queryMatches(this.query,i)?i:null,O=!!b&&this.mutatedKeys.has(b.key),q=!!w&&(w.hasLocalMutations||this.mutatedKeys.has(w.key)&&w.hasCommittedMutations);let j=!1;b&&w?b.data.isEqual(w.data)?O!==q&&(s.track({type:3,doc:w}),j=!0):this.ga(b,w)||(s.track({type:2,doc:w}),j=!0,(f&&this.Aa(w,f)>0||g&&this.Aa(w,g)<0)&&(d=!0)):!b&&w?(s.track({type:0,doc:w}),j=!0):b&&!w&&(s.track({type:1,doc:b}),j=!0,(f||g)&&(d=!0)),j&&(w?(h=h.add(w),_=q?_.add(e):_.delete(e)):(h=h.delete(e),_=_.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),_=_.delete(e.key),s.track({type:1,doc:e})}return{Ra:h,fa:s,ns:d,mutatedKeys:_}}ga(e,i){return e.hasLocalMutations&&i.hasCommittedMutations&&!i.hasLocalMutations}applyChanges(e,i,s,o){const _=this.Ra;this.Ra=e.Ra,this.mutatedKeys=e.mutatedKeys;const h=e.fa.G_();h.sort(((e,i)=>function __PRIVATE_compareChangeType(e,i){const order=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return fail()}};return order(e)-order(i)}(e.type,i.type)||this.Aa(e.doc,i.doc))),this.pa(s),o=null!=o&&o;const d=i&&!o?this.ya():[],f=0===this.da.size&&this.current&&!o?1:0,g=f!==this.Ea;return this.Ea=f,0!==h.length||g?{snapshot:new ViewSnapshot(this.query,e.Ra,_,h,e.mutatedKeys,0===f,g,!1,!!s&&s.resumeToken.approximateByteSize()>0),wa:d}:{wa:d}}Z_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ra:this.Ra,fa:new __PRIVATE_DocumentChangeSet,mutatedKeys:this.mutatedKeys,ns:!1},!1)):{wa:[]}}Sa(e){return!this.Ta.has(e)&&!!this.Ra.has(e)&&!this.Ra.get(e).hasLocalMutations}pa(e){e&&(e.addedDocuments.forEach((e=>this.Ta=this.Ta.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.Ta=this.Ta.delete(e))),this.current=e.current)}ya(){if(!this.current)return[];const e=this.da;this.da=__PRIVATE_documentKeySet(),this.Ra.forEach((e=>{this.Sa(e.key)&&(this.da=this.da.add(e.key))}));const i=[];return e.forEach((e=>{this.da.has(e)||i.push(new __PRIVATE_RemovedLimboDocument(e))})),this.da.forEach((s=>{e.has(s)||i.push(new __PRIVATE_AddedLimboDocument(s))})),i}ba(e){this.Ta=e.Ts,this.da=__PRIVATE_documentKeySet();const i=this.ma(e.documents);return this.applyChanges(i,!0)}Da(){return ViewSnapshot.fromInitialDocuments(this.query,this.Ra,this.mutatedKeys,0===this.Ea,this.hasCachedResults)}}class __PRIVATE_QueryView{constructor(e,i,s){this.query=e,this.targetId=i,this.view=s}}class LimboResolution{constructor(e){this.key=e,this.va=!1}}class __PRIVATE_SyncEngineImpl{constructor(e,i,s,o,_,h){this.localStore=e,this.remoteStore=i,this.eventManager=s,this.sharedClientState=o,this.currentUser=_,this.maxConcurrentLimboResolutions=h,this.Ca={},this.Fa=new ObjectMap((e=>__PRIVATE_canonifyQuery(e)),__PRIVATE_queryEquals),this.Ma=new Map,this.xa=new Set,this.Oa=new SortedMap(DocumentKey.comparator),this.Na=new Map,this.La=new __PRIVATE_ReferenceSet,this.Ba={},this.ka=new Map,this.qa=__PRIVATE_TargetIdGenerator.kn(),this.onlineState="Unknown",this.Qa=void 0}get isPrimaryClient(){return!0===this.Qa}}async function __PRIVATE_syncEngineListen(e,i,s=!0){const o=__PRIVATE_ensureWatchCallbacks(e);let _;const h=o.Fa.get(i);return h?(o.sharedClientState.addLocalQueryTarget(h.targetId),_=h.view.Da()):_=await __PRIVATE_allocateTargetAndMaybeListen(o,i,s,!0),_}async function __PRIVATE_triggerRemoteStoreListen(e,i){const s=__PRIVATE_ensureWatchCallbacks(e);await __PRIVATE_allocateTargetAndMaybeListen(s,i,!0,!1)}async function __PRIVATE_allocateTargetAndMaybeListen(e,i,s,o){const _=await __PRIVATE_localStoreAllocateTarget(e.localStore,__PRIVATE_queryToTarget(i)),h=_.targetId,d=e.sharedClientState.addLocalQueryTarget(h,s);let f;return o&&(f=await __PRIVATE_initializeViewAndComputeSnapshot(e,i,h,"current"===d,_.resumeToken)),e.isPrimaryClient&&s&&__PRIVATE_remoteStoreListen(e.remoteStore,_),f}async function __PRIVATE_initializeViewAndComputeSnapshot(e,i,s,o,_){e.Ka=(i,s,o)=>async function __PRIVATE_applyDocChanges(e,i,s,o){let _=i.view.ma(s);_.ns&&(_=await __PRIVATE_localStoreExecuteQuery(e.localStore,i.query,!1).then((({documents:e})=>i.view.ma(e,_))));const h=o&&o.targetChanges.get(i.targetId),d=o&&null!=o.targetMismatches.get(i.targetId),f=i.view.applyChanges(_,e.isPrimaryClient,h,d);return __PRIVATE_updateTrackedLimbos(e,i.targetId,f.wa),f.snapshot}(e,i,s,o);const h=await __PRIVATE_localStoreExecuteQuery(e.localStore,i,!0),d=new __PRIVATE_View(i,h.Ts),f=d.ma(h.documents),g=TargetChange.createSynthesizedTargetChangeForCurrentChange(s,o&&"Offline"!==e.onlineState,_),b=d.applyChanges(f,e.isPrimaryClient,g);__PRIVATE_updateTrackedLimbos(e,s,b.wa);const w=new __PRIVATE_QueryView(i,s,d);return e.Fa.set(i,w),e.Ma.has(s)?e.Ma.get(s).push(i):e.Ma.set(s,[i]),b.snapshot}async function __PRIVATE_syncEngineUnlisten(e,i,s){const o=__PRIVATE_debugCast(e),_=o.Fa.get(i),h=o.Ma.get(_.targetId);if(h.length>1)return o.Ma.set(_.targetId,h.filter((e=>!__PRIVATE_queryEquals(e,i)))),void o.Fa.delete(i);o.isPrimaryClient?(o.sharedClientState.removeLocalQueryTarget(_.targetId),o.sharedClientState.isActiveQueryTarget(_.targetId)||await __PRIVATE_localStoreReleaseTarget(o.localStore,_.targetId,!1).then((()=>{o.sharedClientState.clearQueryState(_.targetId),s&&__PRIVATE_remoteStoreUnlisten(o.remoteStore,_.targetId),__PRIVATE_removeAndCleanupTarget(o,_.targetId)})).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)):(__PRIVATE_removeAndCleanupTarget(o,_.targetId),await __PRIVATE_localStoreReleaseTarget(o.localStore,_.targetId,!0))}async function __PRIVATE_triggerRemoteStoreUnlisten(e,i){const s=__PRIVATE_debugCast(e),o=s.Fa.get(i),_=s.Ma.get(o.targetId);s.isPrimaryClient&&1===_.length&&(s.sharedClientState.removeLocalQueryTarget(o.targetId),__PRIVATE_remoteStoreUnlisten(s.remoteStore,o.targetId))}async function __PRIVATE_syncEngineApplyRemoteEvent(e,i){const s=__PRIVATE_debugCast(e);try{const e=await function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e,i){const s=__PRIVATE_debugCast(e),o=i.snapshotVersion;let _=s.os;return s.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const h=s.cs.newChangeBuffer({trackRemovals:!0});_=s.os;const d=[];i.targetChanges.forEach(((h,f)=>{const g=_.get(f);if(!g)return;d.push(s.Ur.removeMatchingKeys(e,h.removedDocuments,f).next((()=>s.Ur.addMatchingKeys(e,h.addedDocuments,f))));let b=g.withSequenceNumber(e.currentSequenceNumber);null!==i.targetMismatches.get(f)?b=b.withResumeToken(ByteString.EMPTY_BYTE_STRING,SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()):h.resumeToken.approximateByteSize()>0&&(b=b.withResumeToken(h.resumeToken,o)),_=_.insert(f,b),function __PRIVATE_shouldPersistTargetData(e,i,s){return 0===e.resumeToken.approximateByteSize()||i.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0}(g,b,h)&&d.push(s.Ur.updateTargetData(e,b))}));let f=__PRIVATE_mutableDocumentMap(),g=__PRIVATE_documentKeySet();if(i.documentUpdates.forEach((o=>{i.resolvedLimboDocuments.has(o)&&d.push(s.persistence.referenceDelegate.updateLimboDocument(e,o))})),d.push(__PRIVATE_populateDocumentChangeBuffer(e,h,i.documentUpdates).next((e=>{f=e.Ps,g=e.Is}))),!o.isEqual(SnapshotVersion.min())){const i=s.Ur.getLastRemoteSnapshotVersion(e).next((i=>s.Ur.setTargetsMetadata(e,e.currentSequenceNumber,o)));d.push(i)}return PersistencePromise.waitFor(d).next((()=>h.apply(e))).next((()=>s.localDocuments.getLocalViewOfDocuments(e,f,g))).next((()=>f))})).then((e=>(s.os=_,e)))}(s.localStore,i);i.targetChanges.forEach(((e,i)=>{const o=s.Na.get(i);o&&(__PRIVATE_hardAssert(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?o.va=!0:e.modifiedDocuments.size>0?__PRIVATE_hardAssert(o.va):e.removedDocuments.size>0&&(__PRIVATE_hardAssert(o.va),o.va=!1))})),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e,i)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}function __PRIVATE_syncEngineApplyOnlineStateChange(e,i,s){const o=__PRIVATE_debugCast(e);if(o.isPrimaryClient&&0===s||!o.isPrimaryClient&&1===s){const e=[];o.Fa.forEach(((s,o)=>{const _=o.view.Z_(i);_.snapshot&&e.push(_.snapshot)})),function __PRIVATE_eventManagerOnOnlineStateChange(e,i){const s=__PRIVATE_debugCast(e);s.onlineState=i;let o=!1;s.queries.forEach(((e,s)=>{for(const e of s.j_)e.Z_(i)&&(o=!0)})),o&&__PRIVATE_raiseSnapshotsInSyncEvent(s)}(o.eventManager,i),e.length&&o.Ca.d_(e),o.onlineState=i,o.isPrimaryClient&&o.sharedClientState.setOnlineState(i)}}async function __PRIVATE_syncEngineRejectListen(e,i,s){const o=__PRIVATE_debugCast(e);o.sharedClientState.updateQueryState(i,"rejected",s);const _=o.Na.get(i),h=_&&_.key;if(h){let e=new SortedMap(DocumentKey.comparator);e=e.insert(h,MutableDocument.newNoDocument(h,SnapshotVersion.min()));const s=__PRIVATE_documentKeySet().add(h),_=new RemoteEvent(SnapshotVersion.min(),new Map,new SortedMap(__PRIVATE_primitiveComparator),e,s);await __PRIVATE_syncEngineApplyRemoteEvent(o,_),o.Oa=o.Oa.remove(h),o.Na.delete(i),__PRIVATE_pumpEnqueuedLimboResolutions(o)}else await __PRIVATE_localStoreReleaseTarget(o.localStore,i,!1).then((()=>__PRIVATE_removeAndCleanupTarget(o,i,s))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)}async function __PRIVATE_syncEngineApplySuccessfulWrite(e,i){const s=__PRIVATE_debugCast(e),o=i.batch.batchId;try{const e=await function __PRIVATE_localStoreAcknowledgeBatch(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const o=i.batch.keys(),_=s.cs.newChangeBuffer({trackRemovals:!0});return function __PRIVATE_applyWriteToRemoteDocuments(e,i,s,o){const _=s.batch,h=_.keys();let d=PersistencePromise.resolve();return h.forEach((e=>{d=d.next((()=>o.getEntry(i,e))).next((i=>{const h=s.docVersions.get(e);__PRIVATE_hardAssert(null!==h),i.version.compareTo(h)<0&&(_.applyToRemoteDocument(i,s),i.isValidDocument()&&(i.setReadTime(s.commitVersion),o.addEntry(i)))}))})),d.next((()=>e.mutationQueue.removeMutationBatch(i,_)))}(s,e,i,_).next((()=>_.apply(e))).next((()=>s.mutationQueue.performConsistencyCheck(e))).next((()=>s.documentOverlayCache.removeOverlaysForBatchId(e,o,i.batch.batchId))).next((()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function __PRIVATE_getKeysWithTransformResults(e){let i=__PRIVATE_documentKeySet();for(let s=0;s<e.mutationResults.length;++s)e.mutationResults[s].transformResults.length>0&&(i=i.add(e.batch.mutations[s].key));return i}(i)))).next((()=>s.localDocuments.getDocuments(e,o)))}))}(s.localStore,i);__PRIVATE_processUserCallback(s,o,null),__PRIVATE_triggerPendingWritesCallbacks(s,o),s.sharedClientState.updateMutationState(o,"acknowledged"),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}async function __PRIVATE_syncEngineRejectFailedWrite(e,i,s){const o=__PRIVATE_debugCast(e);try{const e=await function __PRIVATE_localStoreRejectBatch(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let o;return s.mutationQueue.lookupMutationBatch(e,i).next((i=>(__PRIVATE_hardAssert(null!==i),o=i.keys(),s.mutationQueue.removeMutationBatch(e,i)))).next((()=>s.mutationQueue.performConsistencyCheck(e))).next((()=>s.documentOverlayCache.removeOverlaysForBatchId(e,o,i))).next((()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,o))).next((()=>s.localDocuments.getDocuments(e,o)))}))}(o.localStore,i);__PRIVATE_processUserCallback(o,i,s),__PRIVATE_triggerPendingWritesCallbacks(o,i),o.sharedClientState.updateMutationState(i,"rejected",s),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(o,e)}catch(s){await __PRIVATE_ignoreIfPrimaryLeaseLoss(s)}}function __PRIVATE_triggerPendingWritesCallbacks(e,i){(e.ka.get(i)||[]).forEach((e=>{e.resolve()})),e.ka.delete(i)}function __PRIVATE_processUserCallback(e,i,s){const o=__PRIVATE_debugCast(e);let _=o.Ba[o.currentUser.toKey()];if(_){const e=_.get(i);e&&(s?e.reject(s):e.resolve(),_=_.remove(i)),o.Ba[o.currentUser.toKey()]=_}}function __PRIVATE_removeAndCleanupTarget(e,i,s=null){e.sharedClientState.removeLocalQueryTarget(i);for(const o of e.Ma.get(i))e.Fa.delete(o),s&&e.Ca.$a(o,s);e.Ma.delete(i),e.isPrimaryClient&&e.La.gr(i).forEach((i=>{e.La.containsKey(i)||__PRIVATE_removeLimboTarget(e,i)}))}function __PRIVATE_removeLimboTarget(e,i){e.xa.delete(i.path.canonicalString());const s=e.Oa.get(i);null!==s&&(__PRIVATE_remoteStoreUnlisten(e.remoteStore,s),e.Oa=e.Oa.remove(i),e.Na.delete(s),__PRIVATE_pumpEnqueuedLimboResolutions(e))}function __PRIVATE_updateTrackedLimbos(e,i,s){for(const o of s)o instanceof __PRIVATE_AddedLimboDocument?(e.La.addReference(o.key,i),__PRIVATE_trackLimboChange(e,o)):o instanceof __PRIVATE_RemovedLimboDocument?(__PRIVATE_logDebug("SyncEngine","Document no longer in limbo: "+o.key),e.La.removeReference(o.key,i),e.La.containsKey(o.key)||__PRIVATE_removeLimboTarget(e,o.key)):fail()}function __PRIVATE_trackLimboChange(e,i){const s=i.key,o=s.path.canonicalString();e.Oa.get(s)||e.xa.has(o)||(__PRIVATE_logDebug("SyncEngine","New document in limbo: "+s),e.xa.add(o),__PRIVATE_pumpEnqueuedLimboResolutions(e))}function __PRIVATE_pumpEnqueuedLimboResolutions(e){for(;e.xa.size>0&&e.Oa.size<e.maxConcurrentLimboResolutions;){const i=e.xa.values().next().value;e.xa.delete(i);const s=new DocumentKey(ResourcePath.fromString(i)),o=e.qa.next();e.Na.set(o,new LimboResolution(s)),e.Oa=e.Oa.insert(s,o),__PRIVATE_remoteStoreListen(e.remoteStore,new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(s.path)),o,"TargetPurposeLimboResolution",__PRIVATE_ListenSequence.oe))}}async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,i,s){const o=__PRIVATE_debugCast(e),_=[],h=[],d=[];o.Fa.isEmpty()||(o.Fa.forEach(((e,f)=>{d.push(o.Ka(f,i,s).then((e=>{var i;if((e||s)&&o.isPrimaryClient){const _=e?!e.fromCache:null===(i=null==s?void 0:s.targetChanges.get(f.targetId))||void 0===i?void 0:i.current;o.sharedClientState.updateQueryState(f.targetId,_?"current":"not-current")}if(e){_.push(e);const i=__PRIVATE_LocalViewChanges.Wi(f.targetId,e);h.push(i)}})))})),await Promise.all(d),o.Ca.d_(_),await async function __PRIVATE_localStoreNotifyLocalViewChanges(e,i){const s=__PRIVATE_debugCast(e);try{await s.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>PersistencePromise.forEach(i,(i=>PersistencePromise.forEach(i.$i,(o=>s.persistence.referenceDelegate.addReference(e,i.targetId,o))).next((()=>PersistencePromise.forEach(i.Ui,(o=>s.persistence.referenceDelegate.removeReference(e,i.targetId,o)))))))))}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug("LocalStore","Failed to update sequence numbers: "+e)}for(const e of i){const i=e.targetId;if(!e.fromCache){const e=s.os.get(i),o=e.snapshotVersion,_=e.withLastLimboFreeSnapshotVersion(o);s.os=s.os.insert(i,_)}}}(o.localStore,h))}async function __PRIVATE_syncEngineHandleCredentialChange(e,i){const s=__PRIVATE_debugCast(e);if(!s.currentUser.isEqual(i)){__PRIVATE_logDebug("SyncEngine","User change. New user:",i.toKey());const e=await __PRIVATE_localStoreHandleUserChange(s.localStore,i);s.currentUser=i,function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e,i){e.ka.forEach((e=>{e.forEach((e=>{e.reject(new FirestoreError(_e.CANCELLED,i))}))})),e.ka.clear()}(s,"'waitForPendingWrites' promise is rejected due to a user change."),s.sharedClientState.handleUserChange(i,e.removedBatchIds,e.addedBatchIds),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e.hs)}}function __PRIVATE_syncEngineGetRemoteKeysForTarget(e,i){const s=__PRIVATE_debugCast(e),o=s.Na.get(i);if(o&&o.va)return __PRIVATE_documentKeySet().add(o.key);{let e=__PRIVATE_documentKeySet();const o=s.Ma.get(i);if(!o)return e;for(const i of o){const o=s.Fa.get(i);e=e.unionWith(o.view.Va)}return e}}async function __PRIVATE_synchronizeViewAndComputeSnapshot(e,i){const s=__PRIVATE_debugCast(e),o=await __PRIVATE_localStoreExecuteQuery(s.localStore,i.query,!0),_=i.view.ba(o);return s.isPrimaryClient&&__PRIVATE_updateTrackedLimbos(s,i.targetId,_.wa),_}async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e,i){const s=__PRIVATE_debugCast(e);return __PRIVATE_localStoreGetNewDocumentChanges(s.localStore,i).then((e=>__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e)))}async function __PRIVATE_syncEngineApplyBatchState(e,i,s,o){const _=__PRIVATE_debugCast(e),h=await function __PRIVATE_localStoreLookupMutationDocuments(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_debugCast(s.mutationQueue);return s.persistence.runTransaction("Lookup mutation documents","readonly",(e=>o.Mn(e,i).next((i=>i?s.localDocuments.getDocuments(e,i):PersistencePromise.resolve(null)))))}(_.localStore,i);null!==h?("pending"===s?await __PRIVATE_fillWritePipeline(_.remoteStore):"acknowledged"===s||"rejected"===s?(__PRIVATE_processUserCallback(_,i,o||null),__PRIVATE_triggerPendingWritesCallbacks(_,i),function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e,i){__PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).On(i)}(_.localStore,i)):fail(),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(_,h)):__PRIVATE_logDebug("SyncEngine","Cannot apply mutation batch with id: "+i)}async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e,i,s){const o=__PRIVATE_debugCast(e),_=[],h=[];for(const e of i){let i;const s=o.Ma.get(e);if(s&&0!==s.length){i=await __PRIVATE_localStoreAllocateTarget(o.localStore,__PRIVATE_queryToTarget(s[0]));for(const e of s){const i=o.Fa.get(e),s=await __PRIVATE_synchronizeViewAndComputeSnapshot(o,i);s.snapshot&&h.push(s.snapshot)}}else{const s=await __PRIVATE_localStoreGetCachedTarget(o.localStore,e);i=await __PRIVATE_localStoreAllocateTarget(o.localStore,s),await __PRIVATE_initializeViewAndComputeSnapshot(o,__PRIVATE_synthesizeTargetToQuery(s),e,!1,i.resumeToken)}_.push(i)}return o.Ca.d_(h),_}function __PRIVATE_synthesizeTargetToQuery(e){return __PRIVATE_newQuery(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function __PRIVATE_syncEngineGetActiveClients(e){return function __PRIVATE_localStoreGetActiveClients(e){return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Qi()}(__PRIVATE_debugCast(e).localStore)}async function __PRIVATE_syncEngineApplyTargetState(e,i,s,o){const _=__PRIVATE_debugCast(e);if(_.Qa)return void __PRIVATE_logDebug("SyncEngine","Ignoring unexpected query state notification.");const h=_.Ma.get(i);if(h&&h.length>0)switch(s){case"current":case"not-current":{const e=await __PRIVATE_localStoreGetNewDocumentChanges(_.localStore,__PRIVATE_queryCollectionGroup(h[0])),o=RemoteEvent.createSynthesizedRemoteEventForCurrentChange(i,"current"===s,ByteString.EMPTY_BYTE_STRING);await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(_,e,o);break}case"rejected":await __PRIVATE_localStoreReleaseTarget(_.localStore,i,!0),__PRIVATE_removeAndCleanupTarget(_,i,o);break;default:fail()}}async function __PRIVATE_syncEngineApplyActiveTargetsChange(e,i,s){const o=__PRIVATE_ensureWatchCallbacks(e);if(o.Qa){for(const e of i){if(o.Ma.has(e)&&o.sharedClientState.isActiveQueryTarget(e)){__PRIVATE_logDebug("SyncEngine","Adding an already active target "+e);continue}const i=await __PRIVATE_localStoreGetCachedTarget(o.localStore,e),s=await __PRIVATE_localStoreAllocateTarget(o.localStore,i);await __PRIVATE_initializeViewAndComputeSnapshot(o,__PRIVATE_synthesizeTargetToQuery(i),s.targetId,!1,s.resumeToken),__PRIVATE_remoteStoreListen(o.remoteStore,s)}for(const e of s)o.Ma.has(e)&&await __PRIVATE_localStoreReleaseTarget(o.localStore,e,!1).then((()=>{__PRIVATE_remoteStoreUnlisten(o.remoteStore,e),__PRIVATE_removeAndCleanupTarget(o,e)})).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)}}function __PRIVATE_ensureWatchCallbacks(e){const i=__PRIVATE_debugCast(e);return i.remoteStore.remoteSyncer.applyRemoteEvent=__PRIVATE_syncEngineApplyRemoteEvent.bind(null,i),i.remoteStore.remoteSyncer.getRemoteKeysForTarget=__PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null,i),i.remoteStore.remoteSyncer.rejectListen=__PRIVATE_syncEngineRejectListen.bind(null,i),i.Ca.d_=__PRIVATE_eventManagerOnWatchChange.bind(null,i.eventManager),i.Ca.$a=__PRIVATE_eventManagerOnWatchError.bind(null,i.eventManager),i}function __PRIVATE_syncEngineEnsureWriteCallbacks(e){const i=__PRIVATE_debugCast(e);return i.remoteStore.remoteSyncer.applySuccessfulWrite=__PRIVATE_syncEngineApplySuccessfulWrite.bind(null,i),i.remoteStore.remoteSyncer.rejectFailedWrite=__PRIVATE_syncEngineRejectFailedWrite.bind(null,i),i}class __PRIVATE_MemoryOfflineComponentProvider{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=__PRIVATE_newSerializer(e.databaseInfo.databaseId),this.sharedClientState=this.Wa(e),this.persistence=this.Ga(e),await this.persistence.start(),this.localStore=this.za(e),this.gcScheduler=this.ja(e,this.localStore),this.indexBackfillerScheduler=this.Ha(e,this.localStore)}ja(e,i){return null}Ha(e,i){return null}za(e){return __PRIVATE_newLocalStore(this.persistence,new __PRIVATE_QueryEngine,e.initialUser,this.serializer)}Ga(e){return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Zr,this.serializer)}Wa(e){return new __PRIVATE_MemorySharedClientState}async terminate(){var e,i;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(i=this.indexBackfillerScheduler)||void 0===i||i.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}__PRIVATE_MemoryOfflineComponentProvider.provider={build:()=>new __PRIVATE_MemoryOfflineComponentProvider};class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider{constructor(e){super(),this.cacheSizeBytes=e}ja(e,i){__PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate);const s=this.persistence.referenceDelegate.garbageCollector;return new __PRIVATE_LruScheduler(s,e.asyncQueue,i)}Ga(e){const i=void 0!==this.cacheSizeBytes?LruParams.withCacheSize(this.cacheSizeBytes):LruParams.DEFAULT;return new __PRIVATE_MemoryPersistence((e=>__PRIVATE_MemoryLruDelegate.Zr(e,i)),this.serializer)}}class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider{constructor(e,i,s){super(),this.Ja=e,this.cacheSizeBytes=i,this.forceOwnership=s,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ja.initialize(this,e),await __PRIVATE_syncEngineEnsureWriteCallbacks(this.Ja.syncEngine),await __PRIVATE_fillWritePipeline(this.Ja.remoteStore),await this.persistence.yi((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}za(e){return __PRIVATE_newLocalStore(this.persistence,new __PRIVATE_QueryEngine,e.initialUser,this.serializer)}ja(e,i){const s=this.persistence.referenceDelegate.garbageCollector;return new __PRIVATE_LruScheduler(s,e.asyncQueue,i)}Ha(e,i){const s=new __PRIVATE_IndexBackfiller(i,this.persistence);return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue,s)}Ga(e){const i=__PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),s=void 0!==this.cacheSizeBytes?LruParams.withCacheSize(this.cacheSizeBytes):LruParams.DEFAULT;return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs,i,e.clientId,s,e.asyncQueue,__PRIVATE_getWindow(),getDocument(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Wa(e){return new __PRIVATE_MemorySharedClientState}}class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider{constructor(e,i){super(e,i,!1),this.Ja=e,this.cacheSizeBytes=i,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const i=this.Ja.syncEngine;this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState&&(this.sharedClientState.syncEngine={no:__PRIVATE_syncEngineApplyBatchState.bind(null,i),ro:__PRIVATE_syncEngineApplyTargetState.bind(null,i),io:__PRIVATE_syncEngineApplyActiveTargetsChange.bind(null,i),Qi:__PRIVATE_syncEngineGetActiveClients.bind(null,i),eo:__PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null,i)},await this.sharedClientState.start()),await this.persistence.yi((async e=>{await async function __PRIVATE_syncEngineApplyPrimaryState(e,i){const s=__PRIVATE_debugCast(e);if(__PRIVATE_ensureWatchCallbacks(s),__PRIVATE_syncEngineEnsureWriteCallbacks(s),!0===i&&!0!==s.Qa){const e=s.sharedClientState.getAllActiveQueryTargets(),i=await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(s,e.toArray());s.Qa=!0,await __PRIVATE_remoteStoreApplyPrimaryState(s.remoteStore,!0);for(const e of i)__PRIVATE_remoteStoreListen(s.remoteStore,e)}else if(!1===i&&!1!==s.Qa){const e=[];let i=Promise.resolve();s.Ma.forEach(((o,_)=>{s.sharedClientState.isLocalQueryTarget(_)?e.push(_):i=i.then((()=>(__PRIVATE_removeAndCleanupTarget(s,_),__PRIVATE_localStoreReleaseTarget(s.localStore,_,!0)))),__PRIVATE_remoteStoreUnlisten(s.remoteStore,_)})),await i,await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(s,e),function __PRIVATE_resetLimboDocuments(e){const i=__PRIVATE_debugCast(e);i.Na.forEach(((e,s)=>{__PRIVATE_remoteStoreUnlisten(i.remoteStore,s)})),i.La.pr(),i.Na=new Map,i.Oa=new SortedMap(DocumentKey.comparator)}(s),s.Qa=!1,await __PRIVATE_remoteStoreApplyPrimaryState(s.remoteStore,!1)}}(this.Ja.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())}))}Wa(e){const i=__PRIVATE_getWindow();if(!__PRIVATE_WebStorageSharedClientState.D(i))throw new FirestoreError(_e.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const s=__PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new __PRIVATE_WebStorageSharedClientState(i,e.asyncQueue,s,e.clientId,e.initialUser)}}class OnlineComponentProvider{async initialize(e,i){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(i),this.remoteStore=this.createRemoteStore(i),this.eventManager=this.createEventManager(i),this.syncEngine=this.createSyncEngine(i,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>__PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=__PRIVATE_syncEngineHandleCredentialChange.bind(null,this.syncEngine),await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function __PRIVATE_newEventManager(){return new __PRIVATE_EventManagerImpl}()}createDatastore(e){const i=__PRIVATE_newSerializer(e.databaseInfo.databaseId),s=function __PRIVATE_newConnection(e){return new __PRIVATE_WebChannelConnection(e)}(e.databaseInfo);return function __PRIVATE_newDatastore(e,i,s,o){return new __PRIVATE_DatastoreImpl(e,i,s,o)}(e.authCredentials,e.appCheckCredentials,s,i)}createRemoteStore(e){return function __PRIVATE_newRemoteStore(e,i,s,o,_){return new __PRIVATE_RemoteStoreImpl(e,i,s,o,_)}(this.localStore,this.datastore,e.asyncQueue,(e=>__PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine,e,0)),function __PRIVATE_newConnectivityMonitor(){return __PRIVATE_BrowserConnectivityMonitor.D()?new __PRIVATE_BrowserConnectivityMonitor:new __PRIVATE_NoopConnectivityMonitor}())}createSyncEngine(e,i){return function __PRIVATE_newSyncEngine(e,i,s,o,_,h,d){const f=new __PRIVATE_SyncEngineImpl(e,i,s,o,_,h);return d&&(f.Qa=!0),f}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,i)}async terminate(){var e,i;await async function __PRIVATE_remoteStoreShutdown(e){const i=__PRIVATE_debugCast(e);__PRIVATE_logDebug("RemoteStore","RemoteStore shutting down."),i.L_.add(5),await __PRIVATE_disableNetworkInternal(i),i.k_.shutdown(),i.q_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(i=this.eventManager)||void 0===i||i.terminate()}}function __PRIVATE_toByteStreamReaderHelper(e,i=10240){let s=0;return{async read(){if(s<e.byteLength){const o={value:e.slice(s,s+i),done:!1};return s+=i,o}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}OnlineComponentProvider.provider={build:()=>new OnlineComponentProvider};class __PRIVATE_AsyncObserver{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ya(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ya(this.observer.error,e):__PRIVATE_logError("Uncaught Error in snapshot listener:",e.toString()))}Za(){this.muted=!0}Ya(e,i){setTimeout((()=>{this.muted||e(i)}),0)}}class __PRIVATE_BundleReaderImpl{constructor(e,i){this.Xa=e,this.serializer=i,this.metadata=new __PRIVATE_Deferred,this.buffer=new Uint8Array,this.eu=function __PRIVATE_newTextDecoder(){return new TextDecoder("utf-8")}(),this.tu().then((e=>{e&&e.ua()?this.metadata.resolve(e.aa.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.aa)}`))}),(e=>this.metadata.reject(e)))}close(){return this.Xa.cancel()}async getMetadata(){return this.metadata.promise}async Ua(){return await this.getMetadata(),this.tu()}async tu(){const e=await this.nu();if(null===e)return null;const i=this.eu.decode(e),s=Number(i);isNaN(s)&&this.ru(`length string (${i}) is not valid number`);const o=await this.iu(s);return new __PRIVATE_SizedBundleElement(JSON.parse(o),e.length+s)}su(){return this.buffer.findIndex((e=>e==="{".charCodeAt(0)))}async nu(){for(;this.su()<0&&!await this.ou(););if(0===this.buffer.length)return null;const e=this.su();e<0&&this.ru("Reached the end of bundle when a length string is expected.");const i=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),i}async iu(e){for(;this.buffer.length<e;)await this.ou()&&this.ru("Reached the end of bundle when more is expected.");const i=this.eu.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),i}ru(e){throw this.Xa.cancel(),new Error(`Invalid bundle format: ${e}`)}async ou(){const e=await this.Xa.read();if(!e.done){const i=new Uint8Array(this.buffer.length+e.value.length);i.set(this.buffer),i.set(e.value,this.buffer.length),this.buffer=i}return e.done}}class Transaction$2{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(),this.mutations.length>0)throw this.lastTransactionError=new FirestoreError(_e.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const i=await async function __PRIVATE_invokeBatchGetDocumentsRpc(e,i){const s=__PRIVATE_debugCast(e),o={documents:i.map((e=>__PRIVATE_toName(s.serializer,e)))},_=await s.Lo("BatchGetDocuments",s.serializer.databaseId,ResourcePath.emptyPath(),o,i.length),h=new Map;_.forEach((e=>{const i=function __PRIVATE_fromBatchGetDocumentsResponse(e,i){return"found"in i?function __PRIVATE_fromFound(e,i){__PRIVATE_hardAssert(!!i.found),i.found.name,i.found.updateTime;const s=fromName(e,i.found.name),o=__PRIVATE_fromVersion(i.found.updateTime),_=i.found.createTime?__PRIVATE_fromVersion(i.found.createTime):SnapshotVersion.min(),h=new ObjectValue({mapValue:{fields:i.found.fields}});return MutableDocument.newFoundDocument(s,o,_,h)}(e,i):"missing"in i?function __PRIVATE_fromMissing(e,i){__PRIVATE_hardAssert(!!i.missing),__PRIVATE_hardAssert(!!i.readTime);const s=fromName(e,i.missing),o=__PRIVATE_fromVersion(i.readTime);return MutableDocument.newNoDocument(s,o)}(e,i):fail()}(s.serializer,e);h.set(i.key.toString(),i)}));const d=[];return i.forEach((e=>{const i=h.get(e.toString());__PRIVATE_hardAssert(!!i),d.push(i)})),d}(this.datastore,e);return i.forEach((e=>this.recordVersion(e))),i}set(e,i){this.write(i.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,i){try{this.write(i.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new __PRIVATE_DeleteMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const e=this.readVersions;this.mutations.forEach((i=>{e.delete(i.key.toString())})),e.forEach(((e,i)=>{const s=DocumentKey.fromPath(i);this.mutations.push(new __PRIVATE_VerifyMutation(s,this.precondition(s)))})),await async function __PRIVATE_invokeCommitRpc(e,i){const s=__PRIVATE_debugCast(e),o={writes:i.map((e=>toMutation(s.serializer,e)))};await s.Mo("Commit",s.serializer.databaseId,ResourcePath.emptyPath(),o)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let i;if(e.isFoundDocument())i=e.version;else{if(!e.isNoDocument())throw fail();i=SnapshotVersion.min()}const s=this.readVersions.get(e.key.toString());if(s){if(!i.isEqual(s))throw new FirestoreError(_e.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),i)}precondition(e){const i=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&i?i.isEqual(SnapshotVersion.min())?Precondition.exists(!1):Precondition.updateTime(i):Precondition.none()}preconditionForUpdate(e){const i=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&i){if(i.isEqual(SnapshotVersion.min()))throw new FirestoreError(_e.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Precondition.updateTime(i)}return Precondition.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class __PRIVATE_TransactionRunner{constructor(e,i,s,o,_){this.asyncQueue=e,this.datastore=i,this.options=s,this.updateFunction=o,this.deferred=_,this._u=s.maxAttempts,this.t_=new __PRIVATE_ExponentialBackoff(this.asyncQueue,"transaction_retry")}au(){this._u-=1,this.uu()}uu(){this.t_.Go((async()=>{const e=new Transaction$2(this.datastore),i=this.cu(e);i&&i.then((i=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(i)})).catch((e=>{this.lu(e)}))))})).catch((e=>{this.lu(e)}))}))}cu(e){try{const i=this.updateFunction(e);return!__PRIVATE_isNullOrUndefined(i)&&i.catch&&i.then?i:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}lu(e){this._u>0&&this.hu(e)?(this._u-=1,this.asyncQueue.enqueueAndForget((()=>(this.uu(),Promise.resolve())))):this.deferred.reject(e)}hu(e){if("FirebaseError"===e.name){const i=e.code;return"aborted"===i||"failed-precondition"===i||"already-exists"===i||!__PRIVATE_isPermanentError(i)}return!1}}class FirestoreClient{constructor(e,i,s,o,_){this.authCredentials=e,this.appCheckCredentials=i,this.asyncQueue=s,this.databaseInfo=o,this.user=User.UNAUTHENTICATED,this.clientId=__PRIVATE_AutoId.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=_,this.authCredentials.start(s,(async e=>{__PRIVATE_logDebug("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(s,(e=>(__PRIVATE_logDebug("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}terminate(){this.asyncQueue.enterRestrictedMode();const e=new __PRIVATE_Deferred;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(i){const s=__PRIVATE_wrapInUserErrorIfRecoverable(i,"Failed to shutdown persistence");e.reject(s)}})),e.promise}}async function __PRIVATE_setOfflineComponentProvider(e,i){e.asyncQueue.verifyOperationInProgress(),__PRIVATE_logDebug("FirestoreClient","Initializing OfflineComponentProvider");const s=e.configuration;await i.initialize(s);let o=s.initialUser;e.setCredentialChangeListener((async e=>{o.isEqual(e)||(await __PRIVATE_localStoreHandleUserChange(i.localStore,e),o=e)})),i.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=i}async function __PRIVATE_setOnlineComponentProvider(e,i){e.asyncQueue.verifyOperationInProgress();const s=await __PRIVATE_ensureOfflineComponents(e);__PRIVATE_logDebug("FirestoreClient","Initializing OnlineComponentProvider"),await i.initialize(s,e.configuration),e.setCredentialChangeListener((e=>__PRIVATE_remoteStoreHandleCredentialChange(i.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,s)=>__PRIVATE_remoteStoreHandleCredentialChange(i.remoteStore,s))),e._onlineComponents=i}async function __PRIVATE_ensureOfflineComponents(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){__PRIVATE_logDebug("FirestoreClient","Using user provided OfflineComponentProvider");try{await __PRIVATE_setOfflineComponentProvider(e,e._uninitializedComponentsProvider._offline)}catch(i){const s=i;if(!function __PRIVATE_canFallbackFromIndexedDbError(e){return"FirebaseError"===e.name?e.code===_e.FAILED_PRECONDITION||e.code===_e.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}(s))throw s;__PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: "+s),await __PRIVATE_setOfflineComponentProvider(e,new __PRIVATE_MemoryOfflineComponentProvider)}}else __PRIVATE_logDebug("FirestoreClient","Using default OfflineComponentProvider"),await __PRIVATE_setOfflineComponentProvider(e,new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0));return e._offlineComponents}async function __PRIVATE_ensureOnlineComponents(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(__PRIVATE_logDebug("FirestoreClient","Using user provided OnlineComponentProvider"),await __PRIVATE_setOnlineComponentProvider(e,e._uninitializedComponentsProvider._online)):(__PRIVATE_logDebug("FirestoreClient","Using default OnlineComponentProvider"),await __PRIVATE_setOnlineComponentProvider(e,new OnlineComponentProvider))),e._onlineComponents}function __PRIVATE_getPersistence(e){return __PRIVATE_ensureOfflineComponents(e).then((e=>e.persistence))}function __PRIVATE_getLocalStore(e){return __PRIVATE_ensureOfflineComponents(e).then((e=>e.localStore))}function __PRIVATE_getRemoteStore(e){return __PRIVATE_ensureOnlineComponents(e).then((e=>e.remoteStore))}function __PRIVATE_getSyncEngine(e){return __PRIVATE_ensureOnlineComponents(e).then((e=>e.syncEngine))}function __PRIVATE_getDatastore(e){return __PRIVATE_ensureOnlineComponents(e).then((e=>e.datastore))}async function __PRIVATE_getEventManager(e){const i=await __PRIVATE_ensureOnlineComponents(e),s=i.eventManager;return s.onListen=__PRIVATE_syncEngineListen.bind(null,i.syncEngine),s.onUnlisten=__PRIVATE_syncEngineUnlisten.bind(null,i.syncEngine),s.onFirstRemoteStoreListen=__PRIVATE_triggerRemoteStoreListen.bind(null,i.syncEngine),s.onLastRemoteStoreUnlisten=__PRIVATE_triggerRemoteStoreUnlisten.bind(null,i.syncEngine),s}function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e,i,s={}){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_readDocumentViaSnapshotListener(e,i,s,o,_){const h=new __PRIVATE_AsyncObserver({next:f=>{h.Za(),i.enqueueAndForget((()=>__PRIVATE_eventManagerUnlisten(e,d)));const g=f.docs.has(s);!g&&f.fromCache?_.reject(new FirestoreError(_e.UNAVAILABLE,"Failed to get document because the client is offline.")):g&&f.fromCache&&o&&"server"===o.source?_.reject(new FirestoreError(_e.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.)')):_.resolve(f)},error:e=>_.reject(e)}),d=new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(s.path),h,{includeMetadataChanges:!0,_a:!0});return __PRIVATE_eventManagerListen(e,d)}(await __PRIVATE_getEventManager(e),e.asyncQueue,i,s,o))),o.promise}function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e,i,s={}){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_executeQueryViaSnapshotListener(e,i,s,o,_){const h=new __PRIVATE_AsyncObserver({next:s=>{h.Za(),i.enqueueAndForget((()=>__PRIVATE_eventManagerUnlisten(e,d))),s.fromCache&&"server"===o.source?_.reject(new FirestoreError(_e.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.)')):_.resolve(s)},error:e=>_.reject(e)}),d=new __PRIVATE_QueryListener(s,h,{includeMetadataChanges:!0,_a:!0});return __PRIVATE_eventManagerListen(e,d)}(await __PRIVATE_getEventManager(e),e.asyncQueue,i,s,o))),o.promise}function __PRIVATE_firestoreClientLoadBundle(e,i,s,o){const _=function __PRIVATE_createBundleReader(e,i){let s;return s="string"==typeof e?__PRIVATE_newTextEncoder().encode(e):e,function __PRIVATE_newBundleReader(e,i){return new __PRIVATE_BundleReaderImpl(e,i)}(function __PRIVATE_toByteStreamReader(e,i){if(e instanceof Uint8Array)return __PRIVATE_toByteStreamReaderHelper(e,i);if(e instanceof ArrayBuffer)return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e),i);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),i)}(s,__PRIVATE_newSerializer(i));e.asyncQueue.enqueueAndForget((async()=>{!function __PRIVATE_syncEngineLoadBundle(e,i,s){const o=__PRIVATE_debugCast(e);(async function __PRIVATE_loadBundleImpl(e,i,s){try{const o=await i.getMetadata();if(await function __PRIVATE_localStoreHasNewerBundle(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_fromVersion(i.createTime);return s.persistence.runTransaction("hasNewerBundle","readonly",(e=>s.Gr.getBundleMetadata(e,i.id))).then((e=>!!e&&e.createTime.compareTo(o)>=0))}(e.localStore,o))return await i.close(),s._completeWith(function __PRIVATE_bundleSuccessProgress(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(o)),Promise.resolve(new Set);s._updateProgress(__PRIVATE_bundleInitialProgress(o));const _=new __PRIVATE_BundleLoader(o,e.localStore,i.serializer);let h=await i.Ua();for(;h;){const e=await _.la(h);e&&s._updateProgress(e),h=await i.Ua()}const d=await _.complete();return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,d.Ia,void 0),await function __PRIVATE_localStoreSaveBundle(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("Save bundle","readwrite",(e=>s.Gr.saveBundleMetadata(e,i)))}(e.localStore,o),s._completeWith(d.progress),Promise.resolve(d.Pa)}catch(e){return __PRIVATE_logWarn("SyncEngine",`Loading bundle failed with ${e}`),s._failWith(e),Promise.resolve(new Set)}})(o,i,s).then((e=>{o.sharedClientState.notifyBundleLoaded(e)}))}(await __PRIVATE_getSyncEngine(e),_,o)}))}function __PRIVATE_cloneLongPollingOptions(e){const i={};return void 0!==e.timeoutSeconds&&(i.timeoutSeconds=e.timeoutSeconds),i}const ut=new Map;function __PRIVATE_validateNonEmptyArgument(e,i,s){if(!s)throw new FirestoreError(_e.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${i}.`)}function __PRIVATE_validateIsNotUsedTogether(e,i,s,o){if(!0===i&&!0===o)throw new FirestoreError(_e.INVALID_ARGUMENT,`${e} and ${s} cannot be used together.`)}function __PRIVATE_validateDocumentPath(e){if(!DocumentKey.isDocumentKey(e))throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_validateCollectionPath(e){if(DocumentKey.isDocumentKey(e))throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_valueDescription(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const i=function __PRIVATE_tryGetCustomObjectType(e){return e.constructor?e.constructor.name:null}(e);return i?`a custom ${i} object`:"an object"}}return"function"==typeof e?"a function":fail()}function __PRIVATE_cast(e,i){if("_delegate"in e&&(e=e._delegate),!(e instanceof i)){if(i.name===e.constructor.name)throw new FirestoreError(_e.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const s=__PRIVATE_valueDescription(e);throw new FirestoreError(_e.INVALID_ARGUMENT,`Expected type '${i.name}', but it was: ${s}`)}}return e}function __PRIVATE_validatePositiveNumber(e,i){if(i<=0)throw new FirestoreError(_e.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${i}.`)}class FirestoreSettingsImpl{constructor(e){var i,s;if(void 0===e.host){if(void 0!==e.ssl)throw new FirestoreError(_e.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===(i=e.ssl)||void 0===i||i;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 FirestoreError(_e.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}__PRIVATE_validateIsNotUsedTogether("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=__PRIVATE_cloneLongPollingOptions(null!==(s=e.experimentalLongPollingOptions)&&void 0!==s?s:{}),function __PRIVATE_validateLongPollingOptions(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new FirestoreError(_e.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new FirestoreError(_e.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new FirestoreError(_e.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&&function __PRIVATE_longPollingOptionsEqual(e,i){return e.timeoutSeconds===i.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Firestore$1{constructor(e,i,s,o){this._authCredentials=e,this._appCheckCredentials=i,this._databaseId=s,this._app=o,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new FirestoreSettingsImpl({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new FirestoreError(_e.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"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new FirestoreError(_e.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 FirestoreSettingsImpl(e),void 0!==e.credentials&&(this._authCredentials=function __PRIVATE_makeAuthCredentialsProvider(e){if(!e)return new __PRIVATE_EmptyAuthCredentialsProvider;switch(e.type){case"firstParty":return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new FirestoreError(_e.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function __PRIVATE_removeComponents(e){const i=ut.get(e);i&&(__PRIVATE_logDebug("ComponentProvider","Removing Datastore"),ut.delete(e),i.terminate())}(this),Promise.resolve()}}function connectFirestoreEmulator(e,i,s,o={}){var _;const h=(e=__PRIVATE_cast(e,Firestore$1))._getSettings(),d=`${i}:${s}`;if("firestore.googleapis.com"!==h.host&&h.host!==d&&__PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},h),{host:d,ssl:!1})),o.mockUserToken){let i,s;if("string"==typeof o.mockUserToken)i=o.mockUserToken,s=User.MOCK_USER;else{i=function createMockUserToken(e,i){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const s=i||"demo-project",o=e.iat||0,_=e.sub||e.user_id;if(!_)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const h=Object.assign({iss:`https://securetoken.google.com/${s}`,aud:s,iat:o,exp:o+3600,auth_time:o,sub:_,user_id:_,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(h)),""].join(".")}(o.mockUserToken,null===(_=e._app)||void 0===_?void 0:_.options.projectId);const h=o.mockUserToken.sub||o.mockUserToken.user_id;if(!h)throw new FirestoreError(_e.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");s=new User(h)}e._authCredentials=new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(i,s))}}class Query{constructor(e,i,s){this.converter=i,this._query=s,this.type="query",this.firestore=e}withConverter(e){return new Query(this.firestore,e,this._query)}}class DocumentReference{constructor(e,i,s){this.converter=i,this._key=s,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 CollectionReference(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DocumentReference(this.firestore,e,this._key)}}class CollectionReference extends Query{constructor(e,i,s){super(e,i,__PRIVATE_newQueryForPath(s)),this._path=s,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 DocumentReference(this.firestore,null,new DocumentKey(e))}withConverter(e){return new CollectionReference(this.firestore,e,this._path)}}function collection(e,i,...s){if(e=getModularInstance(e),__PRIVATE_validateNonEmptyArgument("collection","path",i),e instanceof Firestore$1){const o=ResourcePath.fromString(i,...s);return __PRIVATE_validateCollectionPath(o),new CollectionReference(e,null,o)}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(_e.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const o=e._path.child(ResourcePath.fromString(i,...s));return __PRIVATE_validateCollectionPath(o),new CollectionReference(e.firestore,null,o)}}function collectionGroup(e,i){if(e=__PRIVATE_cast(e,Firestore$1),__PRIVATE_validateNonEmptyArgument("collectionGroup","collection id",i),i.indexOf("/")>=0)throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid collection ID '${i}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Query(e,null,function __PRIVATE_newQueryForCollectionGroup(e){return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(),e)}(i))}function doc(e,i,...s){if(e=getModularInstance(e),1===arguments.length&&(i=__PRIVATE_AutoId.newId()),__PRIVATE_validateNonEmptyArgument("doc","path",i),e instanceof Firestore$1){const o=ResourcePath.fromString(i,...s);return __PRIVATE_validateDocumentPath(o),new DocumentReference(e,null,new DocumentKey(o))}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(_e.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const o=e._path.child(ResourcePath.fromString(i,...s));return __PRIVATE_validateDocumentPath(o),new DocumentReference(e.firestore,e instanceof CollectionReference?e.converter:null,new DocumentKey(o))}}function refEqual(e,i){return e=getModularInstance(e),i=getModularInstance(i),(e instanceof DocumentReference||e instanceof CollectionReference)&&(i instanceof DocumentReference||i instanceof CollectionReference)&&e.firestore===i.firestore&&e.path===i.path&&e.converter===i.converter}function queryEqual(e,i){return e=getModularInstance(e),i=getModularInstance(i),e instanceof Query&&i instanceof Query&&e.firestore===i.firestore&&__PRIVATE_queryEquals(e._query,i._query)&&e.converter===i.converter}class __PRIVATE_AsyncQueueImpl{constructor(e=Promise.resolve()){this.Pu=[],this.Iu=!1,this.Tu=[],this.Eu=null,this.du=!1,this.Au=!1,this.Ru=[],this.t_=new __PRIVATE_ExponentialBackoff(this,"async_queue_retry"),this.Vu=()=>{const e=getDocument();e&&__PRIVATE_logDebug("AsyncQueue","Visibility state changed to "+e.visibilityState),this.t_.jo()},this.mu=e;const i=getDocument();i&&"function"==typeof i.addEventListener&&i.addEventListener("visibilitychange",this.Vu)}get isShuttingDown(){return this.Iu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.fu(),this.gu(e)}enterRestrictedMode(e){if(!this.Iu){this.Iu=!0,this.Au=e||!1;const i=getDocument();i&&"function"==typeof i.removeEventListener&&i.removeEventListener("visibilitychange",this.Vu)}}enqueue(e){if(this.fu(),this.Iu)return new Promise((()=>{}));const i=new __PRIVATE_Deferred;return this.gu((()=>this.Iu&&this.Au?Promise.resolve():(e().then(i.resolve,i.reject),i.promise))).then((()=>i.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Pu.push(e),this.pu())))}async pu(){if(0!==this.Pu.length){try{await this.Pu[0](),this.Pu.shift(),this.t_.reset()}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug("AsyncQueue","Operation failed with retryable error: "+e)}this.Pu.length>0&&this.t_.Go((()=>this.pu()))}}gu(e){const i=this.mu.then((()=>(this.du=!0,e().catch((e=>{this.Eu=e,this.du=!1;const i=function __PRIVATE_getMessageOrStack(e){let i=e.message||"";return e.stack&&(i=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),i}(e);throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ",i),e})).then((e=>(this.du=!1,e))))));return this.mu=i,i}enqueueAfterDelay(e,i,s){this.fu(),this.Ru.indexOf(e)>-1&&(i=0);const o=DelayedOperation.createAndSchedule(this,e,i,s,(e=>this.yu(e)));return this.Tu.push(o),o}fu(){this.Eu&&fail()}verifyOperationInProgress(){}async wu(){let e;do{e=this.mu,await e}while(e!==this.mu)}Su(e){for(const i of this.Tu)if(i.timerId===e)return!0;return!1}bu(e){return this.wu().then((()=>{this.Tu.sort(((e,i)=>e.targetTimeMs-i.targetTimeMs));for(const i of this.Tu)if(i.skipDelay(),"all"!==e&&i.timerId===e)break;return this.wu()}))}Du(e){this.Ru.push(e)}yu(e){const i=this.Tu.indexOf(e);this.Tu.splice(i,1)}}function __PRIVATE_isPartialObserver(e){return function __PRIVATE_implementsAnyMethods(e,i){if("object"!=typeof e||null===e)return!1;const s=e;for(const e of i)if(e in s&&"function"==typeof s[e])return!0;return!1}(e,["next","error","complete"])}class LoadBundleTask{constructor(){this._progressObserver={},this._taskCompletionResolver=new __PRIVATE_Deferred,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,i,s){this._progressObserver={next:e,error:i,complete:s}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,i){return this._taskCompletionResolver.promise.then(e,i)}_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)}}const ct=-1;class Firestore extends Firestore$1{constructor(e,i,s,o){super(e,i,s,o),this.type="firestore",this._queue=new __PRIVATE_AsyncQueueImpl,this._persistenceKey=(null==o?void 0:o.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new __PRIVATE_AsyncQueueImpl(e),this._firestoreClient=void 0,await e}}}function initializeFirestore(e,i,s){s||(s="(default)");const o=_getProvider(e,"firestore");if(o.isInitialized(s)){const e=o.getImmediate({identifier:s});if(deepEqual(o.getOptions(s),i))return e;throw new FirestoreError(_e.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==i.cacheSizeBytes&&void 0!==i.localCache)throw new FirestoreError(_e.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(void 0!==i.cacheSizeBytes&&-1!==i.cacheSizeBytes&&i.cacheSizeBytes<1048576)throw new FirestoreError(_e.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return o.initialize({options:i,instanceIdentifier:s})}function getFirestore(e,i){const o="object"==typeof e?e:s(),_="string"==typeof e?e:i||"(default)",h=_getProvider(o,"firestore").getImmediate({identifier:_});if(!h._initialized){const e=getDefaultEmulatorHostnameAndPort("firestore");e&&connectFirestoreEmulator(h,...e)}return h}function ensureFirestoreConfigured(e){if(e._terminated)throw new FirestoreError(_e.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||__PRIVATE_configureFirestore(e),e._firestoreClient}function __PRIVATE_configureFirestore(e){var i,s,o;const _=e._freezeSettings(),h=function __PRIVATE_makeDatabaseInfo(e,i,s,o){return new DatabaseInfo(e,i,s,o.host,o.ssl,o.experimentalForceLongPolling,o.experimentalAutoDetectLongPolling,__PRIVATE_cloneLongPollingOptions(o.experimentalLongPollingOptions),o.useFetchStreams)}(e._databaseId,(null===(i=e._app)||void 0===i?void 0:i.options.appId)||"",e._persistenceKey,_);e._componentsProvider||(null===(s=_.localCache)||void 0===s?void 0:s._offlineComponentProvider)&&(null===(o=_.localCache)||void 0===o?void 0:o._onlineComponentProvider)&&(e._componentsProvider={_offline:_.localCache._offlineComponentProvider,_online:_.localCache._onlineComponentProvider}),e._firestoreClient=new FirestoreClient(e._authCredentials,e._appCheckCredentials,e._queue,h,e._componentsProvider&&function __PRIVATE_buildComponentProvider(e){const i=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(i),_online:i}}(e._componentsProvider))}function enableIndexedDbPersistence(e,i){__PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const s=e._freezeSettings();return __PRIVATE_setPersistenceProviders(e,OnlineComponentProvider.provider,{build:e=>new __PRIVATE_IndexedDbOfflineComponentProvider(e,s.cacheSizeBytes,null==i?void 0:i.forceOwnership)}),Promise.resolve()}async function enableMultiTabIndexedDbPersistence(e){__PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const i=e._freezeSettings();__PRIVATE_setPersistenceProviders(e,OnlineComponentProvider.provider,{build:e=>new __PRIVATE_MultiTabOfflineComponentProvider(e,i.cacheSizeBytes)})}function __PRIVATE_setPersistenceProviders(e,i,s){if((e=__PRIVATE_cast(e,Firestore))._firestoreClient||e._terminated)throw new FirestoreError(_e.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.");if(e._componentsProvider||e._getSettings().localCache)throw new FirestoreError(_e.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:i,_offline:s},__PRIVATE_configureFirestore(e)}function clearIndexedDbPersistence(e){if(e._initialized&&!e._terminated)throw new FirestoreError(_e.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const i=new __PRIVATE_Deferred;return e._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await async function __PRIVATE_indexedDbClearPersistence(e){if(!__PRIVATE_SimpleDb.D())return Promise.resolve();const i=e+"main";await __PRIVATE_SimpleDb.delete(i)}(__PRIVATE_indexedDbStoragePrefix(e._databaseId,e._persistenceKey)),i.resolve()}catch(e){i.reject(e)}})),i.promise}function waitForPendingWrites(e){return function __PRIVATE_firestoreClientWaitForPendingWrites(e){const i=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e,i){const s=__PRIVATE_debugCast(e);__PRIVATE_canUseNetwork(s.remoteStore)||__PRIVATE_logDebug("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e){const i=__PRIVATE_debugCast(e);return i.persistence.runTransaction("Get highest unacknowledged batch id","readonly",(e=>i.mutationQueue.getHighestUnacknowledgedBatchId(e)))}(s.localStore);if(-1===e)return void i.resolve();const o=s.ka.get(e)||[];o.push(i),s.ka.set(e,o)}catch(e){const s=__PRIVATE_wrapInUserErrorIfRecoverable(e,"Initialization of waitForPendingWrites() operation failed");i.reject(s)}}(await __PRIVATE_getSyncEngine(e),i))),i.promise}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)))}function enableNetwork(e){return function __PRIVATE_firestoreClientEnableNetwork(e){return e.asyncQueue.enqueue((async()=>{const i=await __PRIVATE_getPersistence(e),s=await __PRIVATE_getRemoteStore(e);return i.setNetworkEnabled(!0),function __PRIVATE_remoteStoreEnableNetwork(e){const i=__PRIVATE_debugCast(e);return i.L_.delete(0),__PRIVATE_enableNetworkInternal(i)}(s)}))}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)))}function disableNetwork(e){return function __PRIVATE_firestoreClientDisableNetwork(e){return e.asyncQueue.enqueue((async()=>{const i=await __PRIVATE_getPersistence(e),s=await __PRIVATE_getRemoteStore(e);return i.setNetworkEnabled(!1),async function __PRIVATE_remoteStoreDisableNetwork(e){const i=__PRIVATE_debugCast(e);i.L_.add(0),await __PRIVATE_disableNetworkInternal(i),i.q_.set("Offline")}(s)}))}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)))}function terminate(e){return o(e.app,"firestore",e._databaseId.database),e._delete()}function loadBundle(e,i){const s=ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),o=new LoadBundleTask;return __PRIVATE_firestoreClientLoadBundle(s,e._databaseId,i,o),o}function namedQuery(e,i){return function __PRIVATE_firestoreClientGetNamedQuery(e,i){return e.asyncQueue.enqueue((async()=>function __PRIVATE_localStoreGetNamedQuery(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("Get named query","readonly",(e=>s.Gr.getNamedQuery(e,i)))}(await __PRIVATE_getLocalStore(e),i)))}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),i).then((i=>i?new Query(e,null,i.query):null))}class AggregateField{constructor(e="count",i){this._internalFieldPath=i,this.type="AggregateField",this.aggregateType=e}}class AggregateQuerySnapshot{constructor(e,i,s){this._userDataWriter=i,this._data=s,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Bytes{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Bytes(ByteString.fromBase64String(e))}catch(e){throw new FirestoreError(_e.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Bytes(ByteString.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 FieldPath{constructor(...e){for(let i=0;i<e.length;++i)if(0===e[i].length)throw new FirestoreError(_e.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new FieldPath$1(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}function documentId(){return new FieldPath("__name__")}class FieldValue{constructor(e){this._methodName=e}}class GeoPoint{constructor(e,i){if(!isFinite(e)||e<-90||e>90)throw new FirestoreError(_e.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(i)||i<-180||i>180)throw new FirestoreError(_e.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+i);this._lat=e,this._long=i}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 __PRIVATE_primitiveComparator(this._lat,e._lat)||__PRIVATE_primitiveComparator(this._long,e._long)}}class VectorValue{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function __PRIVATE_isPrimitiveArrayEqual(e,i){if(e.length!==i.length)return!1;for(let s=0;s<e.length;++s)if(e[s]!==i[s])return!1;return!0}(this._values,e._values)}}const lt=/^__.*__$/;class ParsedSetData{constructor(e,i,s){this.data=e,this.fieldMask=i,this.fieldTransforms=s}toMutation(e,i){return null!==this.fieldMask?new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,i,this.fieldTransforms):new __PRIVATE_SetMutation(e,this.data,i,this.fieldTransforms)}}class ParsedUpdateData{constructor(e,i,s){this.data=e,this.fieldMask=i,this.fieldTransforms=s}toMutation(e,i){return new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,i,this.fieldTransforms)}}function __PRIVATE_isWrite(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw fail()}}class __PRIVATE_ParseContextImpl{constructor(e,i,s,o,_,h){this.settings=e,this.databaseId=i,this.serializer=s,this.ignoreUndefinedProperties=o,void 0===_&&this.vu(),this.fieldTransforms=_||[],this.fieldMask=h||[]}get path(){return this.settings.path}get Cu(){return this.settings.Cu}Fu(e){return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Mu(e){var i;const s=null===(i=this.path)||void 0===i?void 0:i.child(e),o=this.Fu({path:s,xu:!1});return o.Ou(e),o}Nu(e){var i;const s=null===(i=this.path)||void 0===i?void 0:i.child(e),o=this.Fu({path:s,xu:!1});return o.vu(),o}Lu(e){return this.Fu({path:void 0,xu:!0})}Bu(e){return __PRIVATE_createError(e,this.settings.methodName,this.settings.ku||!1,this.path,this.settings.qu)}contains(e){return void 0!==this.fieldMask.find((i=>e.isPrefixOf(i)))||void 0!==this.fieldTransforms.find((i=>e.isPrefixOf(i.field)))}vu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Ou(this.path.get(e))}Ou(e){if(0===e.length)throw this.Bu("Document fields must not be empty");if(__PRIVATE_isWrite(this.Cu)&&lt.test(e))throw this.Bu('Document fields cannot begin and end with "__"')}}class __PRIVATE_UserDataReader{constructor(e,i,s){this.databaseId=e,this.ignoreUndefinedProperties=i,this.serializer=s||__PRIVATE_newSerializer(e)}Qu(e,i,s,o=!1){return new __PRIVATE_ParseContextImpl({Cu:e,methodName:i,qu:s,path:FieldPath$1.emptyPath(),xu:!1,ku:o},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function __PRIVATE_newUserDataReader(e){const i=e._freezeSettings(),s=__PRIVATE_newSerializer(e._databaseId);return new __PRIVATE_UserDataReader(e._databaseId,!!i.ignoreUndefinedProperties,s)}function __PRIVATE_parseSetData(e,i,s,o,_,h={}){const d=e.Qu(h.merge||h.mergeFields?2:0,i,s,_);__PRIVATE_validatePlainObject("Data must be an object, but it was:",d,o);const f=__PRIVATE_parseObject(o,d);let g,b;if(h.merge)g=new FieldMask(d.fieldMask),b=d.fieldTransforms;else if(h.mergeFields){const e=[];for(const o of h.mergeFields){const _=__PRIVATE_fieldPathFromArgument$1(i,o,s);if(!d.contains(_))throw new FirestoreError(_e.INVALID_ARGUMENT,`Field '${_}' is specified in your field mask but missing from your input data.`);__PRIVATE_fieldMaskContains(e,_)||e.push(_)}g=new FieldMask(e),b=d.fieldTransforms.filter((e=>g.covers(e.field)))}else g=null,b=d.fieldTransforms;return new ParsedSetData(new ObjectValue(f),g,b)}class __PRIVATE_DeleteFieldValueImpl extends FieldValue{_toFieldTransform(e){if(2!==e.Cu)throw 1===e.Cu?e.Bu(`${this._methodName}() can only appear at the top level of your update data`):e.Bu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof __PRIVATE_DeleteFieldValueImpl}}function __PRIVATE_createSentinelChildContext(e,i,s){return new __PRIVATE_ParseContextImpl({Cu:3,qu:i.settings.qu,methodName:e._methodName,xu:s},i.databaseId,i.serializer,i.ignoreUndefinedProperties)}class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue{_toFieldTransform(e){return new FieldTransform(e.path,new __PRIVATE_ServerTimestampTransform)}isEqual(e){return e instanceof __PRIVATE_ServerTimestampFieldValueImpl}}class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ku=i}_toFieldTransform(e){const i=__PRIVATE_createSentinelChildContext(this,e,!0),s=this.Ku.map((e=>__PRIVATE_parseData(e,i))),o=new __PRIVATE_ArrayUnionTransformOperation(s);return new FieldTransform(e.path,o)}isEqual(e){return e instanceof __PRIVATE_ArrayUnionFieldValueImpl&&deepEqual(this.Ku,e.Ku)}}class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ku=i}_toFieldTransform(e){const i=__PRIVATE_createSentinelChildContext(this,e,!0),s=this.Ku.map((e=>__PRIVATE_parseData(e,i))),o=new __PRIVATE_ArrayRemoveTransformOperation(s);return new FieldTransform(e.path,o)}isEqual(e){return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl&&deepEqual(this.Ku,e.Ku)}}class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.$u=i}_toFieldTransform(e){const i=new __PRIVATE_NumericIncrementTransformOperation(e.serializer,toNumber(e.serializer,this.$u));return new FieldTransform(e.path,i)}isEqual(e){return e instanceof __PRIVATE_NumericIncrementFieldValueImpl&&this.$u===e.$u}}function __PRIVATE_parseUpdateData(e,i,s,o){const _=e.Qu(1,i,s);__PRIVATE_validatePlainObject("Data must be an object, but it was:",_,o);const h=[],d=ObjectValue.empty();forEach(o,((e,o)=>{const f=__PRIVATE_fieldPathFromDotSeparatedString(i,e,s);o=getModularInstance(o);const g=_.Nu(f);if(o instanceof __PRIVATE_DeleteFieldValueImpl)h.push(f);else{const e=__PRIVATE_parseData(o,g);null!=e&&(h.push(f),d.set(f,e))}}));const f=new FieldMask(h);return new ParsedUpdateData(d,f,_.fieldTransforms)}function __PRIVATE_parseUpdateVarargs(e,i,s,o,_,h){const d=e.Qu(1,i,s),f=[__PRIVATE_fieldPathFromArgument$1(i,o,s)],g=[_];if(h.length%2!=0)throw new FirestoreError(_e.INVALID_ARGUMENT,`Function ${i}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<h.length;e+=2)f.push(__PRIVATE_fieldPathFromArgument$1(i,h[e])),g.push(h[e+1]);const b=[],w=ObjectValue.empty();for(let e=f.length-1;e>=0;--e)if(!__PRIVATE_fieldMaskContains(b,f[e])){const i=f[e];let s=g[e];s=getModularInstance(s);const o=d.Nu(i);if(s instanceof __PRIVATE_DeleteFieldValueImpl)b.push(i);else{const e=__PRIVATE_parseData(s,o);null!=e&&(b.push(i),w.set(i,e))}}const O=new FieldMask(b);return new ParsedUpdateData(w,O,d.fieldTransforms)}function __PRIVATE_parseQueryValue(e,i,s,o=!1){return __PRIVATE_parseData(s,e.Qu(o?4:3,i))}function __PRIVATE_parseData(e,i){if(__PRIVATE_looksLikeJsonObject(e=getModularInstance(e)))return __PRIVATE_validatePlainObject("Unsupported field value:",i,e),__PRIVATE_parseObject(e,i);if(e instanceof FieldValue)return function __PRIVATE_parseSentinelFieldValue(e,i){if(!__PRIVATE_isWrite(i.Cu))throw i.Bu(`${e._methodName}() can only be used with update() and set()`);if(!i.path)throw i.Bu(`${e._methodName}() is not currently supported inside arrays`);const s=e._toFieldTransform(i);s&&i.fieldTransforms.push(s)}(e,i),null;if(void 0===e&&i.ignoreUndefinedProperties)return null;if(i.path&&i.fieldMask.push(i.path),e instanceof Array){if(i.settings.xu&&4!==i.Cu)throw i.Bu("Nested arrays are not supported");return function __PRIVATE_parseArray(e,i){const s=[];let o=0;for(const _ of e){let e=__PRIVATE_parseData(_,i.Lu(o));null==e&&(e={nullValue:"NULL_VALUE"}),s.push(e),o++}return{arrayValue:{values:s}}}(e,i)}return function __PRIVATE_parseScalarValue(e,i){if(null===(e=getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return toNumber(i.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const s=Timestamp.fromDate(e);return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof Timestamp){const s=new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof GeoPoint)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Bytes)return{bytesValue:__PRIVATE_toBytes(i.serializer,e._byteString)};if(e instanceof DocumentReference){const s=i.databaseId,o=e.firestore._databaseId;if(!o.isEqual(s))throw i.Bu(`Document reference is for database ${o.projectId}/${o.database} but should be for database ${s.projectId}/${s.database}`);return{referenceValue:__PRIVATE_toResourceName(e.firestore._databaseId||i.databaseId,e._key.path)}}if(e instanceof VectorValue)return function __PRIVATE_parseVectorValue(e,i){return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map((e=>{if("number"!=typeof e)throw i.Bu("VectorValues must only contain numeric values.");return __PRIVATE_toDouble(i.serializer,e)}))}}}}}}(e,i);throw i.Bu(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`)}(e,i)}function __PRIVATE_parseObject(e,i){const s={};return isEmpty(e)?i.path&&i.path.length>0&&i.fieldMask.push(i.path):forEach(e,((e,o)=>{const _=__PRIVATE_parseData(o,i.Mu(e));null!=_&&(s[e]=_)})),{mapValue:{fields:s}}}function __PRIVATE_looksLikeJsonObject(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Bytes||e instanceof DocumentReference||e instanceof FieldValue||e instanceof VectorValue)}function __PRIVATE_validatePlainObject(e,i,s){if(!__PRIVATE_looksLikeJsonObject(s)||!function __PRIVATE_isPlainObject(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(s)){const o=__PRIVATE_valueDescription(s);throw"an object"===o?i.Bu(e+" a custom object"):i.Bu(e+" "+o)}}function __PRIVATE_fieldPathFromArgument$1(e,i,s){if((i=getModularInstance(i))instanceof FieldPath)return i._internalPath;if("string"==typeof i)return __PRIVATE_fieldPathFromDotSeparatedString(e,i);throw __PRIVATE_createError("Field path arguments must be of type string or ",e,!1,void 0,s)}const _t=new RegExp("[~\\*/\\[\\]]");function __PRIVATE_fieldPathFromDotSeparatedString(e,i,s){if(i.search(_t)>=0)throw __PRIVATE_createError(`Invalid field path (${i}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,s);try{return new FieldPath(...i.split("."))._internalPath}catch(o){throw __PRIVATE_createError(`Invalid field path (${i}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,s)}}function __PRIVATE_createError(e,i,s,o,_){const h=o&&!o.isEmpty(),d=void 0!==_;let f=`Function ${i}() called with invalid data`;s&&(f+=" (via `toFirestore()`)"),f+=". ";let g="";return(h||d)&&(g+=" (found",h&&(g+=` in field ${o}`),d&&(g+=` in document ${_}`),g+=")"),new FirestoreError(_e.INVALID_ARGUMENT,f+e+g)}function __PRIVATE_fieldMaskContains(e,i){return e.some((e=>e.isEqual(i)))}class DocumentSnapshot$1{constructor(e,i,s,o,_){this._firestore=e,this._userDataWriter=i,this._key=s,this._document=o,this._converter=_}get id(){return this._key.path.lastSegment()}get ref(){return new DocumentReference(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new QueryDocumentSnapshot$1(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const i=this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get",e));if(null!==i)return this._userDataWriter.convertValue(i)}}}class QueryDocumentSnapshot$1 extends DocumentSnapshot$1{data(){return super.data()}}function __PRIVATE_fieldPathFromArgument(e,i){return"string"==typeof i?__PRIVATE_fieldPathFromDotSeparatedString(e,i):i instanceof FieldPath?i._internalPath:i._delegate._internalPath}function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new FirestoreError(_e.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class AppliableConstraint{}class QueryConstraint extends AppliableConstraint{}function query(e,i,...s){let o=[];i instanceof AppliableConstraint&&o.push(i),o=o.concat(s),function __PRIVATE_validateQueryConstraintArray(e){const i=e.filter((e=>e instanceof QueryCompositeFilterConstraint)).length,s=e.filter((e=>e instanceof QueryFieldFilterConstraint)).length;if(i>1||i>0&&s>0)throw new FirestoreError(_e.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(...)))`.")}(o);for(const i of o)e=i._apply(e);return e}class QueryFieldFilterConstraint extends QueryConstraint{constructor(e,i,s){super(),this._field=e,this._op=i,this._value=s,this.type="where"}static _create(e,i,s){return new QueryFieldFilterConstraint(e,i,s)}_apply(e){const i=this._parse(e);return __PRIVATE_validateNewFieldFilter(e._query,i),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,i))}_parse(e){const i=__PRIVATE_newUserDataReader(e.firestore),s=function __PRIVATE_newQueryFilter(e,i,s,o,_,h,d){let f;if(_.isKeyField()){if("array-contains"===h||"array-contains-any"===h)throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid Query. You can't perform '${h}' queries on documentId().`);if("in"===h||"not-in"===h){__PRIVATE_validateDisjunctiveFilterElements(d,h);const i=[];for(const s of d)i.push(__PRIVATE_parseDocumentIdValue(o,e,s));f={arrayValue:{values:i}}}else f=__PRIVATE_parseDocumentIdValue(o,e,d)}else"in"!==h&&"not-in"!==h&&"array-contains-any"!==h||__PRIVATE_validateDisjunctiveFilterElements(d,h),f=__PRIVATE_parseQueryValue(s,i,d,"in"===h||"not-in"===h);return FieldFilter.create(_,h,f)}(e._query,"where",i,e.firestore._databaseId,this._field,this._op,this._value);return s}}function where(e,i,s){const o=i,_=__PRIVATE_fieldPathFromArgument("where",e);return QueryFieldFilterConstraint._create(_,o,s)}class QueryCompositeFilterConstraint extends AppliableConstraint{constructor(e,i){super(),this.type=e,this._queryConstraints=i}static _create(e,i){return new QueryCompositeFilterConstraint(e,i)}_parse(e){const i=this._queryConstraints.map((i=>i._parse(e))).filter((e=>e.getFilters().length>0));return 1===i.length?i[0]:CompositeFilter.create(i,this._getOperator())}_apply(e){const i=this._parse(e);return 0===i.getFilters().length?e:(function __PRIVATE_validateNewFilter(e,i){let s=e;const o=i.getFlattenedFilters();for(const e of o)__PRIVATE_validateNewFieldFilter(s,e),s=__PRIVATE_queryWithAddedFilter(s,e)}(e._query,i),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,i)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function or(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("or",e))),QueryCompositeFilterConstraint._create("or",e)}function and(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("and",e))),QueryCompositeFilterConstraint._create("and",e)}class QueryOrderByConstraint extends QueryConstraint{constructor(e,i){super(),this._field=e,this._direction=i,this.type="orderBy"}static _create(e,i){return new QueryOrderByConstraint(e,i)}_apply(e){const i=function __PRIVATE_newQueryOrderBy(e,i,s){if(null!==e.startAt)throw new FirestoreError(_e.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new FirestoreError(_e.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new OrderBy(i,s)}(e._query,this._field,this._direction);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithAddedOrderBy(e,i){const s=e.explicitOrderBy.concat([i]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,s,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,i))}}function orderBy(e,i="asc"){const s=i,o=__PRIVATE_fieldPathFromArgument("orderBy",e);return QueryOrderByConstraint._create(o,s)}class QueryLimitConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._limit=i,this._limitType=s}static _create(e,i,s){return new QueryLimitConstraint(e,i,s)}_apply(e){return new Query(e.firestore,e.converter,__PRIVATE_queryWithLimit(e._query,this._limit,this._limitType))}}function limit(e){return __PRIVATE_validatePositiveNumber("limit",e),QueryLimitConstraint._create("limit",e,"F")}function limitToLast(e){return __PRIVATE_validatePositiveNumber("limitToLast",e),QueryLimitConstraint._create("limitToLast",e,"L")}class QueryStartAtConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._docOrFields=i,this._inclusive=s}static _create(e,i,s){return new QueryStartAtConstraint(e,i,s)}_apply(e){const i=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithStartAt(e,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,i,e.endAt)}(e._query,i))}}function startAt(...e){return QueryStartAtConstraint._create("startAt",e,!0)}function startAfter(...e){return QueryStartAtConstraint._create("startAfter",e,!1)}class QueryEndAtConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._docOrFields=i,this._inclusive=s}static _create(e,i,s){return new QueryEndAtConstraint(e,i,s)}_apply(e){const i=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithEndAt(e,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,i)}(e._query,i))}}function endBefore(...e){return QueryEndAtConstraint._create("endBefore",e,!1)}function endAt(...e){return QueryEndAtConstraint._create("endAt",e,!0)}function __PRIVATE_newQueryBoundFromDocOrFields(e,i,s,o){if(s[0]=getModularInstance(s[0]),s[0]instanceof DocumentSnapshot$1)return function __PRIVATE_newQueryBoundFromDocument(e,i,s,o,_){if(!o)throw new FirestoreError(_e.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${s}().`);const h=[];for(const s of __PRIVATE_queryNormalizedOrderBy(e))if(s.field.isKeyField())h.push(__PRIVATE_refValue(i,o.key));else{const e=o.data.field(s.field);if(__PRIVATE_isServerTimestamp(e))throw new FirestoreError(_e.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+s.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=s.field.canonicalString();throw new FirestoreError(_e.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.`)}h.push(e)}return new Bound(h,_)}(e._query,e.firestore._databaseId,i,s[0]._document,o);{const _=__PRIVATE_newUserDataReader(e.firestore);return function __PRIVATE_newQueryBoundFromFields(e,i,s,o,_,h){const d=e.explicitOrderBy;if(_.length>d.length)throw new FirestoreError(_e.INVALID_ARGUMENT,`Too many arguments provided to ${o}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const f=[];for(let h=0;h<_.length;h++){const g=_[h];if(d[h].field.isKeyField()){if("string"!=typeof g)throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${o}(), but got a ${typeof g}`);if(!__PRIVATE_isCollectionGroupQuery(e)&&-1!==g.indexOf("/"))throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${o}() must be a plain document ID, but '${g}' contains a slash.`);const s=e.path.child(ResourcePath.fromString(g));if(!DocumentKey.isDocumentKey(s))throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${o}() must result in a valid document path, but '${s}' is not because it contains an odd number of segments.`);const _=new DocumentKey(s);f.push(__PRIVATE_refValue(i,_))}else{const e=__PRIVATE_parseQueryValue(s,o,g);f.push(e)}}return new Bound(f,h)}(e._query,e.firestore._databaseId,_,i,s,o)}}function __PRIVATE_parseDocumentIdValue(e,i,s){if("string"==typeof(s=getModularInstance(s))){if(""===s)throw new FirestoreError(_e.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!__PRIVATE_isCollectionGroupQuery(i)&&-1!==s.indexOf("/"))throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${s}' contains a '/' character.`);const o=i.path.child(ResourcePath.fromString(s));if(!DocumentKey.isDocumentKey(o))throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${o}' is not because it has an odd number of segments (${o.length}).`);return __PRIVATE_refValue(e,new DocumentKey(o))}if(s instanceof DocumentReference)return __PRIVATE_refValue(e,s._key);throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(s)}.`)}function __PRIVATE_validateDisjunctiveFilterElements(e,i){if(!Array.isArray(e)||0===e.length)throw new FirestoreError(_e.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${i.toString()}' filters.`)}function __PRIVATE_validateNewFieldFilter(e,i){const s=function __PRIVATE_findOpInsideFilters(e,i){for(const s of e)for(const e of s.getFlattenedFilters())if(i.indexOf(e.op)>=0)return e.op;return null}(e.filters,function __PRIVATE_conflictingOps(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[]}}(i.op));if(null!==s)throw s===i.op?new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${i.op.toString()}' filter.`):new FirestoreError(_e.INVALID_ARGUMENT,`Invalid query. You cannot use '${i.op.toString()}' filters with '${s.toString()}' filters.`)}function __PRIVATE_validateQueryFilterConstraint(e,i){if(!(i instanceof QueryFieldFilterConstraint||i instanceof QueryCompositeFilterConstraint))throw new FirestoreError(_e.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class AbstractUserDataWriter{convertValue(e,i="none"){switch(__PRIVATE_typeOrder(e)){case 0:return null;case 1:return e.booleanValue;case 2:return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,i);case 5:return e.stringValue;case 6:return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,i);case 11:return this.convertObject(e.mapValue,i);case 10:return this.convertVectorValue(e.mapValue);default:throw fail()}}convertObject(e,i){return this.convertObjectMap(e.fields,i)}convertObjectMap(e,i="none"){const s={};return forEach(e,((e,o)=>{s[e]=this.convertValue(o,i)})),s}convertVectorValue(e){var i,s,o;const _=null===(o=null===(s=null===(i=e.fields)||void 0===i?void 0:i.value.arrayValue)||void 0===s?void 0:s.values)||void 0===o?void 0:o.map((e=>__PRIVATE_normalizeNumber(e.doubleValue)));return new VectorValue(_)}convertGeoPoint(e){return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(e.longitude))}convertArray(e,i){return(e.values||[]).map((e=>this.convertValue(e,i)))}convertServerTimestamp(e,i){switch(i){case"previous":const s=__PRIVATE_getPreviousValue(e);return null==s?null:this.convertValue(s,i);case"estimate":return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));default:return null}}convertTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}convertDocumentKey(e,i){const s=ResourcePath.fromString(e);__PRIVATE_hardAssert(__PRIVATE_isValidResourceName(s));const o=new DatabaseId(s.get(1),s.get(3)),_=new DocumentKey(s.popFirst(5));return o.isEqual(i)||__PRIVATE_logError(`Document ${_} contains a document reference within a different database (${o.projectId}/${o.database}) which is not supported. It will be treated as a reference in the current database (${i.projectId}/${i.database}) instead.`),_}}function __PRIVATE_applyFirestoreDataConverter(e,i,s){let o;return o=e?s&&(s.merge||s.mergeFields)?e.toFirestore(i,s):e.toFirestore(i):i,o}class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const i=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,i)}}function sum(e){return new AggregateField("sum",__PRIVATE_fieldPathFromArgument$1("sum",e))}function average(e){return new AggregateField("avg",__PRIVATE_fieldPathFromArgument$1("average",e))}function count(){return new AggregateField("count")}function aggregateFieldEqual(e,i){var s,o;return e instanceof AggregateField&&i instanceof AggregateField&&e.aggregateType===i.aggregateType&&(null===(s=e._internalFieldPath)||void 0===s?void 0:s.canonicalString())===(null===(o=i._internalFieldPath)||void 0===o?void 0:o.canonicalString())}function aggregateQuerySnapshotEqual(e,i){return queryEqual(e.query,i.query)&&deepEqual(e.data(),i.data())}class SnapshotMetadata{constructor(e,i){this.hasPendingWrites=e,this.fromCache=i}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class DocumentSnapshot extends DocumentSnapshot$1{constructor(e,i,s,o,_,h){super(e,i,s,o,h),this._firestore=e,this._firestoreImpl=e,this.metadata=_}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const i=new QueryDocumentSnapshot(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(i,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,i={}){if(this._document){const s=this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get",e));if(null!==s)return this._userDataWriter.convertValue(s,i.serverTimestamps)}}}class QueryDocumentSnapshot extends DocumentSnapshot{data(e={}){return super.data(e)}}class QuerySnapshot{constructor(e,i,s,o){this._firestore=e,this._userDataWriter=i,this._snapshot=o,this.metadata=new SnapshotMetadata(o.hasPendingWrites,o.fromCache),this.query=s}get docs(){const e=[];return this.forEach((i=>e.push(i))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,i){this._snapshot.docs.forEach((s=>{e.call(i,new QueryDocumentSnapshot(this._firestore,this._userDataWriter,s.key,s,new SnapshotMetadata(this._snapshot.mutatedKeys.has(s.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const i=!!e.includeMetadataChanges;if(i&&this._snapshot.excludesMetadataChanges)throw new FirestoreError(_e.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===i||(this._cachedChanges=function __PRIVATE_changesFromSnapshot(e,i){if(e._snapshot.oldDocs.isEmpty()){let i=0;return e._snapshot.docChanges.map((s=>{const o=new QueryDocumentSnapshot(e._firestore,e._userDataWriter,s.doc.key,s.doc,new SnapshotMetadata(e._snapshot.mutatedKeys.has(s.doc.key),e._snapshot.fromCache),e.query.converter);return s.doc,{type:"added",doc:o,oldIndex:-1,newIndex:i++}}))}{let s=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>i||3!==e.type)).map((i=>{const o=new QueryDocumentSnapshot(e._firestore,e._userDataWriter,i.doc.key,i.doc,new SnapshotMetadata(e._snapshot.mutatedKeys.has(i.doc.key),e._snapshot.fromCache),e.query.converter);let _=-1,h=-1;return 0!==i.type&&(_=s.indexOf(i.doc.key),s=s.delete(i.doc.key)),1!==i.type&&(s=s.add(i.doc),h=s.indexOf(i.doc.key)),{type:__PRIVATE_resultChangeType(i.type),doc:o,oldIndex:_,newIndex:h}}))}}(this,i),this._cachedChangesIncludeMetadataChanges=i),this._cachedChanges}}function __PRIVATE_resultChangeType(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return fail()}}function snapshotEqual(e,i){return e instanceof DocumentSnapshot&&i instanceof DocumentSnapshot?e._firestore===i._firestore&&e._key.isEqual(i._key)&&(null===e._document?null===i._document:e._document.isEqual(i._document))&&e._converter===i._converter:e instanceof QuerySnapshot&&i instanceof QuerySnapshot&&e._firestore===i._firestore&&queryEqual(e.query,i.query)&&e.metadata.isEqual(i.metadata)&&e._snapshot.isEqual(i._snapshot)}function getDoc(e){e=__PRIVATE_cast(e,DocumentReference);const i=__PRIVATE_cast(e.firestore,Firestore);return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(i),e._key).then((s=>__PRIVATE_convertToDocSnapshot(i,e,s)))}class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const i=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,i)}}function getDocFromCache(e){e=__PRIVATE_cast(e,DocumentReference);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e,i){const s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_readDocumentFromCache(e,i,s){try{const o=await function __PRIVATE_localStoreReadDocument(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction("read document","readonly",(e=>s.localDocuments.getDocument(e,i)))}(e,i);o.isFoundDocument()?s.resolve(o):o.isNoDocument()?s.resolve(null):s.reject(new FirestoreError(_e.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){const o=__PRIVATE_wrapInUserErrorIfRecoverable(e,`Failed to get document '${i} from cache`);s.reject(o)}}(await __PRIVATE_getLocalStore(e),i,s))),s.promise}(s,e._key).then((s=>new DocumentSnapshot(i,o,e._key,s,new SnapshotMetadata(null!==s&&s.hasLocalMutations,!0),e.converter)))}function getDocFromServer(e){e=__PRIVATE_cast(e,DocumentReference);const i=__PRIVATE_cast(e.firestore,Firestore);return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(i),e._key,{source:"server"}).then((s=>__PRIVATE_convertToDocSnapshot(i,e,s)))}function getDocs(e){e=__PRIVATE_cast(e,Query);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query),__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(s,e._query).then((s=>new QuerySnapshot(i,o,e,s)))}function getDocsFromCache(e){e=__PRIVATE_cast(e,Query);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e,i){const s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_executeQueryFromCache(e,i,s){try{const o=await __PRIVATE_localStoreExecuteQuery(e,i,!0),_=new __PRIVATE_View(i,o.Ts),h=_.ma(o.documents),d=_.applyChanges(h,!1);s.resolve(d.snapshot)}catch(e){const o=__PRIVATE_wrapInUserErrorIfRecoverable(e,`Failed to execute query '${i} against cache`);s.reject(o)}}(await __PRIVATE_getLocalStore(e),i,s))),s.promise}(s,e._query).then((s=>new QuerySnapshot(i,o,e,s)))}function getDocsFromServer(e){e=__PRIVATE_cast(e,Query);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(s,e._query,{source:"server"}).then((s=>new QuerySnapshot(i,o,e,s)))}function setDoc(e,i,s){e=__PRIVATE_cast(e,DocumentReference);const o=__PRIVATE_cast(e.firestore,Firestore),_=__PRIVATE_applyFirestoreDataConverter(e.converter,i,s);return executeWrite(o,[__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(o),"setDoc",e._key,_,null!==e.converter,s).toMutation(e._key,Precondition.none())])}function updateDoc(e,i,s,...o){e=__PRIVATE_cast(e,DocumentReference);const _=__PRIVATE_cast(e.firestore,Firestore),h=__PRIVATE_newUserDataReader(_);let d;return d="string"==typeof(i=getModularInstance(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(h,"updateDoc",e._key,i,s,o):__PRIVATE_parseUpdateData(h,"updateDoc",e._key,i),executeWrite(_,[d.toMutation(e._key,Precondition.exists(!0))])}function deleteDoc(e){return executeWrite(__PRIVATE_cast(e.firestore,Firestore),[new __PRIVATE_DeleteMutation(e._key,Precondition.none())])}function addDoc(e,i){const s=__PRIVATE_cast(e.firestore,Firestore),o=doc(e),_=__PRIVATE_applyFirestoreDataConverter(e.converter,i);return executeWrite(s,[__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),"addDoc",o._key,_,null!==e.converter,{}).toMutation(o._key,Precondition.exists(!1))]).then((()=>o))}function onSnapshot(e,...i){var s,o,_;e=getModularInstance(e);let h={includeMetadataChanges:!1,source:"default"},d=0;"object"!=typeof i[d]||__PRIVATE_isPartialObserver(i[d])||(h=i[d],d++);const f={includeMetadataChanges:h.includeMetadataChanges,source:h.source};if(__PRIVATE_isPartialObserver(i[d])){const e=i[d];i[d]=null===(s=e.next)||void 0===s?void 0:s.bind(e),i[d+1]=null===(o=e.error)||void 0===o?void 0:o.bind(e),i[d+2]=null===(_=e.complete)||void 0===_?void 0:_.bind(e)}let g,b,w;if(e instanceof DocumentReference)b=__PRIVATE_cast(e.firestore,Firestore),w=__PRIVATE_newQueryForPath(e._key.path),g={next:s=>{i[d]&&i[d](__PRIVATE_convertToDocSnapshot(b,e,s))},error:i[d+1],complete:i[d+2]};else{const s=__PRIVATE_cast(e,Query);b=__PRIVATE_cast(s.firestore,Firestore),w=s._query;const o=new __PRIVATE_ExpUserDataWriter(b);g={next:e=>{i[d]&&i[d](new QuerySnapshot(b,o,s,e))},error:i[d+1],complete:i[d+2]},__PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query)}return function __PRIVATE_firestoreClientListen(e,i,s,o){const _=new __PRIVATE_AsyncObserver(o),h=new __PRIVATE_QueryListener(i,_,s);return e.asyncQueue.enqueueAndForget((async()=>__PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e),h))),()=>{_.Za(),e.asyncQueue.enqueueAndForget((async()=>__PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e),h)))}}(ensureFirestoreConfigured(b),w,f,g)}function onSnapshotsInSync(e,i){return function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e,i){const s=new __PRIVATE_AsyncObserver(i);return e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_addSnapshotsInSyncListener(e,i){__PRIVATE_debugCast(e).Y_.add(i),i.next()}(await __PRIVATE_getEventManager(e),s))),()=>{s.Za(),e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_removeSnapshotsInSyncListener(e,i){__PRIVATE_debugCast(e).Y_.delete(i)}(await __PRIVATE_getEventManager(e),s)))}}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),__PRIVATE_isPartialObserver(i)?i:{next:i})}function executeWrite(e,i){return function __PRIVATE_firestoreClientWrite(e,i){const s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_syncEngineWrite(e,i,s){const o=__PRIVATE_syncEngineEnsureWriteCallbacks(e);try{const e=await function __PRIVATE_localStoreWriteLocally(e,i){const s=__PRIVATE_debugCast(e),o=Timestamp.now(),_=i.reduce(((e,i)=>e.add(i.key)),__PRIVATE_documentKeySet());let h,d;return s.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let f=__PRIVATE_mutableDocumentMap(),g=__PRIVATE_documentKeySet();return s.cs.getEntries(e,_).next((e=>{f=e,f.forEach(((e,i)=>{i.isValidDocument()||(g=g.add(e))}))})).next((()=>s.localDocuments.getOverlayedDocuments(e,f))).next((_=>{h=_;const d=[];for(const e of i){const i=__PRIVATE_mutationExtractBaseValue(e,h.get(e.key).overlayedDocument);null!=i&&d.push(new __PRIVATE_PatchMutation(e.key,i,__PRIVATE_extractFieldMask(i.value.mapValue),Precondition.exists(!0)))}return s.mutationQueue.addMutationBatch(e,o,d,i)})).next((i=>{d=i;const o=i.applyToLocalDocumentSet(h,g);return s.documentOverlayCache.saveOverlays(e,i.batchId,o)}))})).then((()=>({batchId:d.batchId,changes:__PRIVATE_convertOverlayedDocumentMapToDocumentMap(h)})))}(o.localStore,i);o.sharedClientState.addPendingMutation(e.batchId),function __PRIVATE_addMutationCallback(e,i,s){let o=e.Ba[e.currentUser.toKey()];o||(o=new SortedMap(__PRIVATE_primitiveComparator)),o=o.insert(i,s),e.Ba[e.currentUser.toKey()]=o}(o,e.batchId,s),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(o,e.changes),await __PRIVATE_fillWritePipeline(o.remoteStore)}catch(e){const i=__PRIVATE_wrapInUserErrorIfRecoverable(e,"Failed to persist write");s.reject(i)}}(await __PRIVATE_getSyncEngine(e),i,s))),s.promise}(ensureFirestoreConfigured(e),i)}function __PRIVATE_convertToDocSnapshot(e,i,s){const o=s.docs.get(i._key),_=new __PRIVATE_ExpUserDataWriter(e);return new DocumentSnapshot(e,_,i._key,o,new SnapshotMetadata(s.hasPendingWrites,s.fromCache),i.converter)}function getCountFromServer(e){return getAggregateFromServer(e,{count:count()})}function getAggregateFromServer(e,i){const s=__PRIVATE_cast(e.firestore,Firestore),o=ensureFirestoreConfigured(s),_=__PRIVATE_mapToArray(i,((e,i)=>new __PRIVATE_AggregateImpl(i,e.aggregateType,e._internalFieldPath)));return function __PRIVATE_firestoreClientRunAggregateQuery(e,i,s){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>{try{const _=await __PRIVATE_getDatastore(e);o.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e,i,s){var o;const _=__PRIVATE_debugCast(e),{request:h,ut:d,parent:f}=__PRIVATE_toRunAggregationQueryRequest(_.serializer,__PRIVATE_queryToAggregateTarget(i),s);_.connection.Fo||delete h.parent;const g=(await _.Lo("RunAggregationQuery",_.serializer.databaseId,f,h,1)).filter((e=>!!e.result));__PRIVATE_hardAssert(1===g.length);const b=null===(o=g[0].result)||void 0===o?void 0:o.aggregateFields;return Object.keys(b).reduce(((e,i)=>(e[d[i]]=b[i],e)),{})}(_,i,s))}catch(e){o.reject(e)}})),o.promise}(o,e._query,_).then((i=>function __PRIVATE_convertToAggregateQuerySnapshot(e,i,s){const o=new __PRIVATE_ExpUserDataWriter(e);return new AggregateQuerySnapshot(i,o,s)}(s,e,i)))}class __PRIVATE_MemoryLocalCacheImpl{constructor(e){this.kind="memory",this._onlineComponentProvider=OnlineComponentProvider.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0)}}toJSON(){return{kind:this.kind}}}class __PRIVATE_PersistentLocalCacheImpl{constructor(e){let i;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),i=e.tabManager):(i=persistentSingleTabManager(void 0),i._initialize(e)),this._onlineComponentProvider=i._onlineComponentProvider,this._offlineComponentProvider=i._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class __PRIVATE_MemoryEagerGarbageCollectorImpl{constructor(){this.kind="memoryEager",this._offlineComponentProvider=__PRIVATE_MemoryOfflineComponentProvider.provider}toJSON(){return{kind:this.kind}}}class __PRIVATE_MemoryLruGarbageCollectorImpl{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new __PRIVATE_LruGcMemoryOfflineComponentProvider(e)}}toJSON(){return{kind:this.kind}}}function memoryEagerGarbageCollector(){return new __PRIVATE_MemoryEagerGarbageCollectorImpl}function memoryLruGarbageCollector(e){return new __PRIVATE_MemoryLruGarbageCollectorImpl(null==e?void 0:e.cacheSizeBytes)}function memoryLocalCache(e){return new __PRIVATE_MemoryLocalCacheImpl(e)}function persistentLocalCache(e){return new __PRIVATE_PersistentLocalCacheImpl(e)}class __PRIVATE_SingleTabManagerImpl{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=OnlineComponentProvider.provider,this._offlineComponentProvider={build:i=>new __PRIVATE_IndexedDbOfflineComponentProvider(i,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class __PRIVATE_MultiTabManagerImpl{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=OnlineComponentProvider.provider,this._offlineComponentProvider={build:i=>new __PRIVATE_MultiTabOfflineComponentProvider(i,null==e?void 0:e.cacheSizeBytes)}}}function persistentSingleTabManager(e){return new __PRIVATE_SingleTabManagerImpl(null==e?void 0:e.forceOwnership)}function persistentMultipleTabManager(){return new __PRIVATE_MultiTabManagerImpl}const ht={maxAttempts:5};class WriteBatch{constructor(e,i){this._firestore=e,this._commitHandler=i,this._mutations=[],this._committed=!1,this._dataReader=__PRIVATE_newUserDataReader(e)}set(e,i,s){this._verifyNotCommitted();const o=__PRIVATE_validateReference(e,this._firestore),_=__PRIVATE_applyFirestoreDataConverter(o.converter,i,s),h=__PRIVATE_parseSetData(this._dataReader,"WriteBatch.set",o._key,_,null!==o.converter,s);return this._mutations.push(h.toMutation(o._key,Precondition.none())),this}update(e,i,s,...o){this._verifyNotCommitted();const _=__PRIVATE_validateReference(e,this._firestore);let h;return h="string"==typeof(i=getModularInstance(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"WriteBatch.update",_._key,i,s,o):__PRIVATE_parseUpdateData(this._dataReader,"WriteBatch.update",_._key,i),this._mutations.push(h.toMutation(_._key,Precondition.exists(!0))),this}delete(e){this._verifyNotCommitted();const i=__PRIVATE_validateReference(e,this._firestore);return this._mutations=this._mutations.concat(new __PRIVATE_DeleteMutation(i._key,Precondition.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FirestoreError(_e.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function __PRIVATE_validateReference(e,i){if((e=getModularInstance(e)).firestore!==i)throw new FirestoreError(_e.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class Transaction extends class Transaction$1{constructor(e,i){this._firestore=e,this._transaction=i,this._dataReader=__PRIVATE_newUserDataReader(e)}get(e){const i=__PRIVATE_validateReference(e,this._firestore),s=new __PRIVATE_LiteUserDataWriter(this._firestore);return this._transaction.lookup([i._key]).then((e=>{if(!e||1!==e.length)return fail();const o=e[0];if(o.isFoundDocument())return new DocumentSnapshot$1(this._firestore,s,o.key,o,i.converter);if(o.isNoDocument())return new DocumentSnapshot$1(this._firestore,s,i._key,null,i.converter);throw fail()}))}set(e,i,s){const o=__PRIVATE_validateReference(e,this._firestore),_=__PRIVATE_applyFirestoreDataConverter(o.converter,i,s),h=__PRIVATE_parseSetData(this._dataReader,"Transaction.set",o._key,_,null!==o.converter,s);return this._transaction.set(o._key,h),this}update(e,i,s,...o){const _=__PRIVATE_validateReference(e,this._firestore);let h;return h="string"==typeof(i=getModularInstance(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"Transaction.update",_._key,i,s,o):__PRIVATE_parseUpdateData(this._dataReader,"Transaction.update",_._key,i),this._transaction.update(_._key,h),this}delete(e){const i=__PRIVATE_validateReference(e,this._firestore);return this._transaction.delete(i._key),this}}{constructor(e,i){super(e,i),this._firestore=e}get(e){const i=__PRIVATE_validateReference(e,this._firestore),s=new __PRIVATE_ExpUserDataWriter(this._firestore);return super.get(e).then((e=>new DocumentSnapshot(this._firestore,s,i._key,e._document,new SnapshotMetadata(!1,!1),i.converter)))}}function runTransaction(e,i,s){e=__PRIVATE_cast(e,Firestore);const o=Object.assign(Object.assign({},ht),s);return function __PRIVATE_validateTransactionOptions(e){if(e.maxAttempts<1)throw new FirestoreError(_e.INVALID_ARGUMENT,"Max attempts must be at least 1")}(o),function __PRIVATE_firestoreClientTransaction(e,i,s){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>{const _=await __PRIVATE_getDatastore(e);new __PRIVATE_TransactionRunner(e.asyncQueue,_,s,i,o).au()})),o.promise}(ensureFirestoreConfigured(e),(s=>i(new Transaction(e,s))),o)}function deleteField(){return new __PRIVATE_DeleteFieldValueImpl("deleteField")}function serverTimestamp(){return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp")}function arrayUnion(...e){return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion",e)}function arrayRemove(...e){return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove",e)}function increment(e){return new __PRIVATE_NumericIncrementFieldValueImpl("increment",e)}function vector(e){return new VectorValue(e)}function writeBatch(e){return ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),new WriteBatch(e,(i=>executeWrite(e,i)))}function setIndexConfiguration(e,i){const s=ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore));if(!s._uninitializedComponentsProvider||"memory"===s._uninitializedComponentsProvider._offline.kind)return __PRIVATE_logWarn("Cannot enable indexes when persistence is disabled"),Promise.resolve();const o=function __PRIVATE_parseIndexes(e){const i="string"==typeof e?function __PRIVATE_tryParseJson(e){try{return JSON.parse(e)}catch(e){throw new FirestoreError(_e.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,s=[];if(Array.isArray(i.indexes))for(const e of i.indexes){const i=__PRIVATE_tryGetString(e,"collectionGroup"),o=[];if(Array.isArray(e.fields))for(const i of e.fields){const e=__PRIVATE_fieldPathFromDotSeparatedString("setIndexConfiguration",__PRIVATE_tryGetString(i,"fieldPath"));"CONTAINS"===i.arrayConfig?o.push(new IndexSegment(e,2)):"ASCENDING"===i.order?o.push(new IndexSegment(e,0)):"DESCENDING"===i.order&&o.push(new IndexSegment(e,1))}s.push(new FieldIndex(FieldIndex.UNKNOWN_ID,i,o,IndexState.empty()))}return s}(i);return function __PRIVATE_firestoreClientSetIndexConfiguration(e,i){return e.asyncQueue.enqueue((async()=>async function __PRIVATE_localStoreConfigureFieldIndexes(e,i){const s=__PRIVATE_debugCast(e),o=s.indexManager,_=[];return s.persistence.runTransaction("Configure indexes","readwrite",(e=>o.getFieldIndexes(e).next((s=>function __PRIVATE_diffArrays(e,i,s,o,_){e=[...e],i=[...i],e.sort(s),i.sort(s);const h=e.length,d=i.length;let f=0,g=0;for(;f<d&&g<h;){const h=s(e[g],i[f]);h<0?_(e[g++]):h>0?o(i[f++]):(f++,g++)}for(;f<d;)o(i[f++]);for(;g<h;)_(e[g++])}(s,i,__PRIVATE_fieldIndexSemanticComparator,(i=>{_.push(o.addFieldIndex(e,i))}),(i=>{_.push(o.deleteFieldIndex(e,i))})))).next((()=>PersistencePromise.waitFor(_)))))}(await __PRIVATE_getLocalStore(e),i)))}(s,o)}function __PRIVATE_tryGetString(e,i){if("string"!=typeof e[i])throw new FirestoreError(_e.INVALID_ARGUMENT,"Missing string value for: "+i);return e[i]}class PersistentCacheIndexManager{constructor(e){this._firestore=e,this.type="PersistentCacheIndexManager"}}function getPersistentCacheIndexManager(e){var i;e=__PRIVATE_cast(e,Firestore);const s=dt.get(e);if(s)return s;if("persistent"!==(null===(i=ensureFirestoreConfigured(e)._uninitializedComponentsProvider)||void 0===i?void 0:i._offline.kind))return null;const o=new PersistentCacheIndexManager(e);return dt.set(e,o),o}function enablePersistentCacheIndexAutoCreation(e){__PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e,!0)}function disablePersistentCacheIndexAutoCreation(e){__PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e,!1)}function deleteAllPersistentCacheIndexes(e){(function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e){return e.asyncQueue.enqueue((async()=>function __PRIVATE_localStoreDeleteAllFieldIndexes(e){const i=__PRIVATE_debugCast(e),s=i.indexManager;return i.persistence.runTransaction("Delete All Indexes","readwrite",(e=>s.deleteAllFieldIndexes(e)))}(await __PRIVATE_getLocalStore(e))))})(ensureFirestoreConfigured(e._firestore)).then((e=>__PRIVATE_logDebug("deleting all persistent cache indexes succeeded"))).catch((e=>__PRIVATE_logWarn("deleting all persistent cache indexes failed",e)))}function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e,i){(function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e,i){return e.asyncQueue.enqueue((async()=>function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e,i){__PRIVATE_debugCast(e).ss.zi=i}(await __PRIVATE_getLocalStore(e),i)))})(ensureFirestoreConfigured(e._firestore),i).then((e=>__PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${i} succeeded`))).catch((e=>__PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${i} failed`,e)))}const dt=new WeakMap;function _internalQueryToProtoQueryTarget(e){var i;const s=null===(i=ensureFirestoreConfigured(__PRIVATE_cast(e.firestore,Firestore))._onlineComponents)||void 0===i?void 0:i.datastore.serializer;return void 0===s?null:__PRIVATE_toQueryTarget(s,__PRIVATE_queryToTarget(e._query))._t}function _internalAggregationQueryToProtoRunAggregationQueryRequest(e,i){var s;const o=__PRIVATE_mapToArray(i,((e,i)=>new __PRIVATE_AggregateImpl(i,e.aggregateType,e._internalFieldPath))),_=null===(s=ensureFirestoreConfigured(__PRIVATE_cast(e.firestore,Firestore))._onlineComponents)||void 0===s?void 0:s.datastore.serializer;return void 0===_?null:__PRIVATE_toRunAggregationQueryRequest(_,__PRIVATE_queryToAggregateTarget(e._query),o,!0).request}class TestingHooks{constructor(){throw new Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e)}}class __PRIVATE_TestingHooksSpiImpl{constructor(){this.Uu=new Map}static get instance(){return mt||(mt=new __PRIVATE_TestingHooksSpiImpl,function __PRIVATE_setTestingHooksSpi(e){if(He)throw new Error("a TestingHooksSpi instance is already set");He=e}(mt)),mt}et(e){this.Uu.forEach((i=>i(e)))}onExistenceFilterMismatch(e){const i=Symbol(),s=this.Uu;return s.set(i,e),()=>s.delete(i)}}let mt=null;!function __PRIVATE_registerFirestore(s,o=!0){!function __PRIVATE_setSDKVersion(e){ce=e}(_),e(new Component("firestore",((e,{instanceIdentifier:i,options:s})=>{const _=e.getProvider("app").getImmediate(),h=new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider("auth-internal")),new __PRIVATE_FirebaseAppCheckTokenProvider(e.getProvider("app-check-internal")),function __PRIVATE_databaseIdFromApp(e,i){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new FirestoreError(_e.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new DatabaseId(e.options.projectId,i)}(_,i),_);return s=Object.assign({useFetchStreams:o},s),h._setSettings(s),h}),"PUBLIC").setMultipleInstances(!0)),i(ue,"4.7.4",s),i(ue,"4.7.4","esm2017")}();export{AbstractUserDataWriter,AggregateField,AggregateQuerySnapshot,Bytes,ct as CACHE_SIZE_UNLIMITED,CollectionReference,DocumentReference,DocumentSnapshot,FieldPath,FieldValue,Firestore,FirestoreError,GeoPoint,LoadBundleTask,PersistentCacheIndexManager,Query,QueryCompositeFilterConstraint,QueryConstraint,QueryDocumentSnapshot,QueryEndAtConstraint,QueryFieldFilterConstraint,QueryLimitConstraint,QueryOrderByConstraint,QuerySnapshot,QueryStartAtConstraint,SnapshotMetadata,Timestamp,Transaction,VectorValue,WriteBatch,__PRIVATE_AutoId as _AutoId,ByteString as _ByteString,DatabaseId as _DatabaseId,DocumentKey as _DocumentKey,__PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider,__PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider,FieldPath$1 as _FieldPath,TestingHooks as _TestingHooks,__PRIVATE_cast as _cast,__PRIVATE_debugAssert as _debugAssert,_internalAggregationQueryToProtoRunAggregationQueryRequest,_internalQueryToProtoQueryTarget,__PRIVATE_isBase64Available as _isBase64Available,__PRIVATE_logWarn as _logWarn,__PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether,addDoc,aggregateFieldEqual,aggregateQuerySnapshotEqual,and,arrayRemove,arrayUnion,average,clearIndexedDbPersistence,collection,collectionGroup,connectFirestoreEmulator,count,deleteAllPersistentCacheIndexes,deleteDoc,deleteField,disableNetwork,disablePersistentCacheIndexAutoCreation,doc,documentId,enableIndexedDbPersistence,enableMultiTabIndexedDbPersistence,enableNetwork,enablePersistentCacheIndexAutoCreation,endAt,endBefore,ensureFirestoreConfigured,executeWrite,getAggregateFromServer,getCountFromServer,getDoc,getDocFromCache,getDocFromServer,getDocs,getDocsFromCache,getDocsFromServer,getFirestore,getPersistentCacheIndexManager,increment,initializeFirestore,limit,limitToLast,loadBundle,memoryEagerGarbageCollector,memoryLocalCache,memoryLruGarbageCollector,namedQuery,onSnapshot,onSnapshotsInSync,or,orderBy,persistentLocalCache,persistentMultipleTabManager,persistentSingleTabManager,query,queryEqual,refEqual,runTransaction,serverTimestamp,setDoc,setIndexConfiguration,setLogLevel,snapshotEqual,startAfter,startAt,sum,terminate,updateDoc,vector,waitForPendingWrites,where,writeBatch};
//# sourceMappingURL=firebase-firestore.js.map