12 |
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(Qg,Hg){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(Qg);function n(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let h=0;h<n.length;h+=3){var s=n[h],o=h+1<n.length,a=o?n[h+1]:0,u=h+2<n.length,c=u?n[h+2]:0;let e=(15&a)<<2|c>>6,t=63&c;u||(t=64,o||(e=64)),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,o=e[n++];o<128?t[r++]=String.fromCharCode(o):191<o&&o<224?(i=e[n++],t[r++]=String.fromCharCode((31&o)<<6|63&i)):239<o&&o<365?(s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u<e.length;){var i=n[e.charAt(u++)],s=u<e.length?n[e.charAt(u)]:0;++u;var o=u<e.length?n[e.charAt(u)]:64;++u;var a=u<e.length?n[e.charAt(u)]:64;if(++u,null==i||null==s||null==o||null==a)throw new c;r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a&&r.push(o<<6&192|a))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const a=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const i=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,s=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},o=()=>{try{return i()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||s()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function h(){return!function(){var e=null===(e=o())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class d extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,f.prototype.create)}}class f{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(g,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new d(i,s,n)}}const g=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class p{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}(Qd=l=l||{})[Qd.DEBUG=0]="DEBUG",Qd[Qd.VERBOSE=1]="VERBOSE",Qd[Qd.INFO=2]="INFO",Qd[Qd.WARN=3]="WARN",Qd[Qd.ERROR=4]="ERROR",Qd[Qd.SILENT=5]="SILENT";const y={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},v=l.INFO,w={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},b=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=w[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};var I,E="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},_={},T=E||self;function S(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function x(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var D="closure_uid_"+(1e9*Math.random()>>>0),A=0;function C(e,t,n){return e.call.apply(e.bind,arguments)}function N(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function k(e,t,n){return(k=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?C:N).apply(null,arguments)}function R(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function M(e,s){function t(){}t.prototype=s.prototype,e.$=s.prototype,e.prototype=new t,(e.prototype.constructor=e).ac=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function F(){this.s=this.s,this.o=this.o}F.prototype.s=!1,F.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,D)&&e[D]||(e[D]=++A))},F.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const L=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function O(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function V(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(S(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function P(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}P.prototype.h=function(){this.defaultPrevented=!0};var B=function(){if(!T.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{T.addEventListener("test",()=>{},t),T.removeEventListener("test",()=>{},t)}catch(e){}return e}();function q(e){return/^[\s\xa0]*$/.test(e)}function U(){var e=T.navigator;return(e=e&&e.userAgent)?e:""}function j(e){return-1!=U().indexOf(e)}function G(e){return G[" "](e),e}G[" "]=function(){};var z,$=j("Opera"),K=j("Trident")||j("MSIE"),Q=j("Edge"),H=Q||K,W=j("Gecko")&&!(-1!=U().toLowerCase().indexOf("webkit")&&!j("Edge"))&&!(j("Trident")||j("MSIE"))&&!j("Edge"),X=-1!=U().toLowerCase().indexOf("webkit")&&!j("Edge");function Y(){var e=T.document;return e?e.documentMode:void 0}e:{var J="",Z=(Z=U(),W?/rv:([^\);]+)(\)|;)/.exec(Z):Q?/Edge\/([\d\.]+)/.exec(Z):K?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Z):X?/WebKit\/(\S+)/.exec(Z):$?/(?:Version)[ \/]?(\S+)/.exec(Z):void 0);if(Z&&(J=Z?Z[1]:""),K){Z=Y();if(null!=Z&&Z>parseFloat(J)){z=String(Z);break e}}z=J}var ee=T.document&&K&&(Y()||parseInt(z,10))||void 0;function te(e,t){if(P.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(W){e:{try{G(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:ne[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&te.$.h.call(this)}}M(te,P);var ne={2:"touch",3:"pen",4:"mouse"};te.prototype.h=function(){te.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var re="closure_listenable_"+(1e6*Math.random()|0),ie=0;function se(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++ie,this.fa=this.ia=!1}function oe(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function ae(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function ue(e){const t={};for(const n in e)t[n]=e[n];return t}const ce="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function he(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<ce.length;e++)n=ce[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function le(e){this.src=e,this.g={},this.h=0}function de(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=L(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(oe(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function fe(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}le.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=fe(e,t,r,i);return-1<o?(t=e[o],n||(t.ia=!1)):((t=new se(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var ge="closure_lm_"+(1e6*Math.random()|0),me={};function pe(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);return null}r=_e(r);return t&&t[re]?t.P(n,r,x(i)?!!i.capture:!!i,s):ye(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)pe(e,t[s],n,r,i);return null}return n=_e(n),e&&e[re]?e.O(t,n,x(r)?!!r.capture:!!r,i):ye(e,t,n,!1,r,i)}function ye(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o=x(i)?!!i.capture:!!i,a=Ie(e);if(a||(e[ge]=a=new le(e)),(n=a.add(t,n,r,o,s)).proxy)return n;if(r=function(){const n=be;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!B?o:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(we(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function ve(e){var t,n,r;"number"!=typeof e&&e&&!e.fa&&((t=e.src)&&t[re]?de(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(we(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Ie(t))?(de(n,e),0==n.h&&(n.src=null,t[ge]=null)):oe(e)))}function we(e){return e in me?me[e]:me[e]="on"+e}function be(e,t){var n,r;return e=!!e.fa||(t=new te(t,this),n=e.listener,r=e.la||e.src,e.ia&&ve(e),n.call(r,t))}function Ie(e){return(e=e[ge])instanceof le?e:null}var Ee="__closure_events_fn_"+(1e9*Math.random()>>>0);function _e(t){return"function"==typeof t?t:(t[Ee]||(t[Ee]=function(e){return t.handleEvent(e)}),t[Ee])}function Te(){F.call(this),this.i=new le(this),(this.S=this).J=null}function Se(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t?t=new P(t,e):t instanceof P?t.target=t.target||e:(o=t,he(t=new P(r,e),o)),o=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],o=xe(s,r,!0,t)&&o;if(o=xe(s=t.g=e,r,!0,t)&&o,o=xe(s,r,!1,t)&&o,n)for(i=0;i<n.length;i++)o=xe(s=t.g=n[i],r,!1,t)&&o}function xe(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o,a,u=t[s];u&&!u.fa&&u.capture==n&&(o=u.listener,a=u.la||u.src,u.ia&&de(e.i,u),i=!1!==o.call(a,r)&&i)}return i&&!r.defaultPrevented}M(Te,F),Te.prototype[re]=!0,Te.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);else i=x(i)?!!i.capture:!!i,r=_e(r),t&&t[re]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=fe(o=t.g[n],r,i,s))&&(oe(o[r]),Array.prototype.splice.call(o,r,1),0==o.length&&(delete t.g[n],t.h--))):(t=t&&Ie(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?fe(n,r,i,s):t)?n[t]:null)&&ve(r))}(this,e,t,n,r)},Te.prototype.N=function(){if(Te.$.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)oe(n[r]);delete t.g[e],t.h--}}this.J=null},Te.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Te.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var De=T.JSON.stringify;var Ae=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new Ce,e=>e.reset());class Ce{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let Ne,ke=!1,Re=new class{constructor(){this.h=this.g=null}add(e,t){const n=Ae.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Me=()=>{const e=T.Promise.resolve(void 0);Ne=()=>{e.then(Fe)}};var Fe=()=>{for(var e;e=function(){var e=Re;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){T.setTimeout(()=>{throw e},0)}(e)}var t=Ae;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}ke=!1};function Le(e,t){Te.call(this),this.h=e||1,this.g=t||T,this.j=k(this.qb,this),this.l=Date.now()}function Oe(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Ve(e,t,n){if("function"==typeof e)n&&(e=k(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=k(e.handleEvent,e)}return 2147483647<Number(t)?-1:T.setTimeout(e,t||0)}M(Le,Te),(I=Le.prototype).ga=!1,I.T=null,I.qb=function(){var e;this.ga&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),Se(this,"tick"),this.ga&&(Oe(this),this.start())))},I.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},I.N=function(){Le.$.N.call(this),Oe(this),delete this.g};class Pe extends F{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Ve(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}N(){super.N(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Be(e){F.call(this),this.h=e,this.g={}}M(Be,F);var qe=[];function Ue(e,t,n,r){Array.isArray(n)||(n&&(qe[0]=n.toString()),n=qe);for(var i=0;i<n.length;i++){var s=pe(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function je(e){ae(e.g,function(e,t){this.g.hasOwnProperty(t)&&ve(e)},e),e.g={}}function Ge(){this.g=!0}function ze(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return De(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Be.prototype.N=function(){Be.$.N.call(this),je(this)},Be.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},Ge.prototype.Ea=function(){this.g=!1},Ge.prototype.info=function(){};var $e={},Ke=null;function Qe(){return Ke=Ke||new Te}function He(e){P.call(this,$e.Ta,e)}function We(){var e=Qe();Se(e,new He(e))}function Xe(e,t){P.call(this,$e.STAT_EVENT,e),this.stat=t}function Ye(e){var t=Qe();Se(t,new Xe(t,e))}function Je(e,t){P.call(this,$e.Ua,e),this.size=t}function Ze(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return T.setTimeout(function(){e()},t)}$e.Ta="serverreachability",M(He,P),$e.STAT_EVENT="statevent",M(Xe,P),$e.Ua="timingevent",M(Je,P);var et={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},tt={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function nt(){}function rt(e){return e.h||(e.h=e.i())}function it(){}nt.prototype.h=null;E={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function st(){P.call(this,"d")}function ot(){P.call(this,"c")}function at(){}function ut(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new Be(this),this.P=lt,this.V=new Le(e=H?125:void 0),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new ct}function ct(){this.i=null,this.g="",this.h=!1}M(st,P),M(ot,P),M(at,nt),at.prototype.g=function(){return new XMLHttpRequest},at.prototype.i=function(){return{}};var ht=new at,lt=45e3,dt={},ft={};function gt(e,t,n){e.L=1,e.v=Rt(Dt(t)),e.s=n,e.S=!0,mt(e,null)}function mt(e,t){e.G=Date.now(),vt(e),e.A=Dt(e.v);var o,a,u,c,h,l,n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),$t(n.i,"t",r),e.C=0,n=e.l.J,e.h=new ct,e.g=$n(e.l,n?t:null,!e.s),0<e.O&&(e.M=new Pe(k(e.Pa,e,e.g),e.O)),Ue(e.U,e.g,"readystatechange",e.nb),t=e.I?ue(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),We(),o=e.j,a=e.u,u=e.A,c=e.m,h=e.W,l=e.s,o.info(function(){if(o.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+h+"]: "+a+"\n"+u+"\n"+e})}function pt(e){return e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function yt(e,t,n){let r=!0,i;for(;!e.J&&e.C<n.length;){if(i=(o=n,u=a=void 0,a=(s=e).C,-1==(u=o.indexOf("\n",a))?ft:(a=Number(o.substring(a,u)),isNaN(a)?dt:(u+=1)+a>o.length?ft:(o=o.slice(u,u+a),s.C=u+a,o))),i==ft){4==t&&(e.o=4,Ye(14),r=!1),ze(e.j,e.m,null,"[Incomplete Response]");break}if(i==dt){e.o=4,Ye(15),ze(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}ze(e.j,e.m,i,null),_t(e,i)}var s,o,a,u;pt(e)&&i!=ft&&i!=dt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,Ye(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),Vn(t),t.M=!0,Ye(11))):(ze(e.j,e.m,n,"[Invalid Chunked Response]"),Et(e),It(e))}function vt(e){e.Y=Date.now()+e.P,wt(e,e.P)}function wt(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Ze(k(e.lb,e),t)}function bt(e){e.B&&(T.clearTimeout(e.B),e.B=null)}function It(e){0==e.l.H||e.J||qn(e.l,e)}function Et(e){bt(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,Oe(e.V),je(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function _t(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Yt(n.i,e)))if(!e.K&&Yt(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;Bn(n),Cn(n)}On(n),Ye(18)}}else n.Fa=i[1],0<n.Fa-n.V&&i[2]<37500&&n.G&&0==n.A&&!n.v&&(n.v=Ze(k(n.ib,n),6e3));if(Xt(n.i)<=1&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else jn(n,11)}else if(!e.K&&n.g!=e||Bn(n),!q(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.V=s[0],s=s[1],2==n.H)if("c"==s[0]){n.K=s[1],n.pa=s[2];var o=s[3];null!=o&&(n.ra=o,n.l.info("VER="+n.ra));var a=s[4];null!=a&&(n.Ga=a,n.l.info("SVER="+n.Ga));var u,c,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;if(g){const m=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null;m&&((u=r.i).g||-1==m.indexOf("spdy")&&-1==m.indexOf("quic")&&-1==m.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(Jt(u,u.h),u.h=null))),!r.F||(c=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.Da=c,kt(r.I,r.F,c))}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var l,d,f=e;(r=n).wa=zn(r,r.J?r.pa:null,r.Y),f.K?(Zt(r.i,f),l=f,(d=r.L)&&l.setTimeout(d),l.B&&(bt(l),vt(l)),r.g=f):Ln(r),0<n.j.length&&kn(n)}else"stop"!=s[0]&&"close"!=s[0]||jn(n,7);else 3==n.H&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?jn(n,7):An(n):"noop"!=s[0]&&n.h&&n.h.Aa(s),n.A=0)}We()}catch(e){}}function Tt(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(S(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(S(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();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(S(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(I=ut.prototype).setTimeout=function(e){this.P=e},I.nb=function(e){e=e.target;const t=this.M;t&&3==En(e)?t.l():this.Pa(e)},I.Pa=function(e){try{if(e==this.g)e:{var t=En(this.g),n=this.g.Ia();this.g.da();if(!(t<3)&&(3!=t||H||this.g&&(this.h.h||this.g.ja()||_n(this.g)))){this.J||4!=t||7==n||We(),bt(this);var r=this.g.da();this.ca=r;t:if(pt(this)){var i=_n(this.g);e="";var s=i.length,o=4==En(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Et(this),It(this);var a="";break t}this.h.i=new T.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:o&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.ja();if(this.i=200==r,l=this.j,d=this.u,f=this.A,g=this.m,m=this.W,p=t,y=r,l.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+m+"]: "+d+"\n"+f+"\n"+p+" "+y}),this.i){if(this.aa&&!this.K){t:{if(this.g){var u,c=this.g;if((u=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!q(u)){var h=u;break t}}h=null}if(!(r=h)){this.i=!1,this.o=3,Ye(12),Et(this),It(this);break e}ze(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,_t(this,r)}this.S?(yt(this,t,a),H&&this.i&&3==t&&(Ue(this.U,this.V,"tick",this.mb),this.V.start())):(ze(this.j,this.m,a,null),_t(this,a)),4==t&&Et(this),this.i&&!this.J&&(4==t?qn(this.l,this):(this.i=!1,vt(this)))}else(function(e){const t={};e=(e.g&&2<=En(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!q(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<a.indexOf("Unknown SID")?(this.o=3,Ye(12)):(this.o=0,Ye(13)),Et(this),It(this)}}}catch(e){}var l,d,f,g,m,p,y},I.mb=function(){var e,t;this.g&&(e=En(this.g),t=this.g.ja(),this.C<t.length&&(bt(this),yt(this,e,t),this.i&&4!=e&&vt(this)))},I.cancel=function(){this.J=!0,Et(this)},I.lb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(We(),Ye(17)),Et(this),this.o=2,It(this)):wt(this,this.Y-n)};var St=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function xt(e){var t,n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof xt?(this.h=e.h,At(this,e.j),this.s=e.s,this.g=e.g,Ct(this,e.m),this.l=e.l,t=e.i,(n=new Ut).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Nt(this,n),this.o=e.o):e&&(t=String(e).match(St))?(this.h=!1,At(this,t[1]||"",!0),this.s=Mt(t[2]||""),this.g=Mt(t[3]||"",!0),Ct(this,t[4]),this.l=Mt(t[5]||"",!0),Nt(this,t[6]||"",!0),this.o=Mt(t[7]||"")):(this.h=!1,this.i=new Ut(null,this.h))}function Dt(e){return new xt(e)}function At(e,t,n){e.j=n?Mt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Ct(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Nt(e,t,n){var r,i;t instanceof Ut?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(jt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Gt(this,t),$t(this,n,e))},r)),r.j=i):(n||(t=Ft(t,Bt)),e.i=new Ut(t,e.h))}function kt(e,t,n){e.i.set(t,n)}function Rt(e){return kt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Mt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Ft(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Lt),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Lt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}xt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Ft(t,Ot,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Ft(t,Ot,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Ft(n,"/"==n.charAt(0)?Pt:Vt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Ft(n,qt)),e.join("")};var Ot=/[#\/\?@]/g,Vt=/[#\?:]/g,Pt=/[#\?]/g,Bt=/[#\?@]/g,qt=/#/g;function Ut(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function jt(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Gt(e,t){jt(e),t=Kt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function zt(e,t){return jt(e),t=Kt(e,t),e.g.has(t)}function $t(e,t,n){Gt(e,t),0<n.length&&(e.i=null,e.g.set(Kt(e,t),O(n)),e.h+=n.length)}function Kt(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(I=Ut.prototype).add=function(e,t){jt(this),this.i=null,e=Kt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},I.forEach=function(n,r){jt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},I.ta=function(){jt(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},I.Z=function(t){jt(this);let n=[];if("string"==typeof t)zt(this,t)&&(n=n.concat(this.g.get(Kt(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},I.set=function(e,t){return jt(this),this.i=null,zt(this,e=Kt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},I.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},I.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.Z(r),r=0;r<s.length;r++){var o=i;""!==s[r]&&(o+="="+encodeURIComponent(String(s[r]))),e.push(o)}return this.i=e.join("&")};var Qt=class{constructor(e,t){this.g=e,this.map=t}};function Ht(e){this.l=e||10,e=T.PerformanceNavigationTiming?0<(e=T.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(T.g&&T.g.Ka&&T.g.Ka()&&T.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Wt(e){return e.h||e.g&&e.g.size>=e.j}function Xt(e){return e.h?1:e.g?e.g.size:0}function Yt(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Jt(e,t){e.g?e.g.add(t):e.h=t}function Zt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function en(t){if(null!=t.h)return t.i.concat(t.h.F);if(null==t.g||0===t.g.size)return O(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.F);return e}}Ht.prototype.cancel=function(){if(this.i=en(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 tn,nn=class{stringify(e){return T.JSON.stringify(e,void 0)}parse(e){return T.JSON.parse(e,void 0)}};function rn(){this.g=new nn}function sn(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function on(e){this.l=e.fc||null,this.j=e.ob||!1}function an(e,t){Te.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=un,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}M(on,nt),on.prototype.g=function(){return new an(this.l,this.j)},on.prototype.i=(tn={},function(){return tn}),M(an,Te);var un=0;function cn(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function hn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ln(e)}function ln(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(I=an.prototype).open=function(e,t){if(this.readyState!=un)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ln(this)},I.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||T).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},I.abort=function(){this.response=this.responseText="",this.v=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,hn(this)),this.readyState=un},I.$a=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,ln(this)),this.g&&(this.readyState=3,ln(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(void 0!==T.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;cn(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},I.Xa=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?hn:ln)(this),3==this.readyState&&cn(this))},I.Za=function(e){this.g&&(this.response=this.responseText=e,hn(this))},I.Ya=function(e){this.g&&(this.response=e,hn(this))},I.ka=function(){this.g&&hn(this)},I.setRequestHeader=function(e,t){this.v.append(e,t)},I.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},I.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(an.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var dn=T.JSON.parse;function fn(e){Te.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=gn,this.L=this.M=!1}M(fn,Te);var gn="",mn=/^https?$/i,pn=["POST","PUT"];function yn(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,vn(e),bn(e)}function vn(e){e.F||(e.F=!0,Se(e,"complete"),Se(e,"error"))}function wn(e){if(e.h&&void 0!==_&&(!e.C[1]||4!=En(e)||2!=e.da()))if(e.v&&4==En(e))Ve(e.La,0,e);else if(Se(e,"readystatechange"),4==En(e)){e.h=!1;try{var t,n,r,i=e.da();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.I).match(St)[1]||null)&&T.self&&T.self.location&&(r=T.self.location.protocol.slice(0,-1)),n=!mn.test(r?r.toLowerCase():"")),t=n),t)Se(e,"complete"),Se(e,"success");else{e.m=6;try{var o=2<En(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.da()+"]",vn(e)}}finally{bn(e)}}}function bn(e,t){if(e.g){In(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||Se(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function In(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(T.clearTimeout(e.A),e.A=null)}function En(e){return e.g?e.g.readyState:0}function _n(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case gn:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Tn(e){let n="";return ae(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Sn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Tn(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):kt(e,t,n))}function xn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Dn(e){this.Ga=0,this.j=[],this.l=new Ge,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=xn("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=xn("baseRetryDelayMs",5e3,e),this.hb=xn("retryDelaySeedMs",1e4,e),this.eb=xn("forwardChannelMaxRetries",2,e),this.xa=xn("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Ht(e&&e.concurrentRequestLimit),this.Ja=new rn,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function An(e){if(Nn(e),3==e.H){var t=e.W++,n=Dt(e.I);if(kt(n,"SID",e.K),kt(n,"RID",t),kt(n,"TYPE","terminate"),Mn(e,n),(t=new ut(e,e.l,t)).L=2,t.v=Rt(Dt(n)),n=!1,T.navigator&&T.navigator.sendBeacon)try{n=T.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&T.Image&&((new Image).src=t.v,n=!0),n||(t.g=$n(t.l,null),t.g.ha(t.v)),t.G=Date.now(),vt(t)}Gn(e)}function Cn(e){e.g&&(Vn(e),e.g.cancel(),e.g=null)}function Nn(e){Cn(e),e.u&&(T.clearTimeout(e.u),e.u=null),Bn(e),e.i.cancel(),e.m&&("number"==typeof e.m&&T.clearTimeout(e.m),e.m=null)}function kn(e){var t;Wt(e.i)||e.m||(e.m=!0,t=e.Na,Ne||Me(),ke||(Ne(),ke=!0),Re.add(t,e),e.C=0)}function Rn(e,t){var n=t?t.m:e.W++,r=Dt(e.I);kt(r,"SID",e.K),kt(r,"RID",n),kt(r,"AID",e.V),Mn(e,r),e.o&&e.s&&Sn(r,e.o,e.s),n=new ut(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=Fn(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),Jt(e.i,n),gt(n,r,t)}function Mn(e,n){e.na&&ae(e.na,function(e,t){kt(n,t,e)}),e.h&&Tt({},function(e,t){kt(n,t,e)})}function Fn(e,t,r){r=Math.min(e.j.length,r);var i=e.h?k(e.h.Va,e.h,e):null;e:{var s=e.j;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=s[0].g,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var o=s[t].g,a=s[t].map;if((o-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Tt(e,function(e,t){let n=e;x(e)&&(n=De(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(a,u,"req"+o+"_")}catch(e){i&&i(a)}}if(e){i=u.join("&");break e}}}return e=e.j.splice(0,r),t.F=e,i}function Ln(e){var t;e.g||e.u||(e.ba=1,t=e.Ma,Ne||Me(),ke||(Ne(),ke=!0),Re.add(t,e),e.A=0)}function On(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=Ze(k(e.Ma,e),Un(e,e.A)),e.A++,1)}function Vn(e){null!=e.B&&(T.clearTimeout(e.B),e.B=null)}function Pn(e){e.g=new ut(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=Dt(e.wa);kt(t,"RID","rpc"),kt(t,"SID",e.K),kt(t,"AID",e.V),kt(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&kt(t,"TO",e.qa),kt(t,"TYPE","xmlhttp"),Mn(e,t),e.o&&e.s&&Sn(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Rt(Dt(t)),n.s=null,n.S=!0,mt(n,e)}function Bn(e){null!=e.v&&(T.clearTimeout(e.v),e.v=null)}function qn(e,t){var n,r,i,s=null;if(e.g==t){Bn(e),Vn(e),e.g=null;var o=2}else{if(!Yt(e.i,t))return;s=t.F,Zt(e.i,t),o=1}if(0!=e.H)if(t.i)1==o?(s=t.s?t.s.length:0,t=Date.now()-t.G,n=e.C,Se(o=Qe(),new Je(o,s)),kn(e)):Ln(e);else if(3==(n=t.o)||0==n&&0<t.ca||(1!=o||(i=t,Xt((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.j=i.F.concat(r.j),0):1==r.H||2==r.H||r.C>=(r.cb?0:r.eb)||(r.m=Ze(k(r.Na,r,i),Un(r,r.C)),r.C++,0))))&&(2!=o||!On(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:jn(e,5);break;case 4:jn(e,10);break;case 3:jn(e,6);break;default:jn(e,2)}}function Un(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function jn(e,t){var n,r;e.l.info("Error code "+t),2==t?(n=null,e.h&&(n=null),r=k(e.pb,e),n||(n=new xt("//www.google.com/images/cleardot.gif"),T.location&&"http"==T.location.protocol||At(n,"https"),Rt(n)),function(e,t){var n=new Ge;if(T.Image){const r=new Image;r.onload=R(sn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=R(sn,n,r,"TestLoadImage: error",!1,t),r.onabort=R(sn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=R(sn,n,r,"TestLoadImage: timeout",!1,t),T.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):Ye(2),e.H=0,e.h&&e.h.za(t),Gn(e),Nn(e)}function Gn(e){var t;e.H=0,e.ma=[],e.h&&(0==(t=en(e.i)).length&&0==e.j.length||(V(e.ma,t),V(e.ma,e.j),e.i.i.length=0,O(e.j),e.j.length=0),e.h.ya())}function zn(e,t,n){var r,i,s=n instanceof xt?Dt(n):new xt(n);return""!=s.g?(t&&(s.g=t+"."+s.g),Ct(s,s.m)):(s=(r=T.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new xt(null),s&&At(i,s),t&&(i.g=t),r&&Ct(i,r),n&&(i.l=n),s=i),n=e.F,t=e.Da,n&&t&&kt(s,n,t),kt(s,"VER",e.ra),Mn(e,s),s}function $n(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new fn(new on({ob:!0})):new fn(e.va)).Oa(e.J),t}function Kn(){}function Qn(){if(K&&!(10<=Number(ee)))throw Error("Environmental error: no available transport.")}function Hn(e,t){Te.call(this),this.g=new Dn(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!q(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!q(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Yn(this)}function Wn(e){st.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function Xn(){ot.call(this),this.status=1}function Yn(e){this.g=e}function Jn(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function Zn(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],o=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((o=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|o>>>10))+((o=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|o>>>12))+((o=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|o>>>9))+((o=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|o>>>11))+((s=(t=n+((o=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|o>>>22))^((i=s+((o=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|o>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(o<<21&4294967295|o>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function er(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(I=fn.prototype).Oa=function(e){this.M=e},I.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=(this.u||ht).g(),this.C=this.u?rt(this.u):rt(ht),this.g.onreadystatechange=k(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void yn(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const u of r.keys())n.set(u,r.get(u))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=T.FormData&&e instanceof T.FormData,0<=L(pn,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,o]of n)this.g.setRequestHeader(s,o);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{In(this),0<this.B&&((this.L=(a=this.g,K&&"number"==typeof a.timeout&&void 0!==a.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=k(this.ua,this)):this.A=Ve(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){yn(this,e)}var a},I.ua=function(){void 0!==_&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Se(this,"timeout"),this.abort(8))},I.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Se(this,"complete"),Se(this,"abort"),bn(this))},I.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),bn(this,!0)),fn.$.N.call(this)},I.La=function(){this.s||(this.G||this.v||this.l?wn(this):this.kb())},I.kb=function(){wn(this)},I.isActive=function(){return!!this.g},I.da=function(){try{return 2<En(this)?this.g.status:-1}catch(e){return-1}},I.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},I.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),dn(t)}},I.Ia=function(){return this.m},I.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(I=Dn.prototype).ra=8,I.H=1,I.Na=function(t){if(this.m)if(this.m=null,1==this.H){if(!t){this.W=Math.floor(1e5*Math.random()),t=this.W++;const s=new ut(this,this.l,t);let e=this.s;if(this.U&&(e?(e=ue(e),he(e,this.U)):e=this.U),null!==this.o||this.O||(s.I=e,e=null),this.P)e:{for(var n=0,r=0;r<this.j.length;r++){var i=this.j[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.j.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Fn(this,s,n),kt(r=Dt(this.I),"RID",t),kt(r,"CVER",22),this.F&&kt(r,"X-HTTP-Session-Id",this.F),Mn(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(Tn(e)))+"&"+n:this.o&&Sn(r,this.o,e)),Jt(this.i,s),this.bb&&kt(r,"TYPE","init"),this.P?(kt(r,"$req",n),kt(r,"SID","null"),s.aa=!0,gt(s,r,null)):gt(s,r,n),this.H=2}}else 3==this.H&&(t?Rn(this,t):0==this.j.length||Wt(this.i)||Rn(this))},I.Ma=function(){var e;this.u=null,Pn(this),this.ca&&!(this.M||null==this.g||this.S<=0)&&(e=2*this.S,this.l.info("BP detection timer enabled: "+e),this.B=Ze(k(this.jb,this),e))},I.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,Ye(10),Cn(this),Pn(this))},I.ib=function(){null!=this.v&&(this.v=null,Cn(this),On(this),Ye(19))},I.pb=function(e){e?(this.l.info("Successfully pinged google.com"),Ye(2)):(this.l.info("Failed to ping google.com"),Ye(1))},I.isActive=function(){return!!this.h&&this.h.isActive(this)},(I=Kn.prototype).Ba=function(){},I.Aa=function(){},I.za=function(){},I.ya=function(){},I.isActive=function(){return!0},I.Va=function(){},Qn.prototype.g=function(e,t){return new Hn(e,t)},M(Hn,Te),Hn.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;Ye(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=zn(e,null,e.Y),kn(e)},Hn.prototype.close=function(){An(this.g)},Hn.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=De(e),e=t),n.j.push(new Qt(n.fb++,e)),3==n.H&&kn(n)},Hn.prototype.N=function(){this.g.h=null,delete this.j,An(this.g),delete this.g,Hn.$.N.call(this)},M(Wn,st),M(Xn,ot),M(Yn,Kn),Yn.prototype.Ba=function(){Se(this.g,"a")},Yn.prototype.Aa=function(e){Se(this.g,new Wn(e))},Yn.prototype.za=function(e){Se(this.g,new Xn)},Yn.prototype.ya=function(){Se(this.g,"b")},M(Jn,function(){this.blockSize=-1}),Jn.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Jn.prototype.j=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)Zn(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){Zn(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){Zn(this,r),i=0;break}}this.h=i,this.i+=t},Jn.prototype.l=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.i,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var tr={};function nr(e){return-128<=e&&e<128?(t=e,n=function(e){return new er([0|e],e<0?-1:0)},r=tr,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new er([0|e],e<0?-1:0);var t,n,r}function rr(e){if(isNaN(e)||!isFinite(e))return sr;if(e<0)return hr(rr(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=ir;return new er(t,0)}var ir=4294967296,sr=nr(0),or=nr(1),ar=nr(16777216);function ur(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function cr(e){return-1==e.h}function hr(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new er(n,~e.h).add(or)}function lr(e,t){return e.add(hr(t))}function dr(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function fr(e,t){this.g=e,this.h=t}function gr(e,t){if(ur(t))throw Error("division by zero");if(ur(e))return new fr(sr,sr);if(cr(e))return t=gr(hr(e),t),new fr(hr(t.g),hr(t.h));if(cr(t))return t=gr(e,hr(t)),new fr(hr(t.g),t.h);if(30<e.g.length){if(cr(e)||cr(t))throw Error("slowDivide_ only works with positive integers.");for(var n=or,r=t;r.X(e)<=0;)n=mr(n),r=mr(r);for(var i=pr(n,1),s=pr(r,1),r=pr(r,2),n=pr(n,2);!ur(r);){var o=s.add(r);o.X(e)<=0&&(i=i.add(n),s=o),r=pr(r,1),n=pr(n,1)}return t=lr(e,i.R(t)),new fr(i,t)}for(i=sr;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),o=(s=rr(n)).R(t);cr(o)||0<o.X(e);)o=(s=rr(n-=r)).R(t);ur(s)&&(s=or),i=i.add(s),e=lr(e,o)}return new fr(i,e)}function mr(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new er(n,e.h)}function pr(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new er(i,e.h)}(I=er.prototype).ea=function(){if(cr(this))return-hr(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:ir+r)*t,t*=ir}return e},I.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(ur(this))return"0";if(cr(this))return"-"+hr(this).toString(e);for(var t=rr(Math.pow(e,6)),n=this,r="";;){var i=gr(n,t).g,s=((0<(n=lr(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(ur(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},I.D=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},I.X=function(e){return cr(e=lr(this,e))?-1:ur(e)?0:1},I.abs=function(){return cr(this)?hr(this):this},I.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),o=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16),r=o>>>16;s&=65535,o&=65535,n[i]=o<<16|s}return new er(n,-2147483648&n[n.length-1]?-1:0)},I.R=function(e){if(ur(this)||ur(e))return sr;if(cr(this))return cr(e)?hr(this).R(hr(e)):hr(hr(this).R(e));if(cr(e))return hr(this.R(hr(e)));if(this.X(ar)<0&&e.X(ar)<0)return rr(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,o=65535&this.D(r),a=e.D(i)>>>16,u=65535&e.D(i);n[2*r+2*i]+=o*u,dr(n,2*r+2*i),n[2*r+2*i+1]+=s*u,dr(n,2*r+2*i+1),n[2*r+2*i+1]+=o*a,dr(n,2*r+2*i+1),n[2*r+2*i+2]+=s*a,dr(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new er(n,0)},I.gb=function(e){return gr(this,e).h},I.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new er(n,this.h&e.h)},I.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new er(n,this.h|e.h)},I.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new er(n,this.h^e.h)},Qn.prototype.createWebChannel=Qn.prototype.g,Hn.prototype.send=Hn.prototype.u,Hn.prototype.open=Hn.prototype.m,et.NO_ERROR=0,et.TIMEOUT=8,et.HTTP_ERROR=6,tt.COMPLETE="complete",(it.EventType=E).OPEN="a",E.CLOSE="b",E.ERROR="c",E.MESSAGE="d",Te.prototype.listen=Te.prototype.O,fn.prototype.listenOnce=fn.prototype.P,fn.prototype.getLastError=fn.prototype.Sa,fn.prototype.getLastErrorCode=fn.prototype.Ia,fn.prototype.getStatus=fn.prototype.da,fn.prototype.getResponseJson=fn.prototype.Wa,fn.prototype.getResponseText=fn.prototype.ja,fn.prototype.send=fn.prototype.ha,fn.prototype.setWithCredentials=fn.prototype.Oa,Jn.prototype.digest=Jn.prototype.l,Jn.prototype.update=Jn.prototype.j,er.prototype.multiply=er.prototype.R,er.prototype.modulo=er.prototype.gb,er.prototype.compare=er.prototype.X,er.prototype.toNumber=er.prototype.ea,er.prototype.getBits=er.prototype.D,er.fromNumber=rr,er.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return hr(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=rr(Math.pow(n,8)),i=sr,s=0;s<t.length;s+=8)var o=Math.min(8,t.length-s),a=parseInt(t.substring(s,s+o),n),i=o<8?(o=rr(Math.pow(n,o)),i.R(o).add(rr(a))):(i=i.R(r)).add(rr(a));return i};var yr,vr=Qe,wr=et,br=tt,Ir=$e,Er=10,_r=11,Tr=on,Sr=it,xr=fn,Dr=Jn,Ar=er;const Cr="@firebase/firestore";class Nr{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}}Nr.UNAUTHENTICATED=new Nr(null),Nr.GOOGLE_CREDENTIALS=new Nr("google-credentials-uid"),Nr.FIRST_PARTY=new Nr("first-party-uid"),Nr.MOCK_USER=new Nr("mock-user");let kr="9.23.0";const Rr=new class{constructor(e){this.name=e,this._logLevel=v,this._logHandler=b,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in l))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?y[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,l.DEBUG,...e),this._logHandler(this,l.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,l.VERBOSE,...e),this._logHandler(this,l.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,l.INFO,...e),this._logHandler(this,l.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,l.WARN,...e),this._logHandler(this,l.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,l.ERROR,...e),this._logHandler(this,l.ERROR,...e)}}("@firebase/firestore");function Mr(){return Rr.logLevel}function Fr(e,...t){var n;Rr.logLevel<=l.DEBUG&&(n=t.map(Vr),Rr.debug(`Firestore (${kr}): ${e}`,...n))}function Lr(e,...t){var n;Rr.logLevel<=l.ERROR&&(n=t.map(Vr),Rr.error(`Firestore (${kr}): ${e}`,...n))}function Or(e,...t){var n;Rr.logLevel<=l.WARN&&(n=t.map(Vr),Rr.warn(`Firestore (${kr}): ${e}`,...n))}function Vr(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Pr(e="Unexpected state"){var t=`FIRESTORE (${kr}) INTERNAL ASSERTION FAILED: `+e;throw Lr(t),new Error(t)}function Br(e){e||Pr()}const qr={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 Ur extends d{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class jr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class Gr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class zr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Nr.UNAUTHENTICATED))}shutdown(){}}class $r{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Kr{constructor(e){this.t=e,this.currentUser=Nr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new jr;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new jr,t.enqueueRetryable(()=>i(this.currentUser))};const o=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},a=e=>{Fr("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),o()};this.t.onInit(e=>a(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?a(e):(Fr("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new jr))},0),o()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(Fr("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Br("string"==typeof e.accessToken),new Gr(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Br(null===e||"string"==typeof e),new Nr(e)}}class Qr{constructor(e,t,n){this.h=e,this.l=t,this.m=n,this.type="FirstParty",this.user=Nr.FIRST_PARTY,this.g=new Map}p(){return this.m?this.m():null}get headers(){this.g.set("X-Goog-AuthUser",this.h);var e=this.p();return e&&this.g.set("Authorization",e),this.l&&this.g.set("X-Goog-Iam-Authorization-Token",this.l),this.g}}class Hr{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Qr(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(Nr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Wr{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class Xr{constructor(e){this.I=e,this.forceRefresh=!1,this.appCheck=null,this.T=null}start(t,n){const r=e=>{null!=e.error&&Fr("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.T;return this.T=e.token,Fr("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{Fr("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.I.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.I.getImmediate({optional:!0}))?i(e):Fr("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Br("string"==typeof e.token),this.T=e.token,new Wr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Yr{static A(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Jr(e,t){return e<t?-1:t<e?1:0}function Zr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function ei(e){return e+"\0"}class ti{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new Ur(qr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new Ur(qr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new Ur(qr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new Ur(qr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ti.fromMillis(Date.now())}static fromDate(e){return ti.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ti(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Jr(this.nanoseconds,e.nanoseconds):Jr(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class ni{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ni(e)}static min(){return new ni(new ti(0,0))}static max(){return new ni(new ti(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 ri{constructor(e,t,n){void 0===t?t=0:t>e.length&&Pr(),void 0===n?n=e.length-t:n>e.length-t&&Pr(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ri.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ri?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ii extends ri{construct(e,t,n){return new ii(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new Ur(qr.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new ii(t)}static emptyPath(){return new ii([])}}const si=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class oi extends ri{construct(e,t,n){return new oi(e,t,n)}static isValidIdentifier(e){return si.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!oi.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new oi(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new Ur(qr.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new Ur(qr.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new Ur(qr.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new Ur(qr.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new oi(t)}static emptyPath(){return new oi([])}}class ai{constructor(e){this.path=e}static fromPath(e){return new ai(ii.fromString(e))}static fromName(e){return new ai(ii.fromString(e).popFirst(5))}static empty(){return new ai(ii.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ii.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ii.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ai(new ii(e.slice()))}}class ui{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function ci(e){return e.fields.find(e=>2===e.kind)}function hi(e){return e.fields.filter(e=>2!==e.kind)}ui.UNKNOWN_ID=-1;class li{constructor(e,t){this.fieldPath=e,this.kind=t}}class di{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new di(0,mi.min())}}function fi(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=ni.fromTimestamp(1e9===r?new ti(n+1,0):new ti(n,r));return new mi(r,ai.empty(),t)}function gi(e){return new mi(e.readTime,e.key,-1)}class mi{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new mi(ni.min(),ai.empty(),-1)}static max(){return new mi(ni.max(),ai.empty(),-1)}}function pi(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ai.comparator(e.documentKey,t.documentKey),0!==n?n:Jr(e.largestBatchId,t.largestBatchId))}const yi="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class vi{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function wi(e){if(e.code!==qr.FAILED_PRECONDITION||e.message!==yi)throw e;Fr("LocalStore","Unexpectedly lost primary lease")}class bi{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&Pr(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new bi((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof bi?t:bi.resolve(t)}catch(e){return bi.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):bi.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):bi.reject(t)}static resolve(n){return new bi((e,t)=>{e(n)})}static reject(n){return new bi((e,t)=>{t(n)})}static waitFor(e){return new bi((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=bi.resolve(!1);for(const n of e)t=t.next(e=>e?bi.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(a,u){return new bi((t,n)=>{const r=a.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const o=e;u(a[o]).next(e=>{i[o]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new bi((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class Ii{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.v=new jr,this.transaction.oncomplete=()=>{this.v.resolve()},this.transaction.onabort=()=>{e.error?this.v.reject(new Ti(n,e.error)):this.v.resolve()},this.transaction.onerror=e=>{var t=Ci(e.target.error);this.v.reject(new Ti(n,t))}}static open(e,t,n,r){try{return new Ii(t,e.transaction(r,n))}catch(e){throw new Ti(t,e)}}get R(){return this.v.promise}abort(e){e&&this.v.reject(e),this.aborted||(Fr("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}P(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new xi(t)}}class Ei{constructor(e,t,n){this.name=e,this.version=t,this.V=n,12.2===Ei.S(u())&&Lr("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 Fr("SimpleDb","Removing database:",e),Di(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(Ei.C())return!0;const e=u(),t=Ei.S(e),n=0<t&&t<10,r=Ei.N(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static C(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.k)}static M(e,t){return e.store(t)}static S(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static N(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async $(s){return this.db||(Fr("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new Ti(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new Ur(qr.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new Ur(qr.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new Ti(s,t))},i.onupgradeneeded=e=>{Fr("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.V.O(t,i.transaction,e.oldVersion,this.version).next(()=>{Fr("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.F&&(this.db.onversionchange=e=>this.F(e)),this.db}B(t){this.F=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.$(e);const t=Ii.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.P(),e)).catch(e=>(t.abort(e),bi.reject(e))).toPromise();return s.catch(()=>{}),await t.R,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Fr("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class _i{constructor(e){this.L=e,this.q=!1,this.U=null}get isDone(){return this.q}get K(){return this.U}set cursor(e){this.L=e}done(){this.q=!0}G(e){this.U=e}delete(){return Di(this.L.delete())}}class Ti extends Ur{constructor(e,t){super(qr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Si(e){return"IndexedDbTransactionError"===e.name}class xi{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Fr("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Fr("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),Di(n)}add(e){return Fr("SimpleDb","ADD",this.store.name,e,e),Di(this.store.add(e))}get(t){return Di(this.store.get(t)).next(e=>(Fr("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Fr("SimpleDb","DELETE",this.store.name,e),Di(this.store.delete(e))}count(){return Fr("SimpleDb","COUNT",this.store.name),Di(this.store.count())}j(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.W(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new bi((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}H(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new bi((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}J(e,t){Fr("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;var r=this.cursor(n);return this.W(r,(e,t,n)=>n.delete())}X(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.W(r,t)}Z(i){const e=this.cursor({});return new bi((n,r)=>{e.onerror=e=>{var t=Ci(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}W(e,s){const o=[];return new bi((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new _i(t),r=s(t.primaryKey,t.value,n);if(r instanceof bi){const e=r.catch(e=>(n.done(),bi.reject(e)));o.push(e)}n.isDone?i():null===n.K?t.continue():t.continue(n.K)}else i()}}).next(()=>bi.waitFor(o))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Di(e){return new bi((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Ci(e.target.error);r(t)}})}let Ai=!1;function Ci(e){const t=Ei.S(u());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new Ur("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Ai||(Ai=!0,setTimeout(()=>{throw e},0)),e}}return e}class Ni{constructor(e,t){this.asyncQueue=e,this.tt=t,this.task=null}start(){this.et(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}et(e){Fr("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Fr("IndexBackiller",`Documents written: ${await this.tt.nt()}`)}catch(e){Si(e)?Fr("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await wi(e)}await this.et(6e4)})}}class ki{constructor(e,t){this.localStore=e,this.persistence=t}async nt(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.st(e,t))}st(e,t){const n=new Set;let r=t,i=!0;return bi.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(Fr("IndexBackiller",`Processing collection: ${t}`),this.it(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}it(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.rt(n,e)).next(e=>(Fr("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}rt(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=gi(t);0<pi(n,r)&&(r=n)}),new mi(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Ri{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ot(e),this.ut=e=>t.writeSequenceNumber(e))}ot(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ut&&this.ut(e),e}}function Mi(e){return null==e}function Fi(e){return 0===e&&1/e==-1/0}function Li(e){return"number"==typeof e&&Number.isInteger(e)&&!Fi(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Oi(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Vi(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Vi(t)}function Vi(e){return e+""}function Pi(t){const n=t.length;if(Br(2<=n),2===n)return Br(""===t.charAt(0)&&""===t.charAt(1)),ii.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let o=0;o<n;){const n=t.indexOf("",o);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&Pr(),t.charAt(n+1)){case"":var s=t.substring(o,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(o,n),i+="\0";break;case"":i+=t.substring(o,n+1);break;default:Pr()}o=n+2}return new ii(r)}Ri.ct=-1;const Bi=["userId","batchId"];function qi(e,t){return[e,Oi(t)]}function Ui(e,t,n){return[e,Oi(t),n]}const ji={},Gi=["prefixPath","collectionGroup","readTime","documentId"],zi=["prefixPath","collectionGroup","documentId"],$i=["collectionGroup","readTime","prefixPath","documentId"],Ki=["canonicalId","targetId"],Qi=["targetId","path"],Hi=["path","targetId"],Wi=["collectionId","parent"],Xi=["indexId","uid"],Yi=["uid","sequenceNumber"],Ji=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Zi=["indexId","uid","orderedDocumentKey"],es=["userId","collectionPath","documentId"],ts=["userId","collectionPath","largestBatchId"],ns=["userId","collectionGroup","largestBatchId"],rs=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],is=[...rs,"documentOverlays"],ss=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],os=ss,as=[...os,"indexConfiguration","indexState","indexEntries"];class us extends vi{constructor(e,t){super(),this.ht=e,this.currentSequenceNumber=t}}function cs(e,t){var n=e;return Ei.M(n.ht,t)}function hs(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ls(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ds(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class fs{constructor(e,t){this.comparator=e,this.root=t||ms.EMPTY}insert(e,t){return new fs(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ms.BLACK,null,null))}remove(e){return new fs(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ms.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new gs(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new gs(this.root,e,this.comparator,!1)}getReverseIterator(){return new gs(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new gs(this.root,e,this.comparator,!0)}}class gs{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class ms{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:ms.RED,this.left=null!=r?r:ms.EMPTY,this.right=null!=i?i:ms.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new ms(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return ms.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return ms.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,ms.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,ms.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Pr();if(this.right.isRed())throw Pr();var e=this.left.check();if(e!==this.right.check())throw Pr();return e+(this.isRed()?0:1)}}ms.EMPTY=null,ms.RED=!0,ms.BLACK=!1,ms.EMPTY=new class{constructor(){this.size=0}get key(){throw Pr()}get value(){throw Pr()}get color(){throw Pr()}get left(){throw Pr()}get right(){throw Pr()}copy(e,t,n,r,i){return this}insert(e,t,n){return new ms(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class ps{constructor(e){this.comparator=e,this.data=new fs(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ys(this.data.getIterator())}getIteratorFrom(e){return new ys(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof ps))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new ps(this.comparator);return t.data=e,t}}class ys{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function vs(e){return e.hasNext()?e.getNext():void 0}class ws{constructor(e){(this.fields=e).sort(oi.comparator)}static empty(){return new ws([])}unionWith(e){let t=new ps(oi.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new ws(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Zr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class bs extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class Is{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new bs("Invalid base64 string: "+e):e}}(e);return new Is(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new Is(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Jr(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}Is.EMPTY_BYTE_STRING=new Is("");const Es=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function _s(t){if(Br(!!t),"string"!=typeof t)return{seconds:Ts(t.seconds),nanos:Ts(t.nanos)};{let e=0;var n=Es.exec(t);Br(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Ts(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ss(e){return"string"==typeof e?Is.fromBase64String(e):Is.fromUint8Array(e)}function xs(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Ds(e){var t=e.mapValue.fields.__previous_value__;return xs(t)?Ds(t):t}function As(e){var t=_s(e.mapValue.fields.__local_write_time__.timestampValue);return new ti(t.seconds,t.nanos)}class Cs{constructor(e,t,n,r,i,s,o,a,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=u}}class Ns{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Ns("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Ns&&e.projectId===this.projectId&&e.database===this.database}}const ks={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Rs={nullValue:"NULL_VALUE"};function Ms(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?xs(e)?4:Ks(e)?9007199254740991:10:Pr()}function Fs(r,i){if(r===i)return!0;var e,t,n=Ms(r);if(n!==Ms(i))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return As(r).isEqual(As(i));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=_s(r.timestampValue),n=_s(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,Ss(r.bytesValue).isEqual(Ss(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,Ts((t=r).geoPointValue.latitude)===Ts(e.geoPointValue.latitude)&&Ts(t.geoPointValue.longitude)===Ts(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Ts(e.integerValue)===Ts(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Ts(e.doubleValue),r=Ts(t.doubleValue);return n===r?Fi(n)===Fi(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return Zr(r.arrayValue.values||[],i.arrayValue.values||[],Fs);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(hs(t)!==hs(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!Fs(t[e],n[e])))return!1;return!0}(r);default:return Pr()}}function Ls(e,t){return void 0!==(e.values||[]).find(e=>Fs(e,t))}function Os(e,t){if(e===t)return 0;var n,r,i,s,o=Ms(e),a=Ms(t);if(o!==a)return Jr(o,a);switch(o){case 0:case 9007199254740991:return 0;case 1:return Jr(e.booleanValue,t.booleanValue);case 2:return r=t,i=Ts(e.integerValue||e.doubleValue),s=Ts(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Vs(e.timestampValue,t.timestampValue);case 4:return Vs(As(e),As(t));case 5:return Jr(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ss(e),r=Ss(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Jr(n[i],r[i]);if(0!==t)return t}return Jr(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Jr(Ts(n.latitude),Ts(r.latitude)))?s:Jr(Ts(n.longitude),Ts(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Os(n[i],r[i]);if(t)return t}return Jr(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===ks.mapValue&&t===ks.mapValue)return 0;if(e===ks.mapValue)return 1;if(t===ks.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let a=0;a<r.length&&a<s.length;++a){const t=Jr(r[a],s[a]);if(0!==t)return t;var o=Os(n[r[a]],i[s[a]]);if(0!==o)return o}return Jr(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Pr()}}function Vs(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Jr(e,t);var n=_s(e),r=_s(t),i=Jr(n.seconds,r.seconds);return 0!==i?i:Jr(n.nanos,r.nanos)}function Ps(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=_s(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?Ss(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,ai.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):Pr();var t}(e)}function Bs(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function qs(e){return e&&"integerValue"in e}function Us(e){return!!e&&"arrayValue"in e}function js(e){return e&&"nullValue"in e}function Gs(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function zs(e){return e&&"mapValue"in e}function $s(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return ls(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=$s(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=$s(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Ks(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Qs(e,t){var n=Os(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Hs(e,t){var n=Os(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Ws{constructor(e){this.value=e}static empty(){return new Ws({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!zs(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=$s(t)}setAll(e){let n=oi.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=$s(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());zs(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Fs(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];zs(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){ls(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Ws($s(this.value))}}class Xs{constructor(e,t,n,r,i,s,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=o}static newInvalidDocument(e){return new Xs(e,0,ni.min(),ni.min(),ni.min(),Ws.empty(),0)}static newFoundDocument(e,t,n,r){return new Xs(e,1,t,ni.min(),n,r,0)}static newNoDocument(e,t){return new Xs(e,2,t,ni.min(),ni.min(),Ws.empty(),0)}static newUnknownDocument(e,t){return new Xs(e,3,t,ni.min(),ni.min(),Ws.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(ni.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Ws.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ws.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ni.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 Xs&&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 Xs(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 Ys{constructor(e,t){this.position=e,this.inclusive=t}}function Js(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?ai.comparator(ai.fromName(o.referenceValue),n.key):Os(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Zs(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Fs(e.position[n],t.position[n]))return!1;return!0}class eo{constructor(e,t="asc"){this.field=e,this.dir=t}}class to{}class no extends to{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new ho(e,t,n):"array-contains"===t?new mo(e,n):"in"===t?new po(e,n):"not-in"===t?new yo(e,n):"array-contains-any"===t?new vo(e,n):new no(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?lo:fo)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Os(t,this.value)):null!==t&&Ms(this.value)===Ms(t)&&this.matchesComparison(Os(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return Pr()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class ro extends to{constructor(e,t){super(),this.filters=e,this.op=t,this.lt=null}static create(e,t){return new ro(e,t)}matches(t){return io(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.lt||(this.lt=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.lt}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.ft(e=>e.isInequality());return null!==e?e.field:null}ft(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function io(e){return"and"===e.op}function so(e){return"or"===e.op}function oo(e){return ao(e)&&io(e)}function ao(e){for(const t of e.filters)if(t instanceof ro)return!1;return!0}function uo(e,t){var n=e.filters.concat(t);return ro.create(n,e.op)}function co(e){return e instanceof no?`${(t=e).field.canonicalString()} ${t.op} ${Ps(t.value)}`:e instanceof ro?(e=e).op.toString()+" {"+e.getFilters().map(co).join(" ,")+"}":"Filter";var t}class ho extends no{constructor(e,t,n){super(e,t,n),this.key=ai.fromName(n.referenceValue)}matches(e){var t=ai.comparator(e.key,this.key);return this.matchesComparison(t)}}class lo extends no{constructor(e,t){super(e,"in",t),this.keys=go(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class fo extends no{constructor(e,t){super(e,"not-in",t),this.keys=go(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function go(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ai.fromName(e.referenceValue))}class mo extends no{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Us(t)&&Ls(t.arrayValue,this.value)}}class po extends no{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Ls(this.value.arrayValue,t)}}class yo extends no{constructor(e,t){super(e,"not-in",t)}matches(e){if(Ls(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Ls(this.value.arrayValue,t)}}class vo extends no{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Us(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Ls(this.value.arrayValue,e))}}class wo{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.dt=null}}function bo(e,t=null,n=[],r=[],i=null,s=null,o=null){return new wo(e,t,n,r,i,s,o)}function Io(e){const t=e;if(null===t.dt){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof no)return e.field.canonicalString()+e.op.toString()+Ps(e.value);if(oo(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),Mi(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ps(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ps(e)).join(",")),t.dt=e}return t.dt}function Eo(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof no?(n=e,(s=t)instanceof no&&n.op===s.op&&n.field.isEqual(s.field)&&Fs(n.value,s.value)):e instanceof ro?(i=t)instanceof ro&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void Pr();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Zs(e.startAt,t.startAt)&&Zs(e.endAt,t.endAt)}function _o(e){return ai.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function To(e,t){return e.filters.filter(e=>e instanceof no&&e.field.isEqual(t))}function So(t,n,r){let i=Rs,s=!0;for(const r of To(t,n)){let e=Rs,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(o=r.value)?Rs:"booleanValue"in o?{booleanValue:!1}:"integerValue"in o||"doubleValue"in o?{doubleValue:NaN}:"timestampValue"in o?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in o?{stringValue:""}:"bytesValue"in o?{bytesValue:""}:"referenceValue"in o?Bs(Ns.empty(),ai.empty()):"geoPointValue"in o?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in o?{arrayValue:{}}:"mapValue"in o?{mapValue:{}}:Pr();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Rs}Qs({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var o;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Qs({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function xo(t,n,r){let i=ks,s=!0;for(const r of To(t,n)){let e=ks,t=!0;switch(r.op){case">=":case">":e="nullValue"in(o=r.value)?{booleanValue:!1}:"booleanValue"in o?{doubleValue:NaN}:"integerValue"in o||"doubleValue"in o?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in o?{stringValue:""}:"stringValue"in o?{bytesValue:""}:"bytesValue"in o?Bs(Ns.empty(),ai.empty()):"referenceValue"in o?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in o?{arrayValue:{}}:"arrayValue"in o?{mapValue:{}}:"mapValue"in o?ks:Pr(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=ks}0<Hs({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var o;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Hs({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class Do{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.wt=null,this._t=null,this.startAt,this.endAt}}function Ao(e,t,n,r,i,s,o,a){return new Do(e,t,n,r,i,s,o,a)}function Co(e){return new Do(e)}function No(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 ko(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Ro(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function Mo(e){return null!==e.collectionGroup}function Fo(t){const n=t;if(null===n.wt){n.wt=[];const t=Ro(n),e=ko(n);if(null!==t&&null===e)t.isKeyField()||n.wt.push(new eo(t)),n.wt.push(new eo(oi.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.wt.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.wt.push(new eo(oi.keyField(),t))}}}return n.wt}function Lo(e){const t=e;if(!t._t)if("F"===t.limitType)t._t=bo(t.path,t.collectionGroup,Fo(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of Fo(t)){const t="desc"===i.dir?"asc":"desc";e.push(new eo(i.field,t))}var n=t.endAt?new Ys(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new Ys(t.startAt.position,t.startAt.inclusive):null;t._t=bo(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t._t}function Oo(e,t){t.getFirstInequalityField(),Ro(e);var n=e.filters.concat([t]);return new Do(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Vo(e,t,n){return new Do(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Po(e,t){return Eo(Lo(e),Lo(t))&&e.limitType===t.limitType}function Bo(e){return`${Io(Lo(e))}|lt:${e.limitType}`}function qo(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>co(e)).join(", ")}]`),Mi(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ps(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ps(e)).join(",")),`Target(${t})`}(Lo(e))}; limitType=${e.limitType})`}function Uo(n,e){return e.isFoundDocument()&&(i=n,o=(s=e).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(o):ai.isDocumentKey(i.path)?i.path.isEqual(o):i.path.isImmediateParentOf(o))&&function(e){for(const t of Fo(n))if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(i=e,(!(e=n).startAt||(t=e.startAt,r=Js(t,Fo(e),i),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=Js(t,Fo(e),i),t.inclusive?0<=r:0<r)));var t,r,i,s,o}function jo(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Go(i){return(e,t)=>{let n=!1;for(const r of Fo(i)){const i=function(e,i,t){var n=e.field.isKeyField()?ai.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?Os(n,r):Pr()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return Pr()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class zo{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){ls(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return ds(this.inner)}size(){return this.innerSize}}const $o=new fs(ai.comparator);const Ko=new fs(ai.comparator);function Qo(...e){let t=Ko;for(const n of e)t=t.insert(n.key,n);return t}function Ho(e){let n=Ko;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function Wo(){return new zo(e=>e.toString(),(e,t)=>e.isEqual(t))}const Xo=new fs(ai.comparator),Yo=new ps(ai.comparator);function Jo(...e){let t=Yo;for(const n of e)t=t.add(n);return t}const Zo=new ps(Jr);function ea(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Fi(t)?"-0":t}}function ta(e){return{integerValue:""+e}}function na(e,t){return Li(t)?ta(t):ea(e,t)}class ra{constructor(){this._=void 0}}function ia(e,t){return e instanceof ha?qs(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class sa extends ra{}class oa extends ra{constructor(e){super(),this.elements=e}}function aa(e,t){const n=da(t);for(const t of e.elements)n.some(e=>Fs(e,t))||n.push(t);return{arrayValue:{values:n}}}class ua extends ra{constructor(e){super(),this.elements=e}}function ca(e,t){let n=da(t);for(const t of e.elements)n=n.filter(e=>!Fs(e,t));return{arrayValue:{values:n}}}class ha extends ra{constructor(e,t){super(),this.serializer=e,this.gt=t}}function la(e){return Ts(e.integerValue||e.doubleValue)}function da(e){return Us(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class fa{constructor(e,t){this.field=e,this.transform=t}}class ga{constructor(e,t){this.version=e,this.transformResults=t}}class ma{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new ma}static exists(e){return new ma(void 0,e)}static updateTime(e){return new ma(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 pa(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class ya{}function va(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new Da(e.key,ma.none()):new Ea(e.key,e.data,ma.none());{const i=e.data,s=Ws.empty();let t=new ps(oi.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new _a(e.key,s,new ws(t.toArray()),ma.none())}}function wa(e,t,n){e instanceof Ea?function(e,t,n){const r=e.value.clone(),i=Sa(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof _a?function(e,t,n){if(!pa(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Sa(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Ta(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function ba(e,t,n,r){return e instanceof Ea?function(e,t,n,r){if(!pa(e.precondition,t))return n;const i=e.value.clone(),s=xa(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof _a?function(e,t,n,r){if(!pa(e.precondition,t))return n;const i=xa(e.fieldTransforms,r,t),s=t.data;return s.setAll(Ta(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,pa(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function Ia(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&Zr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof oa&&t instanceof oa||e instanceof ua&&t instanceof ua?Zr(e.elements,t.elements,Fs):e instanceof ha&&t instanceof ha?Fs(e.gt,t.gt):e instanceof sa&&t instanceof sa)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class Ea extends ya{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class _a extends ya{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Ta(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function Sa(e,t,n){const r=new Map;Br(e.length===n.length);for(let h=0;h<n.length;h++){var i=e[h],s=i.transform,o=t.data.field(i.field);r.set(i.field,(a=s,u=o,c=n[h],a instanceof oa?aa(a,u):a instanceof ua?ca(a,u):c))}var a,u,c;return r}function xa(e,t,n){const r=new Map;for(const c of e){const e=c.transform,h=n.data.field(c.field);r.set(c.field,(i=e,s=h,o=t,u=a=void 0,i instanceof sa?function(e){const t={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}};return(e=e&&xs(e)?Ds(e):e)&&(t.fields.__previous_value__=e),{mapValue:t}}(s):i instanceof oa?aa(i,s):i instanceof ua?ca(i,s):(a=ia(i=i,s),u=la(a)+la(i.gt),qs(a)&&qs(i.gt)?ta(u):ea(i.serializer,u))))}var i,s,o,a,u;return r}class Da extends ya{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Aa extends ya{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Ca{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&wa(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=ba(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=ba(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,o){const a=Wo();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=o.has(e.key)?null:r;var i=va(n,r);null!==i&&a.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(ni.min())}),a}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Jo())}isEqual(e){return this.batchId===e.batchId&&Zr(this.mutations,e.mutations,(e,t)=>Ia(e,t))&&Zr(this.baseMutations,e.baseMutations,(e,t)=>Ia(e,t))}}class Na{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Br(e.mutations.length===n.length);let r=Xo;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new Na(e,t,n,r)}}class ka{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Ra{constructor(e,t){this.count=e,this.unchangedNames=t}}function Ma(e){switch(e){default:return Pr(),0;case qr.CANCELLED:case qr.UNKNOWN:case qr.DEADLINE_EXCEEDED:case qr.RESOURCE_EXHAUSTED:case qr.INTERNAL:case qr.UNAVAILABLE:case qr.UNAUTHENTICATED:return;case qr.INVALID_ARGUMENT:case qr.NOT_FOUND:case qr.ALREADY_EXISTS:case qr.PERMISSION_DENIED:case qr.FAILED_PRECONDITION:case qr.ABORTED:case qr.OUT_OF_RANGE:case qr.UNIMPLEMENTED:case qr.DATA_LOSS:return 1}}function Fa(e){if(void 0===e)return Lr("GRPC error has no .code"),qr.UNKNOWN;switch(e){case yr.OK:return qr.OK;case yr.CANCELLED:return qr.CANCELLED;case yr.UNKNOWN:return qr.UNKNOWN;case yr.DEADLINE_EXCEEDED:return qr.DEADLINE_EXCEEDED;case yr.RESOURCE_EXHAUSTED:return qr.RESOURCE_EXHAUSTED;case yr.INTERNAL:return qr.INTERNAL;case yr.UNAVAILABLE:return qr.UNAVAILABLE;case yr.UNAUTHENTICATED:return qr.UNAUTHENTICATED;case yr.INVALID_ARGUMENT:return qr.INVALID_ARGUMENT;case yr.NOT_FOUND:return qr.NOT_FOUND;case yr.ALREADY_EXISTS:return qr.ALREADY_EXISTS;case yr.PERMISSION_DENIED:return qr.PERMISSION_DENIED;case yr.FAILED_PRECONDITION:return qr.FAILED_PRECONDITION;case yr.ABORTED:return qr.ABORTED;case yr.OUT_OF_RANGE:return qr.OUT_OF_RANGE;case yr.UNIMPLEMENTED:return qr.UNIMPLEMENTED;case yr.DATA_LOSS:return qr.DATA_LOSS;default:return Pr()}}(tt=yr=yr||{})[tt.OK=0]="OK",tt[tt.CANCELLED=1]="CANCELLED",tt[tt.UNKNOWN=2]="UNKNOWN",tt[tt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",tt[tt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",tt[tt.NOT_FOUND=5]="NOT_FOUND",tt[tt.ALREADY_EXISTS=6]="ALREADY_EXISTS",tt[tt.PERMISSION_DENIED=7]="PERMISSION_DENIED",tt[tt.UNAUTHENTICATED=16]="UNAUTHENTICATED",tt[tt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",tt[tt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",tt[tt.ABORTED=10]="ABORTED",tt[tt.OUT_OF_RANGE=11]="OUT_OF_RANGE",tt[tt.UNIMPLEMENTED=12]="UNIMPLEMENTED",tt[tt.INTERNAL=13]="INTERNAL",tt[tt.UNAVAILABLE=14]="UNAVAILABLE",tt[tt.DATA_LOSS=15]="DATA_LOSS";class La{constructor(){this.onExistenceFilterMismatchCallbacks=new Map}static get instance(){return Oa}static getOrCreateInstance(){return null===Oa&&(Oa=new La),Oa}onExistenceFilterMismatch(e){const t=Symbol();return this.onExistenceFilterMismatchCallbacks.set(t,e),()=>this.onExistenceFilterMismatchCallbacks.delete(t)}notifyOnExistenceFilterMismatch(t){this.onExistenceFilterMismatchCallbacks.forEach(e=>e(t))}}let Oa=null;function Va(){return new TextEncoder}const Pa=new Ar([4294967295,4294967295],0);function Ba(e){const t=Va().encode(e),n=new Dr;return n.update(t),new Uint8Array(n.digest())}function qa(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Ar([n,r],0),new Ar([i,s],0)]}class Ua{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new ja(`Invalid padding: ${t}`);if(n<0)throw new ja(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new ja(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new ja(`Invalid padding when bitmap length is 0: ${t}`);this.It=8*e.length-t,this.Tt=Ar.fromNumber(this.It)}Et(e,t,n){let r=e.add(t.multiply(Ar.fromNumber(n)));return 1===r.compare(Pa)&&(r=new Ar([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Tt).toNumber()}At(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}vt(e){if(0===this.It)return!1;const t=Ba(e),[n,r]=qa(t);for(let i=0;i<this.hashCount;i++){const t=this.Et(n,r,i);if(!this.At(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Ua(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.It){const n=Ba(t),[r,i]=qa(n);for(let e=0;e<this.hashCount;e++){const n=this.Et(r,i,e);this.Rt(n)}}}Rt(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class ja extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Ga{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,za.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Ga(ni.min(),r,new fs(Jr),$o,Jo())}}class za{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new za(n,t,Jo(),Jo(),Jo())}}class $a{constructor(e,t,n,r){this.Pt=e,this.removedTargetIds=t,this.key=n,this.bt=r}}class Ka{constructor(e,t){this.targetId=e,this.Vt=t}}class Qa{constructor(e,t,n=Is.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Ha{constructor(){this.St=0,this.Dt=Ya(),this.Ct=Is.EMPTY_BYTE_STRING,this.xt=!1,this.Nt=!0}get current(){return this.xt}get resumeToken(){return this.Ct}get kt(){return 0!==this.St}get Mt(){return this.Nt}$t(e){0<e.approximateByteSize()&&(this.Nt=!0,this.Ct=e)}Ot(){let n=Jo(),r=Jo(),i=Jo();return this.Dt.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:Pr()}}),new za(this.Ct,this.xt,n,r,i)}Ft(){this.Nt=!1,this.Dt=Ya()}Bt(e,t){this.Nt=!0,this.Dt=this.Dt.insert(e,t)}Lt(e){this.Nt=!0,this.Dt=this.Dt.remove(e)}qt(){this.St+=1}Ut(){--this.St}Kt(){this.Nt=!0,this.xt=!0}}class Wa{constructor(e){this.Gt=e,this.Qt=new Map,this.jt=$o,this.zt=Xa(),this.Wt=new fs(Jr)}Ht(e){for(const t of e.Pt)e.bt&&e.bt.isFoundDocument()?this.Jt(t,e.bt):this.Yt(t,e.key,e.bt);for(const n of e.removedTargetIds)this.Yt(n,e.key,e.bt)}Xt(n){this.forEachTarget(n,e=>{const t=this.Zt(e);switch(n.state){case 0:this.te(e)&&t.$t(n.resumeToken);break;case 1:t.Ut(),t.kt||t.Ft(),t.$t(n.resumeToken);break;case 2:t.Ut(),t.kt||this.removeTarget(e);break;case 3:this.te(e)&&(t.Kt(),t.$t(n.resumeToken));break;case 4:this.te(e)&&(this.ee(e),t.$t(n.resumeToken));break;default:Pr()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Qt.forEach((e,t)=>{this.te(t)&&n(t)})}ne(e){const t=e.targetId,n=e.Vt.count,r=this.se(t);if(r){var i=r.target;if(_o(i))if(0===n){const e=new ai(i.path);this.Yt(t,e,Xs.newNoDocument(e,ni.min()))}else Br(1===n);else{const r=this.ie(t);if(r!==n){const n=this.re(e,r);if(0!==n){this.ee(t);const e=2===n?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Wt=this.Wt.insert(t,e)}null===(i=La.instance)||void 0===i||i.notifyOnExistenceFilterMismatch(function(e,t,n){var r;const i={localCacheCount:t,existenceFilterCount:n.count},s=n.unchangedNames;return s&&(i.bloomFilter={applied:0===e,hashCount:null!==(r=null==s?void 0:s.hashCount)&&void 0!==r?r:0,bitmapLength:null!==(r=null===(r=null===(r=null==s?void 0:s.bits)||void 0===r?void 0:r.bitmap)||void 0===r?void 0:r.length)&&void 0!==r?r:0,padding:null!==(r=null===(r=null==s?void 0:s.bits)||void 0===r?void 0:r.padding)&&void 0!==r?r:0}),i}(n,r,e.Vt))}}}}re(e,t){var{unchangedNames:n,count:r}=e.Vt;if(!n||!n.bits)return 1;var{bits:{bitmap:i="",padding:s=0},hashCount:n=0}=n;let o,a;try{o=Ss(i).toUint8Array()}catch(e){if(e instanceof bs)return Or("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),1;throw e}try{a=new Ua(o,s,n)}catch(e){return Or(e instanceof ja?"BloomFilter error: ":"Applying bloom filter failed: ",e),1}return 0===a.It?1:r!==t-this.oe(e.targetId,a)?2:0}oe(n,r){const e=this.Gt.getRemoteKeysForTarget(n);let i=0;return e.forEach(e=>{var t=this.Gt.ue(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;r.vt(t)||(this.Yt(n,e,null),i++)}),i}ce(r){const i=new Map;this.Qt.forEach((e,t)=>{var n=this.se(t);if(n){if(e.current&&_o(n.target)){const i=new ai(n.target.path);null!==this.jt.get(i)||this.ae(t,i)||this.Yt(t,i,Xs.newNoDocument(i,r))}e.Mt&&(i.set(t,e.Ot()),e.Ft())}});let s=Jo();this.zt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.se(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.jt.forEach((e,t)=>t.setReadTime(r));var e=new Ga(r,i,this.Wt,this.jt,s);return this.jt=$o,this.zt=Xa(),this.Wt=new fs(Jr),e}Jt(e,t){var n;this.te(e)&&(n=this.ae(e,t.key)?2:0,this.Zt(e).Bt(t.key,n),this.jt=this.jt.insert(t.key,t),this.zt=this.zt.insert(t.key,this.he(t.key).add(e)))}Yt(e,t,n){if(this.te(e)){const r=this.Zt(e);this.ae(e,t)?r.Bt(t,1):r.Lt(t),this.zt=this.zt.insert(t,this.he(t).delete(e)),n&&(this.jt=this.jt.insert(t,n))}}removeTarget(e){this.Qt.delete(e)}ie(e){var t=this.Zt(e).Ot();return this.Gt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}qt(e){this.Zt(e).qt()}Zt(e){let t=this.Qt.get(e);return t||(t=new Ha,this.Qt.set(e,t)),t}he(e){let t=this.zt.get(e);return t||(t=new ps(Jr),this.zt=this.zt.insert(e,t)),t}te(e){var t=null!==this.se(e);return t||Fr("WatchChangeAggregator","Detected inactive target",e),t}se(e){var t=this.Qt.get(e);return t&&t.kt?null:this.Gt.le(e)}ee(t){this.Qt.set(t,new Ha),this.Gt.getRemoteKeysForTarget(t).forEach(e=>{this.Yt(t,e,null)})}ae(e,t){return this.Gt.getRemoteKeysForTarget(e).has(t)}}function Xa(){return new fs(ai.comparator)}function Ya(){return new fs(ai.comparator)}const Ja={asc:"ASCENDING",desc:"DESCENDING"},Za={"<":"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"},eu={and:"AND",or:"OR"};class tu{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function nu(e,t){return e.useProto3Json||Mi(t)?t:{value:t}}function ru(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function iu(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function su(e){return Br(!!e),ni.fromTimestamp((t=_s(e),new ti(t.seconds,t.nanos)));var t}function ou(e,t){return e=e,new ii(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function au(e){var t=ii.fromString(e);return Br(Su(t)),t}function uu(e,t){return ou(e.databaseId,t.path)}function cu(e,t){const n=au(t);if(n.get(1)!==e.databaseId.projectId)throw new Ur(qr.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new Ur(qr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ai(fu(n))}function hu(e,t){return ou(e.databaseId,t)}function lu(e){var t=au(e);return 4===t.length?ii.emptyPath():fu(t)}function du(e){return new ii(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function fu(e){return Br(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function gu(e,t,n){return{name:uu(e,t),fields:n.value.mapValue.fields}}function mu(e,t,n){const r=cu(e,t.name),i=su(t.updateTime),s=t.createTime?su(t.createTime):ni.min(),o=new Ws({mapValue:{fields:t.fields}}),a=Xs.newFoundDocument(r,i,s,o);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function pu(e,t){let n;if(t instanceof Ea)n={update:gu(e,t.key,t.value)};else if(t instanceof Da)n={delete:uu(e,t.key)};else if(t instanceof _a)n={update:gu(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof Aa))return Pr();n={verify:uu(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof sa)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof oa)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof ua)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof ha)return{fieldPath:e.field.canonicalString(),increment:t.gt};throw Pr()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,ru(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:Pr()),n;var r}function yu(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?ma.updateTime(su(i.updateTime)):void 0!==i.exists?ma.exists(i.exists):ma.none():ma.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Br("REQUEST_TIME"===t.setToServerValue),n=new sa;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new oa(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new ua(e)}else"increment"in t?n=new ha(e,t.increment):Pr();var r=oi.fromServerFormat(t.fieldPath);return new fa(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=cu(t,n.update.name),o=new Ws({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new ws(e.map(e=>oi.fromServerFormat(e)))}();return new _a(s,o,t,e,r)}return new Ea(s,o,e,r)}if(n.delete){const r=cu(t,n.delete);return new Da(r,e)}if(n.verify){const r=cu(t,n.verify);return new Aa(r,e)}return Pr()}function vu(e,t){return{documents:[hu(e,t.path)]}}function wu(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=hu(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=hu(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return function n(e){return e instanceof no?function(e){if("=="===e.op){if(Gs(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NAN"}};if(js(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Gs(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NOT_NAN"}};if(js(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:_u(e.field),op:Iu(e.op),value:e.value}}}(e):e instanceof ro?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:Eu(e.op),filters:t}}}(e):Pr()}(ro.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:_u(e.field),direction:(e=e.dir,Ja[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);i=nu(e,t.limit);return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(i=t.startAt).inclusive,values:i.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function bu(e){let t=lu(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){Br(1===r);const g=n.from[0];g.allDescendants?i=g.collectionId:t=t.child(g.collectionId)}let s=[];n.where&&(s=function(){const e=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Tu(e.unaryFilter.field);return no.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Tu(e.unaryFilter.field);return no.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Tu(e.unaryFilter.field);return no.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=Tu(e.unaryFilter.field);return no.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Pr()}}(e):void 0!==e.fieldFilter?function(e){return no.create(Tu(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return Pr()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return ro.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Pr()}}(e.compositeFilter.op))}(e):Pr()}(n.where);return e instanceof ro&&oo(e)?e.getFilters():[e]}());let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new eo(Tu(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let a=null;var u,c,h,l;n.limit&&(a=(e=n.limit,Mi(u="object"==typeof e?e.value:e)?null:u));let d=null;n.startAt&&(d=(c=n.startAt,l=!!c.before,h=c.values||[],new Ys(h,l)));let f=null;return n.endAt&&(f=(c=n.endAt,h=!c.before,l=c.values||[],new Ys(l,h))),Ao(t,i,o,s,a,"F",d,f)}function Iu(e){return Za[e]}function Eu(e){return eu[e]}function _u(e){return{fieldPath:e.canonicalString()}}function Tu(e){return oi.fromServerFormat(e.fieldPath)}function Su(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class xu{constructor(e,t,n,r,i=ni.min(),s=ni.min(),o=Is.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new xu(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new xu(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new xu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new xu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Du{constructor(e){this.fe=e}}function Au(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Cu(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:uu(i=e.fe,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:ru(i,e.version.toTimestamp()),createTime:ru(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Nu(t.version)};else{if(!t.isUnknownDocument())return Pr();r.unknownDocument={path:n.path.toArray(),version:Nu(t.version)}}var i;return r}function Cu(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Nu(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function ku(e){var t=new ti(e.seconds,e.nanoseconds);return ni.fromTimestamp(t)}function Ru(t,e){const n=(e.baseMutations||[]).map(e=>yu(t.fe,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>yu(t.fe,e)),i=ti.fromMillis(e.localWriteTimeMs);return new Ca(e.batchId,i,n,r)}function Mu(e){var t,n=ku(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?ku(e.lastLimboFreeSnapshotVersion):ni.min();let i;return i=void 0!==e.query.documents?(Br(1===(t=e.query).documents.length),Lo(Co(lu(t.documents[0])))):Lo(bu(e.query)),new xu(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,Is.fromBase64String(e.resumeToken))}function Fu(e,t){var n=Nu(t.snapshotVersion),r=Nu(t.lastLimboFreeSnapshotVersion),i=(_o(t.target)?vu:wu)(e.fe,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Io(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Lu(e){var t=bu({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Vo(t,t.limit,"L"):t}function Ou(e,t){return new ka(t.largestBatchId,yu(e.fe,t.overlayMutation))}function Vu(e,t){var n=t.path.lastSegment();return[e,Oi(t.path.popLast()),n]}function Pu(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:Nu(r.readTime),documentKey:Oi(r.documentKey.path),largestBatchId:r.largestBatchId}}class Bu{getBundleMetadata(e,t){return qu(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:ku(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return qu(e).put({bundleId:(n=t).id,createTime:Nu(su(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return Uu(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:Lu(t.bundledQuery),readTime:ku(t.readTime)};var t})}saveNamedQuery(e,t){return Uu(e).put({name:(t=t).name,readTime:Nu(su(t.readTime)),bundledQuery:t.bundledQuery})}}function qu(e){return cs(e,"bundles")}function Uu(e){return cs(e,"namedQueries")}class ju{constructor(e,t){this.serializer=e,this.userId=t}static de(e,t){var n=t.uid||"";return new ju(e,n)}getOverlay(e,t){return Gu(e).get(Vu(this.userId,t)).next(e=>e?Ou(this.serializer,e):null)}getOverlays(e,t){const n=Wo();return bi.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new ka(i,t);s.push(this.we(r,n))}),bi.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Oi(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(Gu(n).J("collectionPathOverlayIndex",t))}),bi.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Wo(),i=Oi(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return Gu(e).j("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=Ou(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=Wo();let o;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Gu(e).X({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=Ou(this.serializer,t);s.size()<i||r.largestBatchId===o?(s.set(r.getKey(),r),o=r.largestBatchId):n.done()}).next(()=>s)}we(e,t){return Gu(e).put(function(e,t,n){var[,r,i]=Vu(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:pu(e.fe,n.mutation)}}(this.serializer,this.userId,t))}}function Gu(e){return cs(e,"documentOverlays")}class zu{constructor(){}_e(e,t){this.me(e,t),t.ge()}me(e,t){var n,r;"nullValue"in e?this.ye(t,5):"booleanValue"in e?(this.ye(t,10),t.pe(e.booleanValue?1:0)):"integerValue"in e?(this.ye(t,15),t.pe(Ts(e.integerValue))):"doubleValue"in e?(n=Ts(e.doubleValue),isNaN(n)?this.ye(t,13):(this.ye(t,15),Fi(n)?t.pe(0):t.pe(n))):"timestampValue"in e?(r=e.timestampValue,this.ye(t,20),"string"==typeof r?t.Ie(r):(t.Ie(`${r.seconds||""}`),t.pe(r.nanos||0))):"stringValue"in e?(this.Te(e.stringValue,t),this.Ee(t)):"bytesValue"in e?(this.ye(t,30),t.Ae(Ss(e.bytesValue)),this.Ee(t)):"referenceValue"in e?this.ve(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.ye(t,45),t.pe(r.latitude||0),t.pe(r.longitude||0)):"mapValue"in e?Ks(e)?this.ye(t,Number.MAX_SAFE_INTEGER):(this.Re(e.mapValue,t),this.Ee(t)):"arrayValue"in e?(this.Pe(e.arrayValue,t),this.Ee(t)):Pr()}Te(e,t){this.ye(t,25),this.be(e,t)}be(e,t){t.Ie(e)}Re(e,t){var n=e.fields||{};this.ye(t,55);for(const e of Object.keys(n))this.Te(e,t),this.me(n[e],t)}Pe(e,t){var n=e.values||[];this.ye(t,50);for(const e of n)this.me(e,t)}ve(e,t){this.ye(t,37),ai.fromName(e).path.forEach(e=>{this.ye(t,60),this.be(e,t)})}ye(e,t){e.pe(t)}Ee(e){e.pe(2)}}function $u(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}zu.Ve=new zu;class Ku{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Se(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.De(n.value),n=t.next();this.Ce()}xe(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ne(n.value),n=t.next();this.ke()}Me(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.De(e);else if(e<2048)this.De(960|e>>>6),this.De(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.De(480|e>>>12),this.De(128|63&e>>>6),this.De(128|63&e);else{const e=t.codePointAt(0);this.De(240|e>>>18),this.De(128|63&e>>>12),this.De(128|63&e>>>6),this.De(128|63&e)}}this.Ce()}$e(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ne(e);else if(e<2048)this.Ne(960|e>>>6),this.Ne(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ne(480|e>>>12),this.Ne(128|63&e>>>6),this.Ne(128|63&e);else{const e=t.codePointAt(0);this.Ne(240|e>>>18),this.Ne(128|63&e>>>12),this.Ne(128|63&e>>>6),this.Ne(128|63&e)}}this.ke()}Oe(e){var t=this.Fe(e),n=$u(t);this.Be(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Le(e){var t=this.Fe(e),n=$u(t);this.Be(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}qe(){this.Ue(255),this.Ue(255)}Ke(){this.Ge(255),this.Ge(255)}reset(){this.position=0}seed(e){this.Be(e.length),this.buffer.set(e,this.position),this.position+=e.length}Qe(){return this.buffer.slice(0,this.position)}Fe(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}De(e){var t=255&e;0==t?(this.Ue(0),this.Ue(255)):255==t?(this.Ue(255),this.Ue(0)):this.Ue(t)}Ne(e){var t=255&e;0==t?(this.Ge(0),this.Ge(255)):255==t?(this.Ge(255),this.Ge(0)):this.Ge(e)}Ce(){this.Ue(0),this.Ue(1)}ke(){this.Ge(0),this.Ge(1)}Ue(e){this.Be(1),this.buffer[this.position++]=e}Ge(e){this.Be(1),this.buffer[this.position++]=~e}Be(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class Qu{constructor(e){this.je=e}Ae(e){this.je.Se(e)}Ie(e){this.je.Me(e)}pe(e){this.je.Oe(e)}ge(){this.je.qe()}}class Hu{constructor(e){this.je=e}Ae(e){this.je.xe(e)}Ie(e){this.je.$e(e)}pe(e){this.je.Le(e)}ge(){this.je.Ke()}}class Wu{constructor(){this.je=new Ku,this.ze=new Qu(this.je),this.We=new Hu(this.je)}seed(e){this.je.seed(e)}He(e){return 0===e?this.ze:this.We}Qe(){return this.je.Qe()}reset(){this.je.reset()}}class Xu{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Je(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new Xu(this.indexId,this.documentKey,this.arrayValue,n)}}function Yu(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Ju(e.arrayValue,t.arrayValue),0!==n?n:(n=Ju(e.directionalValue,t.directionalValue),0!==n?n:ai.comparator(e.documentKey,t.documentKey)))}function Ju(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class Zu{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ye=e.orderBy,this.Xe=[];for(const t of e.filters){const e=t;e.isInequality()?this.Ze=e:this.Xe.push(e)}}tn(e){Br(e.collectionGroup===this.collectionId);var t=ci(e);if(void 0!==t&&!this.en(t))return!1;const n=hi(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.en(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.Ze){if(!r.has(this.Ze.field.canonicalString())){const e=n[i];if(!this.nn(this.Ze,e)||!this.sn(this.Ye[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Ye.length||!this.sn(this.Ye[s++],e))return!1}return!0}en(e){for(const t of this.Xe)if(this.nn(t,e))return!0;return!1}nn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function ec(e){if(0===e.getFilters().length)return[];const t=function t(e){if(Br(e instanceof no||e instanceof ro),e instanceof no)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=ro.create(n,e.op);return r=oc(r),rc(r)?r:(Br(r instanceof ro),Br(io(r)),Br(1<r.filters.length),r.filters.reduce((e,t)=>ic(e,t)))}(function t(n){var e;if(Br(n instanceof no||n instanceof ro),n instanceof no){if(n instanceof po){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>no.create(n.field,"==",e)))||[];return ro.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return ro.create(r,n.op)}(e));return Br(rc(t)),tc(t)||nc(t)?[t]:t.getFilters()}function tc(e){return e instanceof no}function nc(e){return e instanceof ro&&oo(e)}function rc(e){return tc(e)||nc(e)||function(e){if(e instanceof ro&&so(e)){for(const t of e.getFilters())if(!tc(t)&&!nc(t))return!1;return!0}return!1}(e)}function ic(e,t){var n,r;return Br(e instanceof no||e instanceof ro),Br(t instanceof no||t instanceof ro),oc(e instanceof no?t instanceof no?(n=e,r=t,ro.create([n,r],"and")):sc(e,t):t instanceof no?sc(t,e):function(e,t){if(Br(0<e.filters.length&&0<t.filters.length),io(e)&&io(t))return uo(e,t.getFilters());const n=so(e)?e:t,r=so(e)?t:e,i=n.filters.map(e=>ic(e,r));return ro.create(i,"or")}(e,t))}function sc(t,e){if(io(e))return uo(e,t.getFilters());var n=e.filters.map(e=>ic(t,e));return ro.create(n,"or")}function oc(t){if(Br(t instanceof no||t instanceof ro),t instanceof no)return t;const e=t.getFilters();if(1===e.length)return oc(e[0]);if(ao(t))return t;const n=e.map(e=>oc(e)),r=[];return n.forEach(e=>{e instanceof no?r.push(e):e instanceof ro&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:ro.create(r,t.op)}class ac{constructor(){this.rn=new uc}addToCollectionParentIndex(e,t){return this.rn.add(t),bi.resolve()}getCollectionParents(e,t){return bi.resolve(this.rn.getEntries(t))}addFieldIndex(e,t){return bi.resolve()}deleteFieldIndex(e,t){return bi.resolve()}getDocumentsMatchingTarget(e,t){return bi.resolve(null)}getIndexType(e,t){return bi.resolve(0)}getFieldIndexes(e,t){return bi.resolve([])}getNextCollectionGroupToUpdate(e){return bi.resolve(null)}getMinOffset(e,t){return bi.resolve(mi.min())}getMinOffsetFromCollectionGroup(e,t){return bi.resolve(mi.min())}updateCollectionGroup(e,t,n){return bi.resolve()}updateIndexEntries(e,t){return bi.resolve()}}class uc{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ps(ii.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new ps(ii.comparator)).toArray()}}const cc=new Uint8Array(0);class hc{constructor(e,t){this.user=e,this.databaseId=t,this.on=new uc,this.un=new zo(e=>Io(e),(e,t)=>Eo(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.on.has(t))return bi.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.on.add(t)});r={collectionId:n,parent:Oi(r)};return lc(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[ei(n),""],!1,!0);return lc(e).j(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Pi(t.parent))}return r})}addFieldIndex(e,t){const n=fc(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=gc(e);return i.next(e=>{n.put(Pu(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=fc(e),r=gc(e),i=dc(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,c){const h=dc(e);let l=!0;const n=new Map;return bi.forEach(this.cn(c),t=>this.an(e,t).next(e=>{l=l&&!!e,n.set(t,e)})).next(()=>{if(l){let u=Jo();const l=[];return bi.forEach(n,(e,t)=>{Fr("IndexedDbIndexManager",`Using index ${a=e,`id=${a.indexId}|cg=${a.collectionGroup}|f=${a.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Io(c)}`);var n=function(e,t){var n=ci(t);if(void 0===n)return null;for(const t of To(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of hi(t))for(const t of To(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),i=function(e,t){const n=[];let r=!0;for(const i of hi(t)){const t=(0===i.kind?So:xo)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Ys(n,r)}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of hi(t)){const t=(0===i.kind?xo:So)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Ys(n,r)}(t,e),o=this.hn(e,t,i),a=this.hn(e,t,s),r=this.ln(e,t,r),r=this.fn(e.indexId,n,o,i.inclusive,a,s.inclusive,r);return bi.forEach(r,e=>h.H(e,c.limit).next(e=>{e.forEach(e=>{var t=ai.fromSegments(e.documentKey);u.has(t)||(u=u.add(t),l.push(t))})}))}).next(()=>l)}return bi.resolve(null)})}cn(t){let e=this.un.get(t);return e||(e=0===t.filters.length?[t]:ec(ro.create(t.filters,"and")).map(e=>bo(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.un.set(t,e),e)}fn(t,e,n,r,i,s,o){const a=(null!=e?e.length:1)*Math.max(n.length,i.length),u=a/(null!=e?e.length:1),c=[];for(let h=0;h<a;++h){const a=e?this.dn(e[h/u]):cc,l=this.wn(t,a,n[h%u],r),d=this._n(t,a,i[h%u],s),f=o.map(e=>this.wn(t,a,e,!0));c.push(...this.createRange(l,d,f))}return c}wn(e,t,n,r){const i=new Xu(e,ai.empty(),t,n);return r?i:i.Je()}_n(e,t,n,r){const i=new Xu(e,ai.empty(),t,n);return r?i.Je():i}an(e,t){const r=new Zu(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.tn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.cn(t);return bi.forEach(r,t=>this.an(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new ps(oi.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>null!==t.limit&&1<r.length&&2===n?1:n)}mn(e,t){const n=new Wu;for(const i of hi(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.He(i.kind);zu.Ve._e(e,r)}return n.Qe()}dn(e){const t=new Wu;return zu.Ve._e(e,t.He(0)),t.Qe()}gn(e,t){const n=new Wu;return zu.Ve._e(Bs(this.databaseId,t),n.He(0===(r=hi(e)).length?0:r[r.length-1].kind)),n.Qe();var r}ln(e,t,n){if(null===n)return[];let r=[];r.push(new Wu);let i=0;for(const s of hi(e)){const e=n[i++];for(const n of r)if(this.yn(t,s.fieldPath)&&Us(e))r=this.pn(r,s,e);else{const t=n.He(s.kind);zu.Ve._e(e,t)}}return this.In(r)}hn(e,t,n){return this.ln(e,t,n.position)}In(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Qe();return t}pn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new Wu;r.seed(n.Qe()),zu.Ve._e(e,r.He(t.kind)),i.push(r)}return i}yn(e,t){return!!e.filters.find(e=>e instanceof no&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=fc(e),r=gc(e);return(t?n.j("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.j()).next(e=>{const s=[];return bi.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new di(e.sequenceNumber,new mi(ku(e.readTime),new ai(Pi(e.documentKey)),e.largestBatchId)):di.empty(),r=t.fields.map(([e,t])=>new li(oi.fromServerFormat(e),t)),new ui(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Jr(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=fc(e),s=gc(e);return this.Tn(e).next(t=>i.j("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>bi.forEach(e,e=>s.put(Pu(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return bi.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?bi.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),bi.forEach(e,n=>this.En(i,t,n).next(e=>{var t=this.An(r,n);return e.isEqual(t)?bi.resolve():this.vn(i,r,n,e,t)}))))})}Rn(e,t,n,r){return dc(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.gn(n,t.key),documentKey:t.key.path.toArray()})}Pn(e,t,n,r){return dc(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.gn(n,t.key),t.key.path.toArray()])}En(e,n,r){const t=dc(e);let i=new ps(Yu);return t.X({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.gn(r,n)])},(e,t)=>{i=i.add(new Xu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}An(e,t){let n=new ps(Yu);var r=this.mn(t,e);if(null==r)return n;const i=ci(t);if(null!=i){var s=e.data.field(i.fieldPath);if(Us(s))for(const i of s.arrayValue.values||[])n=n.add(new Xu(t.indexId,e.key,this.dn(i),r))}else n=n.add(new Xu(t.indexId,e.key,cc,r));return n}vn(t,n,r,c,e){Fr("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const i=[];return function(e,n,r,i){var s=c.getIterator(),o=e.getIterator();let a=vs(s),u=vs(o);for(;a||u;){let e=!1,t=!1;if(a&&u){const r=n(a,u);r<0?t=!0:0<r&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(u),u=vs(o)):t?(i(a),a=vs(s)):(a=vs(s),u=vs(o))}}(e,Yu,e=>{i.push(this.Rn(t,n,r,e))},e=>{i.push(this.Pn(t,n,r,e))}),bi.waitFor(i)}Tn(e){let r=1;return gc(e).X({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>Yu(e,t)).filter((e,t,n)=>!t||0!==Yu(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=Yu(i,e),s=Yu(i,t);if(0===n)r[0]=e.Je();else if(0<n&&s<0)r.push(i),r.push(i.Je());else if(0<s)break}r.push(t);const i=[];for(let o=0;o<r.length;o+=2){if(this.bn(r[o],r[o+1]))return[];const t=[r[o].indexId,this.uid,r[o].arrayValue,r[o].directionalValue,cc,[]],n=[r[o+1].indexId,this.uid,r[o+1].arrayValue,r[o+1].directionalValue,cc,[]];i.push(IDBKeyRange.bound(t,n))}return i}bn(e,t){return 0<Yu(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(mc)}getMinOffset(t,e){return bi.mapArray(this.cn(e),e=>this.an(t,e).next(e=>e||Pr())).next(mc)}}function lc(e){return cs(e,"collectionParents")}function dc(e){return cs(e,"indexEntries")}function fc(e){return cs(e,"indexConfiguration")}function gc(e){return cs(e,"indexState")}function mc(e){Br(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;pi(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new mi(t.readTime,t.documentKey,n)}const pc={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class yc{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new yc(e,yc.DEFAULT_COLLECTION_PERCENTILE,yc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function vc(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const u=r.X({range:o},(e,t,n)=>(a++,n.delete()));s.push(u.next(()=>{Br(1===a)}));const c=[];for(const e of n.mutations){const r=Ui(t,e.key.path,n.batchId);s.push(i.delete(r)),c.push(e.key)}return bi.waitFor(s).next(()=>c)}function wc(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw Pr();t=e.noDocument}return JSON.stringify(t).length}yc.DEFAULT_COLLECTION_PERCENTILE=10,yc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,yc.DEFAULT=new yc(41943040,yc.DEFAULT_COLLECTION_PERCENTILE,yc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),yc.DISABLED=new yc(-1,0,0);class bc{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Vn={}}static de(e,t,n,r){Br(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new bc(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Ec(e).X({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=_c(h),m=Ec(h);return m.add({}).next(e=>{Br("number"==typeof e);const t=new Ca(e,l,d,f),n=(i=this.serializer,s=this.userId,o=t,a=o.baseMutations.map(e=>pu(i.fe,e)),u=o.mutations.map(e=>pu(i.fe,e)),{userId:s,batchId:o.batchId,localWriteTimeMs:o.localWriteTime.toMillis(),baseMutations:a,mutations:u}),r=[];var i,s,o,a,u;let c=new ps((e,t)=>Jr(e.canonicalString(),t.canonicalString()));for(const h of f){const l=Ui(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,ji))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.Vn[e]=t.keys()}),bi.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Ec(e).get(t).next(e=>e?(Br(e.userId===this.userId),Ru(this.serializer,e)):null)}Sn(e,n){return this.Vn[n]?bi.resolve(this.Vn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Vn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return Ec(e).X({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Br(t.batchId>=r),i=Ru(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Ec(e).X({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Ec(e).j("userMutationsIndex",t).next(e=>e.map(e=>Ru(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=qi(this.userId,a.path),t=IDBKeyRange.lowerBound(e),u=[];return _c(o).X({range:t},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);if(r===this.userId&&a.path.isEqual(i))return Ec(o).get(s).next(e=>{if(!e)throw Pr();Br(e.userId===this.userId),u.push(Ru(this.serializer,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new ps(Jr);const n=[];return e.forEach(o=>{var e=qi(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=_c(t).X({range:e},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);r===this.userId&&o.path.isEqual(i)?a=a.add(s):n.done()});n.push(e)}),bi.waitFor(n).next(()=>this.Dn(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=qi(this.userId,o),r=IDBKeyRange.lowerBound(n);let u=new ps(Jr);return _c(e).X({range:r},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);r===this.userId&&o.isPrefixOf(i)?i.length===a&&(u=u.add(s)):n.done()}).next(()=>this.Dn(e,u))}Dn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Ec(t).get(e).next(e=>{if(null===e)throw Pr();Br(e.userId===this.userId),n.push(Ru(this.serializer,e))}))}),bi.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return vc(t.ht,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.Cn(n.batchId)}),bi.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}Cn(e){delete this.Vn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return bi.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return _c(n).X({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Pi(e[1]);r.push(t)}else n.done()}).next(()=>{Br(0===r.length)})})}containsKey(e,t){return Ic(e,this.userId,t)}xn(e){return Tc(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function Ic(e,s,t){const n=qi(s,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return _c(e).X({range:r,Y:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===o&&(a=!0),n.done()}).next(()=>a)}function Ec(e){return cs(e,"mutations")}function _c(e){return cs(e,"documentMutations")}function Tc(e){return cs(e,"mutationQueues")}class Sc{constructor(e){this.Nn=e}next(){return this.Nn+=2,this.Nn}static kn(){return new Sc(0)}static Mn(){return new Sc(-1)}}class xc{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.$n(n).next(e=>{const t=new Sc(e.highestTargetId);return e.highestTargetId=t.next(),this.On(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.$n(e).next(e=>ni.fromTimestamp(new ti(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.$n(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.$n(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.On(t,e)))}addTargetData(t,n){return this.Fn(t,n).next(()=>this.$n(t).next(e=>(e.targetCount+=1,this.Bn(n,e),this.On(t,e))))}updateTargetData(e,t){return this.Fn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Dc(t).delete(e.targetId)).next(()=>this.$n(t)).next(e=>(Br(0<e.targetCount),--e.targetCount,this.On(t,e)))}removeTargets(r,i,s){let o=0;const a=[];return Dc(r).X((e,t)=>{var n=Mu(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>bi.waitFor(a)).next(()=>o)}forEachTarget(e,r){return Dc(e).X((e,t)=>{var n=Mu(t);r(n)})}$n(e){return Ac(e).get("targetGlobalKey").next(e=>(Br(null!==e),e))}On(e,t){return Ac(e).put("targetGlobalKey",t)}Fn(e,t){return Dc(e).put(Fu(this.serializer,t))}Bn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.$n(e).next(e=>e.targetCount)}getTargetData(e,i){var t=Io(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return Dc(e).X({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Mu(t);Eo(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=Cc(n);return e.forEach(e=>{var t=Oi(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),bi.waitFor(i)}removeMatchingKeys(n,e,r){const i=Cc(n);return bi.forEach(e,e=>{var t=Oi(e.path);return bi.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=Cc(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=Cc(e);let i=Jo();return r.X({range:n,Y:!0},(e,t,n)=>{var r=Pi(e[1]),r=new ai(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Oi(t.path),n=IDBKeyRange.bound([n],[ei(n)],!1,!0);let r=0;return Cc(e).X({index:"documentTargetsIndex",Y:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}le(e,t){return Dc(e).get(t).next(e=>e?Mu(e):null)}}function Dc(e){return cs(e,"targets")}function Ac(e){return cs(e,"targetGlobal")}function Cc(e){return cs(e,"targetDocuments")}function Nc([e,t],[n,r]){var i=Jr(e,n);return 0===i?Jr(t,r):i}class kc{constructor(e){this.Ln=e,this.buffer=new ps(Nc),this.qn=0}Un(){return++this.qn}Kn(e){var t=[e,this.Un()];if(this.buffer.size<this.Ln)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Nc(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Rc{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Qn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}Qn(e){Fr("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Si(e)?Fr("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await wi(e)}await this.Qn(3e5)})}}class Mc{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.zn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return bi.resolve(Ri.ct);const n=new kc(t);return this.jn.forEachTarget(e,e=>n.Kn(e.sequenceNumber)).next(()=>this.jn.Wn(e,e=>n.Kn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Fr("LruGarbageCollector","Garbage collection skipped; disabled"),bi.resolve(pc)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Fr("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),pc):this.Hn(t,n))}getCacheSize(e){return this.jn.getCacheSize(e)}Hn(t,n){let r,i,s,o,a,u,c;const h=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(Fr("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,o=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,a=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),Mr()<=l.DEBUG&&Fr("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-h}ms\n\tDetermined least recently used ${i} in `+(a-o)+"ms\n"+`\tRemoved ${s} targets in `+(u-a)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),bi.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class Fc{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Mc(e,t))}zn(e){const n=this.Jn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Jn(e){let t=0;return this.Wn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Wn(e,n){return this.Yn(e,(e,t)=>n(t))}addReference(e,t,n){return Lc(e,n)}removeReference(e,t,n){return Lc(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Lc(e,t)}Xn(t,n){let r=!1;return Tc(t).Z(e=>Ic(t,e,n).next(e=>(e&&(r=!0),bi.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let o=0;return this.Yn(n,(t,e)=>{if(e<=r){const r=this.Xn(n,t).next(e=>{if(!e)return o++,i.getEntry(n,t).next(()=>(i.removeEntry(t,ni.min()),Cc(n).delete([0,Oi(t.path)])))});s.push(r)}}).next(()=>bi.waitFor(s)).next(()=>i.apply(n)).next(()=>o)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Lc(e,t)}Yn(e,r){const t=Cc(e);let i,s=Ri.ct;return t.X({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==Ri.ct&&r(new ai(Pi(i)),s),s=n,i=t):s=Ri.ct}).next(()=>{s!==Ri.ct&&r(new ai(Pi(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Lc(e,t){return Cc(e).put((e=e.currentSequenceNumber,{targetId:0,path:Oi(t.path),sequenceNumber:e}))}class Oc{constructor(){this.changes=new zo(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Xs.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?bi.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Vc{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Uc(e).put(n)}removeEntry(e,n,t){return Uc(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],Cu(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Zn(t,e)))}getEntry(e,n){let r=Xs.newInvalidDocument(n);return Uc(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(jc(n))},(e,t)=>{r=this.ts(n,t)}).next(()=>r)}es(e,n){let r={size:0,document:Xs.newInvalidDocument(n)};return Uc(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(jc(n))},(e,t)=>{r={document:this.ts(n,t),size:wc(t)}}).next(()=>r)}getEntries(e,t){let r=$o;return this.ns(e,t,(e,t)=>{var n=this.ts(e,t);r=r.insert(e,n)}).next(()=>r)}ss(e,t){let r=$o,i=new fs(ai.comparator);return this.ns(e,t,(e,t)=>{var n=this.ts(e,t);r=r.insert(e,n),i=i.insert(e,wc(t))}).next(()=>({documents:r,rs:i}))}ns(e,t,i){if(t.isEmpty())return bi.resolve();let n=new ps(zc);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(jc(n.first()),jc(n.last())),s=n.getIterator();let o=s.getNext();return Uc(e).X({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ai.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);o&&zc(o,r)<0;)i(o,null),o=s.getNext();o&&o.isEqual(r)&&(i(o,t),o=s.hasNext()?s.getNext():null),o?n.G(jc(o)):n.done()}).next(()=>{for(;o;)i(o,null),o=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,r,t,i){const n=r.path,s=[n.popLast().toArray(),n.lastSegment(),Cu(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],o=[n.popLast().toArray(),n.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Uc(e).j(IDBKeyRange.bound(s,o,!0)).next(e=>{let t=$o;for(const n of e){const e=this.ts(ai.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);e.isFoundDocument()&&(Uo(r,e)||i.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=$o;var r=Gc(t,n),o=Gc(t,mi.max());return Uc(e).X({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,o,!0)},(e,t,n)=>{var r=this.ts(ai.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new Bc(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return qc(e).get("remoteDocumentGlobalKey").next(e=>(Br(!!e),e))}Zn(e,t){return qc(e).put("remoteDocumentGlobalKey",t)}ts(e,t){if(t){const e=function(e,t){let n;if(t.document)n=mu(e.fe,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ai.fromSegments(t.noDocument.path),i=ku(t.noDocument.readTime);n=Xs.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Pr();{const e=ai.fromSegments(t.unknownDocument.path),s=ku(t.unknownDocument.version);n=Xs.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new ti(t[0],t[1]),ni.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(ni.min()))return e}return Xs.newInvalidDocument(e)}}function Pc(e){return new Vc(e)}class Bc extends Oc{constructor(e,t){super(),this.os=e,this.trackRemovals=t,this.us=new zo(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const o=[];let a=0,u=new ps((e,t)=>Jr(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.us.get(e);if(o.push(this.os.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Au(this.os.serializer,t);u=u.add(e.path.popLast());var i=wc(r);a+=i-n.size,o.push(this.os.addEntry(s,e,r))}else if(a-=n.size,this.trackRemovals){const a=Au(this.os.serializer,t.convertToNoDocument(ni.min()));o.push(this.os.addEntry(s,e,a))}}),u.forEach(e=>{o.push(this.os.indexManager.addToCollectionParentIndex(s,e))}),o.push(this.os.updateMetadata(s,a)),bi.waitFor(o)}getFromCache(e,t){return this.os.es(e,t).next(e=>(this.us.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.os.ss(e,t).next(({documents:n,rs:e})=>(e.forEach((e,t)=>{this.us.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function qc(e){return cs(e,"remoteDocumentGlobal")}function Uc(e){return cs(e,"remoteDocumentsV14")}function jc(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Gc(e,t){const n=t.documentKey.path.toArray();return[e,Cu(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function zc(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Jr(n[s],r[s]),i)return i;return i=Jr(n.length,r.length),i||(i=Jr(n[n.length-2],r[r.length-2]),i||Jr(n[n.length-1],r[r.length-1]))}class $c{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Kc{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&ba(r.mutation,e,ws.empty(),ti.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Jo()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Jo()){const r=Wo();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=Qo();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=Wo();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Jo()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=$o;const o=Wo(),a=Wo();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof _a)?s=s.insert(t.key,t):void 0!==n?(o.set(t.key,n.mutation.getFieldMask()),ba(n.mutation,t,n.mutation.getFieldMask(),ti.now())):o.set(t.key,ws.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>o.set(e,t)),t.forEach((e,t)=>{var n;return a.set(e,new $c(t,null!==(n=o.get(e))&&void 0!==n?n:null))}),a))}recalculateAndSaveOverlays(s,o){const a=Wo();let u=new fs((e,t)=>e-t),c=Jo();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,o).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=o.get(e);null!==n&&(t=a.get(e)||ws.empty(),t=r.applyToLocalView(n,t),a.set(e,t),t=(u.get(r.batchId)||Jo()).add(e),u=u.insert(r.batchId,t))})}).next(()=>{const e=[],t=u.getReverseIterator();for(;t.hasNext();){const u=t.getNext(),n=u.key,r=u.value,i=Wo();r.forEach(e=>{var t;c.has(e)||(null!==(t=va(o.get(e),a.get(e)))&&i.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return bi.waitFor(e)}).next(()=>a)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,ai.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):Mo(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(s,t,o,a){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,o,a).next(n=>{const e=0<a-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,o.largestBatchId,a-n.size):bi.resolve(Wo());let r=-1,i=n;return e.next(e=>bi.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?bi.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,Jo())).next(e=>({batchId:r,changes:Ho(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ai(t)).next(e=>{let t=Qo();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s){const o=i.collectionGroup;let a=Qo();return this.indexManager.getCollectionParents(r,o).next(e=>bi.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new Do(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}getDocumentsMatchingCollectionQuery(t,s,n){let o;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(o=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,o))).next(r=>{o.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Xs.newInvalidDocument(n)))});let i=Qo();return r.forEach((e,t)=>{var n=o.get(e);void 0!==n&&ba(n.mutation,t,ws.empty(),ti.now()),Uo(s,t)&&(i=i.insert(e,t))}),i})}}class Qc{constructor(e){this.serializer=e,this.cs=new Map,this.hs=new Map}getBundleMetadata(e,t){return bi.resolve(this.cs.get(t))}saveBundleMetadata(e,t){return this.cs.set(t.id,{id:t.id,version:t.version,createTime:su(t.createTime)}),bi.resolve()}getNamedQuery(e,t){return bi.resolve(this.hs.get(t))}saveNamedQuery(e,t){return this.hs.set(t.name,{name:(t=t).name,query:Lu(t.bundledQuery),readTime:su(t.readTime)}),bi.resolve()}}class Hc{constructor(){this.overlays=new fs(ai.comparator),this.ls=new Map}getOverlay(e,t){return bi.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Wo();return bi.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.we(n,r,t)}),bi.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.ls.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.ls.delete(n)),bi.resolve()}getOverlaysForCollection(e,t,n){const r=Wo(),i=t.length+1,s=new ai(t.child("")),o=this.overlays.getIteratorFrom(s);for(;o.hasNext();){const e=o.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return bi.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new fs((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=Wo(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const o=Wo(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach((e,t)=>o.set(e,t)),!(o.size()>=r)););return bi.resolve(o)}we(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.ls.get(r.largestBatchId).delete(n.key);this.ls.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new ka(t,n));let i=this.ls.get(t);void 0===i&&(i=Jo(),this.ls.set(t,i)),this.ls.set(t,i.add(n.key))}}class Wc{constructor(){this.fs=new ps(Xc.ds),this.ws=new ps(Xc._s)}isEmpty(){return this.fs.isEmpty()}addReference(e,t){var n=new Xc(e,t);this.fs=this.fs.add(n),this.ws=this.ws.add(n)}gs(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.ys(new Xc(e,t))}ps(e,t){e.forEach(e=>this.removeReference(e,t))}Is(e){const t=new ai(new ii([])),n=new Xc(t,e),r=new Xc(t,e+1),i=[];return this.ws.forEachInRange([n,r],e=>{this.ys(e),i.push(e.key)}),i}Ts(){this.fs.forEach(e=>this.ys(e))}ys(e){this.fs=this.fs.delete(e),this.ws=this.ws.delete(e)}Es(e){var t=new ai(new ii([])),n=new Xc(t,e),t=new Xc(t,e+1);let r=Jo();return this.ws.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Xc(e,0),t=this.fs.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Xc{constructor(e,t){this.key=e,this.As=t}static ds(e,t){return ai.comparator(e.key,t.key)||Jr(e.As,t.As)}static _s(e,t){return Jr(e.As,t.As)||ai.comparator(e.key,t.key)}}class Yc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.vs=1,this.Rs=new ps(Xc.ds)}checkEmpty(e){return bi.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.vs;this.vs++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new Ca(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.Rs=this.Rs.add(new Xc(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return bi.resolve(s)}lookupMutationBatch(e,t){return bi.resolve(this.Ps(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.bs(t+1),n=n<0?0:n;return bi.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return bi.resolve(0===this.mutationQueue.length?-1:this.vs-1)}getAllMutationBatches(e){return bi.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Xc(t,0),r=new Xc(t,Number.POSITIVE_INFINITY),i=[];return this.Rs.forEachInRange([n,r],e=>{var t=this.Ps(e.As);i.push(t)}),bi.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new ps(Jr);return t.forEach(e=>{var t=new Xc(e,0),n=new Xc(e,Number.POSITIVE_INFINITY);this.Rs.forEachInRange([t,n],e=>{r=r.add(e.As)})}),bi.resolve(this.Vs(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ai.isDocumentKey(i)||(i=i.child(""));var s=new Xc(new ai(i),0);let o=new ps(Jr);return this.Rs.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.As)),!0)},s),bi.resolve(this.Vs(o))}Vs(e){const n=[];return e.forEach(e=>{var t=this.Ps(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Br(0===this.Ss(r.batchId,"removed")),this.mutationQueue.shift();let i=this.Rs;return bi.forEach(r.mutations,e=>{var t=new Xc(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Rs=i})}Cn(e){}containsKey(e,t){var n=new Xc(t,0),n=this.Rs.firstAfterOrEqual(n);return bi.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,bi.resolve()}Ss(e,t){return this.bs(e)}bs(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Ps(e){var t=this.bs(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Jc{constructor(e){this.Ds=e,this.docs=new fs(ai.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Ds(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return bi.resolve(n?n.document.mutableCopy():Xs.newInvalidDocument(t))}getEntries(e,t){let n=$o;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Xs.newInvalidDocument(e))}),bi.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=$o;const s=t.path,o=new ai(s.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||pi(gi(o),n)<=0||(r.has(o.key)||Uo(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return bi.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Pr()}Cs(e,t){return bi.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Zc(this)}getSize(e){return bi.resolve(this.size)}}class Zc extends Oc{constructor(e){super(),this.os=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.os.addEntry(n,t)):this.os.removeEntry(e)}),bi.waitFor(r)}getFromCache(e,t){return this.os.getEntry(e,t)}getAllFromCache(e,t){return this.os.getEntries(e,t)}}class eh{constructor(e){this.persistence=e,this.xs=new zo(e=>Io(e),Eo),this.lastRemoteSnapshotVersion=ni.min(),this.highestTargetId=0,this.Ns=0,this.ks=new Wc,this.targetCount=0,this.Ms=Sc.kn()}forEachTarget(e,n){return this.xs.forEach((e,t)=>n(t)),bi.resolve()}getLastRemoteSnapshotVersion(e){return bi.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return bi.resolve(this.Ns)}allocateTargetId(e){return this.highestTargetId=this.Ms.next(),bi.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Ns&&(this.Ns=t),bi.resolve()}Fn(e){this.xs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Ms=new Sc(t),this.highestTargetId=t),e.sequenceNumber>this.Ns&&(this.Ns=e.sequenceNumber)}addTargetData(e,t){return this.Fn(t),this.targetCount+=1,bi.resolve()}updateTargetData(e,t){return this.Fn(t),bi.resolve()}removeTargetData(e,t){return this.xs.delete(t.target),this.ks.Is(t.targetId),--this.targetCount,bi.resolve()}removeTargets(n,r,i){let s=0;const o=[];return this.xs.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.xs.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),bi.waitFor(o).next(()=>s)}getTargetCount(e){return bi.resolve(this.targetCount)}getTargetData(e,t){var n=this.xs.get(t)||null;return bi.resolve(n)}addMatchingKeys(e,t,n){return this.ks.gs(t,n),bi.resolve()}removeMatchingKeys(t,e,n){this.ks.ps(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),bi.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.ks.Is(t),bi.resolve()}getMatchingKeysForTargetId(e,t){var n=this.ks.Es(t);return bi.resolve(n)}containsKey(e,t){return bi.resolve(this.ks.containsKey(t))}}class th{constructor(e,t){this.$s={},this.overlays={},this.Os=new Ri(0),this.Fs=!1,this.Fs=!0,this.referenceDelegate=e(this),this.Bs=new eh(this),this.indexManager=new ac,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Ls(e),new Jc(e)),this.serializer=new Du(t),this.qs=new Qc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Fs=!1,Promise.resolve()}get started(){return this.Fs}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Hc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.$s[e.toKey()];return n||(n=new Yc(t,this.referenceDelegate),this.$s[e.toKey()]=n),n}getTargetCache(){return this.Bs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.qs}runTransaction(e,t,n){Fr("MemoryPersistence","Starting transaction:",e);const r=new nh(this.Os.next());return this.referenceDelegate.Us(),n(r).next(e=>this.referenceDelegate.Ks(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gs(t,n){return bi.or(Object.values(this.$s).map(e=>()=>e.containsKey(t,n)))}}class nh extends vi{constructor(e){super(),this.currentSequenceNumber=e}}class rh{constructor(e){this.persistence=e,this.Qs=new Wc,this.js=null}static zs(e){return new rh(e)}get Ws(){if(this.js)return this.js;throw Pr()}addReference(e,t,n){return this.Qs.addReference(n,t),this.Ws.delete(n.toString()),bi.resolve()}removeReference(e,t,n){return this.Qs.removeReference(n,t),this.Ws.add(n.toString()),bi.resolve()}markPotentiallyOrphaned(e,t){return this.Ws.add(t.toString()),bi.resolve()}removeTarget(e,t){this.Qs.Is(t.targetId).forEach(e=>this.Ws.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Ws.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Us(){this.js=new Set}Ks(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return bi.forEach(this.Ws,e=>{const t=ai.fromPath(e);return this.Hs(n,t).next(e=>{e||r.removeEntry(t,ni.min())})}).next(()=>(this.js=null,r.apply(n)))}updateLimboDocument(e,t){return this.Hs(e,t).next(e=>{e?this.Ws.delete(t.toString()):this.Ws.add(t.toString())})}Ls(e){return 0}Hs(e,t){return bi.or([()=>bi.resolve(this.Qs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gs(e,t)])}}class ih{constructor(e){this.serializer=e}O(t,e,n,r){const i=new Ii("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Bi,{unique:!0}),s.createObjectStore("documentMutations"),sh(t),t.createObjectStore("remoteDocuments"));let o=bi.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),sh(t)),o=o.next(()=>function(){const e=i.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ni.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(o=o.next(()=>function(r,i){return i.store("mutations").j().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Bi,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return bi.waitFor(n)})}(t,i))),o=o.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(o=o.next(()=>this.Ys(i))),n<6&&6<=r&&(o=o.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.Xs(i)))),n<7&&7<=r&&(o=o.next(()=>this.Zs(i))),n<8&&8<=r&&(o=o.next(()=>this.ti(t,i))),n<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(o=o.next(()=>this.ei(i))),n<11&&11<=r&&(o=o.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(o=o.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:es});e.createIndex("collectionPathOverlayIndex",ts,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",ns,{unique:!1})}()})),n<13&&13<=r&&(o=o.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:Gi});e.createIndex("documentKeyIndex",zi),e.createIndex("collectionGroupIndex",$i)}()).next(()=>this.ni(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(o=o.next(()=>this.si(t,i))),n<15&&15<=r&&(o=o.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Xi}).createIndex("sequenceNumberIndex",Yi,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Ji}).createIndex("documentKeyIndex",Zi,{unique:!1})}(t))),o}Xs(t){let n=0;return t.store("remoteDocuments").X((e,t)=>{n+=wc(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Ys(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.j().next(e=>bi.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.j("userMutationsIndex",e).next(e=>bi.forEach(e,e=>{Br(e.userId===n.userId);var t=Ru(this.serializer,e);return vc(r,n.userId,t).next(()=>{})}))}))}Zs(e){const o=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.X((e,t)=>{const n=new ii(e),r=[0,Oi(n)];s.push(o.get(r).next(e=>e?bi.resolve():(e=>o.put({targetId:0,path:Oi(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>bi.waitFor(s))})}ti(e,t){e.createObjectStore("collectionParents",{keyPath:Wi});const n=t.store("collectionParents"),r=new uc,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Oi(r)})}};return t.store("remoteDocuments").X({Y:!0},(e,t)=>{const n=new ii(e);return i(n.popLast())}).next(()=>t.store("documentMutations").X({Y:!0},([,e],t)=>{const n=Pi(e);return i(n.popLast())}))}ei(e){const r=e.store("targets");return r.X((e,t)=>{var n=Mu(t),n=Fu(this.serializer,n);return r.put(n)})}ni(e,s){const t=s.store("remoteDocuments"),o=[];return t.X((e,t)=>{const n=s.store("remoteDocumentsV14"),r=((i=t).document?new ai(ii.fromString(i.document.name).popFirst(5)):i.noDocument?ai.fromSegments(i.noDocument.path):i.unknownDocument?ai.fromSegments(i.unknownDocument.path):Pr()).path.toArray();var i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};o.push(n.put(i))}).next(()=>bi.waitFor(o))}si(e,s){const t=s.store("mutations"),o=Pc(this.serializer),a=new th(rh.zs,this.serializer.fe);return t.j().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Jo();Ru(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),bi.forEach(r,(e,t)=>{var n=new Nr(t),r=ju.de(this.serializer,n),i=a.getIndexManager(n),n=bc.de(n,this.serializer,i,a.referenceDelegate);return new Kc(o,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new us(s,Ri.ct),e).next()})})}}function sh(e){e.createObjectStore("targetDocuments",{keyPath:Qi}).createIndex("documentTargetsIndex",Hi,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Ki,{unique:!0}),e.createObjectStore("targetGlobal")}const oh="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 ah{constructor(e,t,n,r,i,s,o,a,u,c,h=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.ii=i,this.window=s,this.document=o,this.ri=u,this.oi=c,this.ui=h,this.Os=null,this.Fs=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.ai=null,this.hi=null,this.li=Number.NEGATIVE_INFINITY,this.fi=e=>Promise.resolve(),!ah.D())throw new Ur(qr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new Fc(this,r),this.di=t+"main",this.serializer=new Du(a),this.wi=new Ei(this.di,this.ui,new ih(this.serializer)),this.Bs=new xc(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Pc(this.serializer),this.qs=new Bu,this.window&&this.window.localStorage?this._i=this.window.localStorage:(this._i=null,!1===c&&Lr("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 Ur(qr.FAILED_PRECONDITION,oh);return this.gi(),this.yi(),this.pi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Bs.getHighestSequenceNumber(e))}).then(e=>{this.Os=new Ri(e,this.ri)}).then(()=>{this.Fs=!0}).catch(e=>(this.wi&&this.wi.close(),Promise.reject(e)))}Ii(t){return this.fi=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.wi.B(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.ii.enqueueAndForget(async()=>{this.started&&await this.mi()}))}mi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>ch(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Ti(t).next(e=>{e||(this.isPrimary=!1,this.ii.enqueueRetryable(()=>this.fi(!1)))})}).next(()=>this.Ei(t)).next(e=>this.isPrimary&&!e?this.Ai(t).next(()=>!1):!!e&&this.vi(t).next(()=>!0))).catch(e=>{if(Si(e))return Fr("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Fr("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.ii.enqueueRetryable(()=>this.fi(e)),this.isPrimary=e})}Ti(e){return uh(e).get("owner").next(e=>bi.resolve(this.Ri(e)))}Pi(e){return ch(e).delete(this.clientId)}async bi(){if(this.isPrimary&&!this.Vi(this.li,18e5)){this.li=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=cs(e,"clientMetadata");return r.j().next(e=>{const t=this.Si(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return bi.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this._i)for(const t of e)this._i.removeItem(this.Di(t.clientId))}}pi(){this.hi=this.ii.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.mi().then(()=>this.bi()).then(()=>this.pi()))}Ri(e){return!!e&&e.ownerId===this.clientId}Ei(t){return this.oi?bi.resolve(!0):uh(t).get("owner").next(e=>{if(null!==e&&this.Vi(e.leaseTimestampMs,5e3)&&!this.Ci(e.ownerId)){if(this.Ri(e)&&this.networkEnabled)return!0;if(!this.Ri(e)){if(!e.allowTabSynchronization)throw new Ur(qr.FAILED_PRECONDITION,oh);return!1}}return!(!this.networkEnabled||!this.inForeground)||ch(t).j().next(e=>void 0===this.Si(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&Fr("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Fs=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Ni(),this.ki(),await this.wi.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new us(e,Ri.ct);return this.Ai(t).next(()=>this.Pi(t))}),this.wi.close(),this.Mi()}Si(e,t){return e.filter(e=>this.Vi(e.updateTimeMs,t)&&!this.Ci(e.clientId))}$i(){return this.runTransaction("getActiveClients","readonly",e=>ch(e).j().next(e=>this.Si(e,18e5).map(e=>e.clientId)))}get started(){return this.Fs}getMutationQueue(e,t){return bc.de(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Bs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new hc(e,this.serializer.fe.databaseId)}getDocumentOverlayCache(e){return ju.de(this.serializer,e)}getBundleCache(){return this.qs}runTransaction(t,n,r){Fr("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",e=15===(e=this.ui)?as:14===e?os:13===e?ss:12===e?is:11===e?rs:void Pr();let s;return this.wi.runTransaction(t,i,e,e=>(s=new us(e,this.Os?this.Os.next():Ri.ct),"readwrite-primary"===n?this.Ti(s).next(e=>!!e||this.Ei(s)).next(e=>{if(!e)throw Lr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.ii.enqueueRetryable(()=>this.fi(!1)),new Ur(qr.FAILED_PRECONDITION,yi);return r(s)}).next(e=>this.vi(s).next(()=>e)):this.Oi(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}Oi(e){return uh(e).get("owner").next(e=>{if(null!==e&&this.Vi(e.leaseTimestampMs,5e3)&&!this.Ci(e.ownerId)&&!this.Ri(e)&&!(this.oi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new Ur(qr.FAILED_PRECONDITION,oh)})}vi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return uh(e).put("owner",t)}static D(){return Ei.D()}Ai(e){const t=uh(e);return t.get("owner").next(e=>this.Ri(e)?(Fr("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):bi.resolve())}Vi(e,t){var n=Date.now();return!(e<n-t||n<e&&(Lr(`Detected an update time that is in the future: ${e} > ${n}`),1))}gi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ai=()=>{this.ii.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.mi()))},this.document.addEventListener("visibilitychange",this.ai),this.inForeground="visible"===this.document.visibilityState)}Ni(){this.ai&&(this.document.removeEventListener("visibilitychange",this.ai),this.ai=null)}yi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();var e=/(?:Version|Mobile)\/1[456]/;h()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.ii.enterRestrictedMode(!0),this.ii.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}ki(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Ci(e){var t;try{var n=null!==(null===(t=this._i)||void 0===t?void 0:t.getItem(this.Di(e)));return Fr("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Lr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this._i)try{this._i.setItem(this.Di(this.clientId),String(Date.now()))}catch(e){Lr("Failed to set zombie client id.",e)}}Mi(){if(this._i)try{this._i.removeItem(this.Di(this.clientId))}catch(e){}}Di(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function uh(e){return cs(e,"owner")}function ch(e){return cs(e,"clientMetadata")}function hh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class lh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Fi=n,this.Bi=r}static Li(e,t){let n=Jo(),r=Jo();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new lh(e,t.fromCache,n,r)}}class dh{constructor(){this.qi=!1}initialize(e,t){this.Ui=e,this.indexManager=t,this.qi=!0}getDocumentsMatchingQuery(t,n,r,i){return this.Ki(t,n).next(e=>e||this.Gi(t,n,i,r)).next(e=>e||this.Qi(t,n))}Ki(i,s){if(No(s))return bi.resolve(null);let t=Lo(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Vo(s,null,"F"),t=Lo(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=Jo(...e);return this.Ui.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.ji(s,n);return this.zi(s,t,r,e.readTime)?this.Ki(i,Vo(s,null,"F")):this.Wi(i,t,s,e)}))})))}Gi(n,r,i,s){return No(r)||s.isEqual(ni.min())?this.Qi(n,r):this.Ui.getDocuments(n,i).next(e=>{var t=this.ji(r,e);return this.zi(r,t,i,s)?this.Qi(n,r):(Mr()<=l.DEBUG&&Fr("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),qo(r)),this.Wi(n,t,r,fi(s,-1)))})}ji(n,e){let r=new ps(Go(n));return e.forEach((e,t)=>{Uo(n,t)&&(r=r.add(t))}),r}zi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Qi(e,t){return Mr()<=l.DEBUG&&Fr("QueryEngine","Using full collection scan to execute query:",qo(t)),this.Ui.getDocumentsMatchingQuery(e,t,mi.min())}Wi(e,n,t,r){return this.Ui.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class fh{constructor(e,t,n,r){this.persistence=e,this.Hi=t,this.serializer=r,this.Ji=new fs(Jr),this.Yi=new zo(e=>Io(e),Eo),this.Xi=new Map,this.Zi=e.getRemoteDocumentCache(),this.Bs=e.getTargetCache(),this.qs=e.getBundleCache(),this.tr(n)}tr(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Kc(this.Zi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Zi.setIndexManager(this.indexManager),this.Hi.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Ji))}}function gh(e,t,n,r){return new fh(e,t,n,r)}async function mh(e,t){const o=e;return o.persistence.runTransaction("Handle user change","readonly",i=>{let s;return o.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,o.tr(t),o.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Jo();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return o.localDocuments.getDocuments(i,r).next(e=>({er:e,removedBatchIds:t,addedBatchIds:n}))})})}function ph(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Bs.getLastRemoteSnapshotVersion(e))}function yh(e,c){const h=e,l=c.snapshotVersion;let d=h.Ji;return h.persistence.runTransaction("Apply remote event","readwrite-primary",a=>{const e=h.Zi.newChangeBuffer({trackRemovals:!0});d=h.Ji;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Bs.removeMatchingKeys(a,t.removedDocuments,n).next(()=>h.Bs.addMatchingKeys(a,t.addedDocuments,n)));let e=r.withSequenceNumber(a.currentSequenceNumber);var i,s,o;null!==c.targetMismatches.get(n)?e=e.withResumeToken(Is.EMPTY_BYTE_STRING,ni.min()).withLastLimboFreeSnapshotVersion(ni.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),i=r,s=e,o=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||u.push(h.Bs.updateTargetData(a,e))}});let t=$o,n=Jo();if(c.documentUpdates.forEach(e=>{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(a,e))}),u.push(vh(a,e,c.documentUpdates).next(e=>{t=e.nr,n=e.sr})),!l.isEqual(ni.min())){const c=h.Bs.getLastRemoteSnapshotVersion(a).next(e=>h.Bs.setTargetsMetadata(a,a.currentSequenceNumber,l));u.push(c)}return bi.waitFor(u).next(()=>e.apply(a)).next(()=>h.localDocuments.getLocalViewOfDocuments(a,t,n)).next(()=>t)}).then(e=>(h.Ji=d,e))}function vh(e,s,t){let n=Jo(),o=Jo();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=$o;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(o=o.add(e)),t.isNoDocument()&&t.version.isEqual(ni.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):Fr("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{nr:i,sr:o}})}function wh(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Bs.getTargetData(t,r).next(e=>e?(n=e,bi.resolve(n)):i.Bs.allocateTargetId(t).next(e=>(n=new xu(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Bs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Ji.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Ji=i.Ji.insert(e.targetId,e),i.Yi.set(r,e.targetId)),e})}async function bh(e,t,n){const r=e,i=r.Ji.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!Si(e))throw e;Fr("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Ji=r.Ji.remove(t),r.Yi.delete(i.target)}function Ih(e,n,r){const i=e;let s=ni.min(),o=Jo();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.Yi.get(n);return void 0!==i?bi.resolve(r.Ji.get(i)):r.Bs.getTargetData(t,n)}(i,t,Lo(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Bs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>i.Hi.getDocumentsMatchingQuery(t,n,r?s:ni.min(),r?o:Jo())).next(e=>(Th(i,jo(n),e),{documents:e,ir:o})))}function Eh(e,t){const n=e,r=n.Bs,i=n.Ji.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.le(e,t).next(e=>e?e.target:null))}function _h(e,t){const n=e,r=n.Xi.get(t)||ni.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.Zi.getAllFromCollectionGroup(e,t,fi(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Th(n,t,e),e))}function Th(e,t,n){let r=e.Xi.get(t)||ni.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.Xi.set(t,r)}function Sh(e,t){return`firestore_clients_${e}_${t}`}function xh(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Dh(e,t){return`firestore_targets_${e}_${t}`}class Ah{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static ar(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new Ur(r.error.code,r.error.message))),s?new Ah(e,t,r.state,i):(Lr("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}hr(){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 Ch{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static ar(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new Ur(n.error.code,n.error.message))),i?new Ch(e,n.state,r):(Lr("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}hr(){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 Nh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static ar(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Zo;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Li(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new Nh(e,i):(Lr("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class kh{constructor(e,t){this.clientId=e,this.onlineState=t}static ar(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new kh(t.clientId,t.onlineState):(Lr("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Rh{constructor(){this.activeTargetIds=Zo}lr(e){this.activeTargetIds=this.activeTargetIds.add(e)}dr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}hr(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Mh{constructor(e,t,n,r,i){this.window=e,this.ii=t,this.persistenceKey=n,this.wr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this._r=this.mr.bind(this),this.gr=new fs(Jr),this.started=!1,this.yr=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.pr=Sh(this.persistenceKey,this.wr),this.Ir=`firestore_sequence_number_${this.persistenceKey}`,this.gr=this.gr.insert(this.wr,new Rh),this.Tr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Er=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Ar=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.vr=`firestore_online_state_${this.persistenceKey}`,this.Rr=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this._r)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.$i();for(const n of e)if(n!==this.wr){const e=this.getItem(Sh(this.persistenceKey,n));var t;!e||(t=Nh.ar(n,e))&&(this.gr=this.gr.insert(t.clientId,t))}this.Pr();const n=this.storage.getItem(this.vr);if(n){const e=this.br(n);e&&this.Vr(e)}for(const e of this.yr)this.mr(e);this.yr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ir,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Sr(this.gr)}isActiveQueryTarget(n){let r=!1;return this.gr.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Dr(e,"pending")}updateMutationState(e,t,n){this.Dr(e,t,n),this.Cr(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Dh(this.persistenceKey,e)))||(n=Ch.ar(e,n))&&(t=n.state)),this.Nr.lr(e),this.Pr(),t}removeLocalQueryTarget(e){this.Nr.dr(e),this.Pr()}isLocalQueryTarget(e){return this.Nr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Dh(this.persistenceKey,e))}updateQueryState(e,t,n){this.kr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Cr(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Mr(e)}notifyBundleLoaded(e){this.$r(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this._r),this.removeItem(this.pr),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Fr("SharedClientState","READ",e,t),t}setItem(e,t){Fr("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Fr("SharedClientState","REMOVE",e),this.storage.removeItem(e)}mr(e){const i=e;i.storageArea===this.storage&&(Fr("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.pr?this.ii.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.Tr.test(i.key)){if(null==i.newValue){var e=this.Or(i.key);return this.Fr(e,null)}e=this.Br(i.key,i.newValue);if(e)return this.Fr(e.clientId,e)}else if(this.Er.test(i.key)){if(null!==i.newValue){var t=this.Lr(i.key,i.newValue);if(t)return this.qr(t)}}else if(this.Ar.test(i.key)){if(null!==i.newValue){t=this.Ur(i.key,i.newValue);if(t)return this.Kr(t)}}else if(i.key===this.vr){if(null!==i.newValue){var n=this.br(i.newValue);if(n)return this.Vr(n)}}else if(i.key===this.Ir){n=function(e){let t=Ri.ct;if(null!=e)try{var n=JSON.parse(e);Br("number"==typeof n),t=n}catch(e){Lr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==Ri.ct&&this.sequenceNumberHandler(n)}else if(i.key===this.Rr){const r=this.Gr(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Qr(e)))}}else this.yr.push(i)}):Lr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Nr(){return this.gr.get(this.wr)}Pr(){this.setItem(this.pr,this.Nr.hr())}Dr(e,t,n){const r=new Ah(this.currentUser,e,t,n),i=xh(this.persistenceKey,this.currentUser,e);this.setItem(i,r.hr())}Cr(e){var t=xh(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Mr(e){var t={clientId:this.wr,onlineState:e};this.storage.setItem(this.vr,JSON.stringify(t))}kr(e,t,n){const r=Dh(this.persistenceKey,e),i=new Ch(e,t,n);this.setItem(r,i.hr())}$r(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Rr,t)}Or(e){var t=this.Tr.exec(e);return t?t[1]:null}Br(e,t){var n=this.Or(e);return Nh.ar(n,t)}Lr(e,t){var n=this.Er.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Ah.ar(new Nr(n),r,t)}Ur(e,t){var n=this.Ar.exec(e),n=Number(n[1]);return Ch.ar(n,t)}br(e){return kh.ar(e)}Gr(e){return JSON.parse(e)}async qr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.jr(e.batchId,e.state,e.error);Fr("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Kr(e){return this.syncEngine.zr(e.targetId,e.state,e.error)}Fr(e,t){const n=t?this.gr.insert(e,t):this.gr.remove(e),r=this.Sr(this.gr),i=this.Sr(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.Wr(s,o).then(()=>{this.gr=n})}Vr(e){this.gr.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Sr(e){let n=Zo;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Fh{constructor(){this.Hr=new Rh,this.Jr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Hr.lr(e),this.Jr[e]||"not-current"}updateQueryState(e,t,n){this.Jr[e]=t}removeLocalQueryTarget(e){this.Hr.dr(e)}isLocalQueryTarget(e){return this.Hr.activeTargetIds.has(e)}clearQueryState(e){delete this.Jr[e]}getAllActiveQueryTargets(){return this.Hr.activeTargetIds}isActiveQueryTarget(e){return this.Hr.activeTargetIds.has(e)}start(){return this.Hr=new Rh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Lh{Yr(e){}shutdown(){}}class Oh{constructor(){this.Xr=()=>this.Zr(),this.eo=()=>this.no(),this.so=[],this.io()}Yr(e){this.so.push(e)}shutdown(){window.removeEventListener("online",this.Xr),window.removeEventListener("offline",this.eo)}io(){window.addEventListener("online",this.Xr),window.addEventListener("offline",this.eo)}Zr(){Fr("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.so)e(0)}no(){Fr("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.so)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Vh=null;function Ph(){return null===Vh?Vh=268435456+Math.round(2147483648*Math.random()):Vh++,"0x"+Vh.toString(16)}const Bh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class qh{constructor(e){this.ro=e.ro,this.oo=e.oo}uo(e){this.co=e}ao(e){this.ho=e}onMessage(e){this.lo=e}close(){this.oo()}send(e){this.ro(e)}fo(){this.co()}wo(e){this.ho(e)}_o(e){this.lo(e)}}const Uh="WebChannelConnection";class jh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.mo=t+"://"+e.host,this.yo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get po(){return!1}Io(t,e,n,r,i){const s=Ph(),o=this.To(t,e);Fr("RestConnection",`Sending RPC '${t}' ${s}:`,o,n);var a={};return this.Eo(a,r,i),this.Ao(t,o,a,n).then(e=>(Fr("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw Or("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",o,"request:",n),e})}vo(e,t,n,r,i,s){return this.Io(e,t,n,r,i)}Eo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+kr,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}To(e,t){var n=Bh[e];return`${this.mo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Ao(a,t,n,r){const u=Ph();return new Promise((i,s)=>{const o=new xr;o.setWithCredentials(!0),o.listenOnce(br.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case wr.NO_ERROR:var e=o.getResponseJson();Fr(Uh,`XHR for RPC '${a}' ${u} received:`,JSON.stringify(e)),i(e);break;case wr.TIMEOUT:Fr(Uh,`RPC '${a}' ${u} timed out`),s(new Ur(qr.DEADLINE_EXCEEDED,"Request time out"));break;case wr.HTTP_ERROR:var t=o.getStatus();if(Fr(Uh,`RPC '${a}' ${u} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const a=(r=n.status.toLowerCase().replace(/_/g,"-"),0<=Object.values(qr).indexOf(r)?r:qr.UNKNOWN);s(new Ur(a,n.message))}else s(new Ur(qr.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new Ur(qr.UNAVAILABLE,"Connection failed."));break;default:Pr()}}finally{Fr(Uh,`RPC '${a}' ${u} completed.`)}var r});var e=JSON.stringify(r);Fr(Uh,`RPC '${a}' ${u} sending request:`,r),o.send(t,"POST",e,n,15)})}Ro(i,e,t){const s=Ph(),n=[this.mo,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=new Qn,o=vr(),a={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(a.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(a.xmlHttpFactory=new Tr({})),this.Eo(a.initMessageHeaders,e,t),a.encodeInitMessageHeaders=!0;var c=n.join("");Fr(Uh,`Creating RPC '${i}' stream ${s}: ${c}`,a);const h=r.createWebChannel(c,a);let l=!1,d=!1;const f=new qh({ro:e=>{d?Fr(Uh,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(l||(Fr(Uh,`Opening RPC '${i}' stream ${s} transport.`),h.open(),l=!0),Fr(Uh,`RPC '${i}' stream ${s} sending:`,e),h.send(e))},oo:()=>h.close()}),g=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return g(h,Sr.EventType.OPEN,()=>{d||Fr(Uh,`RPC '${i}' stream ${s} transport opened.`)}),g(h,Sr.EventType.CLOSE,()=>{d||(d=!0,Fr(Uh,`RPC '${i}' stream ${s} transport closed`),f.wo())}),g(h,Sr.EventType.ERROR,e=>{d||(d=!0,Or(Uh,`RPC '${i}' stream ${s} transport errored:`,e),f.wo(new Ur(qr.UNAVAILABLE,"The operation could not be completed")))}),g(h,Sr.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];Br(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Fr(Uh,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=yr[e];if(void 0!==t)return Fa(t)}(n),t=r.message;void 0===e&&(e=qr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,f.wo(new Ur(e,t)),h.close()}else Fr(Uh,`RPC '${i}' stream ${s} received:`,e),f._o(e)}}),g(o,Ir.STAT_EVENT,e=>{e.stat===Er?Fr(Uh,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===_r&&Fr(Uh,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{f.fo()},0),f}}function Gh(){return"undefined"!=typeof window?window:null}function zh(){return"undefined"!=typeof document?document:null}function $h(e){return new tu(e,!0)}class Kh{constructor(e,t,n=1e3,r=1.5,i=6e4){this.ii=e,this.timerId=t,this.Po=n,this.bo=r,this.Vo=i,this.So=0,this.Do=null,this.Co=Date.now(),this.reset()}reset(){this.So=0}xo(){this.So=this.Vo}No(e){this.cancel();var t=Math.floor(this.So+this.ko()),n=Math.max(0,Date.now()-this.Co),r=Math.max(0,t-n);0<r&&Fr("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.So} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Do=this.ii.enqueueAfterDelay(this.timerId,r,()=>(this.Co=Date.now(),e())),this.So*=this.bo,this.So<this.Po&&(this.So=this.Po),this.So>this.Vo&&(this.So=this.Vo)}Mo(){null!==this.Do&&(this.Do.skipDelay(),this.Do=null)}cancel(){null!==this.Do&&(this.Do.cancel(),this.Do=null)}ko(){return(Math.random()-.5)*this.So}}class Qh{constructor(e,t,n,r,i,s,o,a){this.ii=e,this.$o=n,this.Oo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Fo=0,this.Bo=null,this.Lo=null,this.stream=null,this.qo=new Kh(e,t)}Uo(){return 1===this.state||5===this.state||this.Ko()}Ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Go()}async stop(){this.Uo()&&await this.close(0)}Qo(){this.state=0,this.qo.reset()}jo(){this.Ko()&&null===this.Bo&&(this.Bo=this.ii.enqueueAfterDelay(this.$o,6e4,()=>this.zo()))}Wo(e){this.Ho(),this.stream.send(e)}async zo(){if(this.Ko())return this.close(0)}Ho(){this.Bo&&(this.Bo.cancel(),this.Bo=null)}Jo(){this.Lo&&(this.Lo.cancel(),this.Lo=null)}async close(e,t){this.Ho(),this.Jo(),this.qo.cancel(),this.Fo++,4!==e?this.qo.reset():t&&t.code===qr.RESOURCE_EXHAUSTED?(Lr(t.toString()),Lr("Using maximum backoff delay to prevent overloading the backend."),this.qo.xo()):t&&t.code===qr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Yo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.ao(t)}Yo(){}auth(){this.state=1;const e=this.Xo(this.Fo),n=this.Fo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Fo===n&&this.Zo(e,t)},t=>{e(()=>{var e=new Ur(qr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.tu(e)})})}Zo(e,t){const n=this.Xo(this.Fo);this.stream=this.eu(e,t),this.stream.uo(()=>{n(()=>(this.state=2,this.Lo=this.ii.enqueueAfterDelay(this.Oo,1e4,()=>(this.Ko()&&(this.state=3),Promise.resolve())),this.listener.uo()))}),this.stream.ao(e=>{n(()=>this.tu(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Go(){this.state=5,this.qo.No(async()=>{this.state=0,this.start()})}tu(e){return Fr("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Xo(t){return e=>{this.ii.enqueueAndForget(()=>this.Fo===t?e():(Fr("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class Hh extends Qh{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}eu(e,t){return this.connection.Ro("Listen",e,t)}onMessage(e){this.qo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:Pr(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.useProto3Json?(Br(void 0===f||"string"==typeof f),Is.fromBase64String(f||"")):(Br(void 0===f||f instanceof Uint8Array),Is.fromUint8Array(f||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(f=o).code?qr.UNKNOWN:Fa(f.code),new Ur(a,f.message||""));n=new Qa(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var s=cu(e,u.document.name),a=su(u.document.updateTime),c=u.document.createTime?su(u.document.createTime):ni.min(),h=new Ws({mapValue:{fields:u.document.fields}}),c=Xs.newFoundDocument(s,a,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new $a(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=cu(e,h.document),c=h.readTime?su(h.readTime):ni.min(),c=Xs.newNoDocument(u,c),h=h.removedTargetIds||[];n=new $a([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=cu(e,l.document),l=l.removedTargetIds||[];n=new $a([],l,d,null)}else{if(!("filter"in t))return Pr();{t.filter;const e=t.filter;e.targetId;var{count:l=0,unchangedNames:d}=e,l=new Ra(l,d),d=e.targetId;n=new Ka(d,l)}}var a,f;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ni.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?su(t.readTime):ni.min()}(e);return this.listener.nu(t,n)}su(e){const t={};t.database=du(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=_o(r)?{documents:vu(e,r)}:{query:wu(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=iu(e,t.resumeToken);const r=nu(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(ni.min())){n.readTime=ru(e,t.snapshotVersion.toTimestamp());const r=nu(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,r,r=(this.serializer,n=e,null==(r=function(){switch(n.purpose){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Pr()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Wo(t)}iu(e){const t={};t.database=du(this.serializer),t.removeTarget=e,this.Wo(t)}}class Wh extends Qh{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.ru=!1}get ou(){return this.ru}start(){this.ru=!1,this.lastStreamToken=void 0,super.start()}Yo(){this.ru&&this.uu([])}eu(e,t){return this.connection.Ro("Write",e,t)}onMessage(e){if(Br(!!e.streamToken),this.lastStreamToken=e.streamToken,this.ru){this.qo.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(Br(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?su(e.updateTime):su(t);return n.isEqual(ni.min())&&(n=su(t)),new ga(n,e.transformResults||[])}(e,i))):[]),n=su(e.commitTime);return this.listener.cu(n,t)}var r,i;return Br(!e.writeResults||0===e.writeResults.length),this.ru=!0,this.listener.au()}hu(){const e={};e.database=du(this.serializer),this.Wo(e)}uu(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>pu(this.serializer,e))};this.Wo(t)}}class Xh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.lu=!1}fu(){if(this.lu)throw new Ur(qr.FAILED_PRECONDITION,"The client has already been terminated.")}Io(n,r,i){return this.fu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Io(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===qr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Ur(qr.UNKNOWN,e.toString())})}vo(n,r,i,s){return this.fu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.vo(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===qr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Ur(qr.UNKNOWN,e.toString())})}terminate(){this.lu=!0}}class Yh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.wu=0,this._u=null,this.mu=!0}gu(){0===this.wu&&(this.yu("Unknown"),this._u=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._u=null,this.pu("Backend didn't respond within 10 seconds."),this.yu("Offline"),Promise.resolve())))}Iu(e){"Online"===this.state?this.yu("Unknown"):(this.wu++,1<=this.wu&&(this.Tu(),this.pu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.yu("Offline")))}set(e){this.Tu(),this.wu=0,"Online"===e&&(this.mu=!1),this.yu(e)}yu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}pu(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.mu?(Lr(t),this.mu=!1):Fr("OnlineStateTracker",t)}Tu(){null!==this._u&&(this._u.cancel(),this._u=null)}}class Jh{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Eu=[],this.Au=new Map,this.vu=new Set,this.Ru=[],this.Pu=i,this.Pu.Yr(e=>{n.enqueueAndForget(async()=>{al(this)&&(Fr("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.vu.add(4),await el(t),t.bu.set("Unknown"),t.vu.delete(4),await Zh(t)}(this))})}),this.bu=new Yh(n,r)}}async function Zh(e){if(al(e))for(const t of e.Ru)await t(!0)}async function el(e){for(const t of e.Ru)await t(!1)}function tl(e,t){const n=e;n.Au.has(t.targetId)||(n.Au.set(t.targetId,t),ol(n)?sl(n):pl(n).Ko()&&rl(n,t))}function nl(e,t){const n=e,r=pl(n);n.Au.delete(t),r.Ko()&&il(n,t),0===n.Au.size&&(r.Ko()?r.jo():al(n)&&n.bu.set("Unknown"))}function rl(e,t){var n;e.Vu.qt(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(ni.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),pl(e).su(t)}function il(e,t){e.Vu.qt(t),pl(e).iu(t)}function sl(t){t.Vu=new Wa({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),le:e=>t.Au.get(e)||null,ue:()=>t.datastore.serializer.databaseId}),pl(t).start(),t.bu.gu()}function ol(e){return al(e)&&!pl(e).Uo()&&0<e.Au.size}function al(e){return 0===e.vu.size}function ul(e){e.Vu=void 0}async function cl(e,t,n){if(!Si(t))throw t;e.vu.add(1),await el(e),e.bu.set("Offline"),n=n||(()=>ph(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Fr("RemoteStore","Retrying IndexedDB access"),await n(),e.vu.delete(1),await Zh(e)})}function hl(t,n){return n().catch(e=>cl(t,e,n))}async function ll(e){const t=e,n=yl(t);let r=0<t.Eu.length?t.Eu[t.Eu.length-1].batchId:-1;for(;al(i=t)&&i.Eu.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.Eu.length&&n.jo();break}r=e.batchId,function(e,t){e.Eu.push(t);const n=yl(e);n.Ko()&&n.ou&&n.uu(t.mutations)}(t,e)}catch(e){await cl(t,e)}var i;dl(t)&&fl(t)}function dl(e){return al(e)&&!yl(e).Uo()&&0<e.Eu.length}function fl(e){yl(e).start()}async function gl(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Fr("RemoteStore","RemoteStore received new credentials");var r=al(n);n.vu.add(3),await el(n),r&&n.bu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.vu.delete(3),await Zh(n)}async function ml(e,t){const n=e;t?(n.vu.delete(2),await Zh(n)):(n.vu.add(2),await el(n),n.bu.set("Unknown"))}function pl(t){return t.Su||(t.Su=function(e,t,n){const r=e;return r.fu(),new Hh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{uo:(async function(n){n.Au.forEach((e,t)=>{rl(n,e)})}).bind(null,t),ao:(async function(e,t){ul(e),ol(e)?(e.bu.Iu(t),sl(e)):e.bu.set("Unknown")}).bind(null,t),nu:(async function(e,r,t){if(e.bu.set("Online"),r instanceof Qa&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.Au.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.Au.delete(n),e.Vu.removeTarget(n))}(e)}catch(t){Fr("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await cl(e,t)}else if(r instanceof $a?e.Vu.Ht(r):r instanceof Ka?e.Vu.ne(r):e.Vu.Xt(r),!t.isEqual(ni.min()))try{const r=await ph(e.localStore);0<=t.compareTo(r)&&await function(i,r){const e=i.Vu.ce(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.Au.get(t);n&&i.Au.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.Au.get(e);var r;n&&(i.Au.set(e,n.withResumeToken(Is.EMPTY_BYTE_STRING,n.snapshotVersion)),il(i,e),r=new xu(n.target,e,t,n.sequenceNumber),rl(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){Fr("RemoteStore","Failed to raise snapshot:",r),await cl(e,r)}}).bind(null,t)}),t.Ru.push(async e=>{e?(t.Su.Qo(),ol(t)?sl(t):t.bu.set("Unknown")):(await t.Su.stop(),ul(t))})),t.Su}function yl(t){return t.Du||(t.Du=function(e,t,n){const r=e;return r.fu(),new Wh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{uo:(async function(e){yl(e).hu()}).bind(null,t),ao:(async function(e,t){t&&yl(e).ou&&await async function(e,t){if(Ma(n=t.code)&&n!==qr.ABORTED){const n=e.Eu.shift();yl(e).Qo(),await hl(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await ll(e)}var n}(e,t),dl(e)&&fl(e)}).bind(null,t),au:(async function(e){const t=yl(e);for(const n of e.Eu)t.uu(n.mutations)}).bind(null,t),cu:(async function(e,t,n){const r=e.Eu.shift(),i=Na.from(r,t,n);await hl(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await ll(e)}).bind(null,t)}),t.Ru.push(async e=>{e?(t.Du.Qo(),await ll(t)):(await t.Du.stop(),0<t.Eu.length&&(Fr("RemoteStore",`Stopping write stream with ${t.Eu.length} pending writes`),t.Eu=[]))})),t.Du}class vl{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new jr,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new vl(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Ur(qr.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 wl(e,t){if(Lr("AsyncQueue",`${t}: ${e}`),Si(e))return new Ur(qr.UNAVAILABLE,`${t}: ${e}`);throw e}class bl{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ai.comparator(e.key,t.key):(e,t)=>ai.comparator(e.key,t.key),this.keyedMap=Qo(),this.sortedSet=new fs(this.comparator)}static emptySet(e){return new bl(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof bl))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new bl;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Il{constructor(){this.Cu=new fs(ai.comparator)}track(e){var t=e.doc.key,n=this.Cu.get(t);!n||0!==e.type&&3===n.type?this.Cu=this.Cu.insert(t,e):3===e.type&&1!==n.type?this.Cu=this.Cu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Cu=this.Cu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Cu=this.Cu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Cu=this.Cu.remove(t):1===e.type&&2===n.type?this.Cu=this.Cu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Cu=this.Cu.insert(t,{type:2,doc:e.doc}):Pr()}xu(){const n=[];return this.Cu.inorderTraversal((e,t)=>{n.push(t)}),n}}class El{constructor(e,t,n,r,i,s,o,a,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new El(e,t,bl.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Po(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class _l{constructor(){this.Nu=void 0,this.listeners=[]}}class Tl{constructor(){this.queries=new zo(e=>Bo(e),Po),this.onlineState="Unknown",this.ku=new Set}}async function Sl(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new _l),i)try{s.Nu=await n.onListen(r)}catch(e){const n=wl(e,`Initialization of query '${qo(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Mu(n.onlineState),!s.Nu||t.$u(s.Nu)&&Dl(n)}async function xl(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Dl(e){e.ku.forEach(e=>{e.next()})}class Al{constructor(e,t,n){this.query=e,this.Ou=t,this.Fu=!1,this.Bu=null,this.onlineState="Unknown",this.options=n||{}}$u(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new El(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Fu?this.Lu(e)&&(this.Ou.next(e),t=!0):this.qu(e,this.onlineState)&&(this.Uu(e),t=!0),this.Bu=e,t}onError(e){this.Ou.error(e)}Mu(e){this.onlineState=e;let t=!1;return this.Bu&&!this.Fu&&this.qu(this.Bu,e)&&(this.Uu(this.Bu),t=!0),t}qu(e,t){return!e.fromCache||(!this.options.Ku||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Lu(e){if(0<e.docChanges.length)return!0;var t=this.Bu&&this.Bu.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Uu(e){e=El.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Fu=!0,this.Ou.next(e)}}class Cl{constructor(e,t){this.Gu=e,this.byteLength=t}Qu(){return"metadata"in this.Gu}}class Nl{constructor(e){this.serializer=e}rr(e){return cu(this.serializer,e)}ur(e){return e.metadata.exists?mu(this.serializer,e.document,!1):Xs.newNoDocument(this.rr(e.metadata.name),this.cr(e.metadata.readTime))}cr(e){return su(e)}}class kl{constructor(e,t,n){this.ju=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Rl(e)}zu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.Gu.namedQuery)this.queries.push(e.Gu.namedQuery);else if(e.Gu.documentMetadata){this.documents.push({metadata:e.Gu.documentMetadata}),e.Gu.documentMetadata.exists||++t;const n=ii.fromString(e.Gu.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.Gu.document&&(this.documents[this.documents.length-1].document=e.Gu.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Wu(e){const t=new Map,n=new Nl(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.rr(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Jo()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Jo(),o=$o;for(const e of n){const n=t.rr(e.metadata.name);e.document&&(s=s.add(n));const c=t.ur(e);c.setReadTime(t.cr(e.metadata.readTime)),o=o.insert(n,c)}const a=i.Zi.newChangeBuffer({trackRemovals:!0}),u=await wh(i,(r=r,Lo(Co(ii.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>vh(t,a,o).next(e=>(a.apply(t),e)).next(e=>i.Bs.removeMatchingKeysForTargetId(t,u.targetId).next(()=>i.Bs.addMatchingKeys(t,s,u.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.nr,e.sr)).next(()=>e.nr)))}(this.localStore,new Nl(this.serializer),this.documents,this.ju.id),t=this.Wu(this.documents);for(const e of this.queries)await async function(e,n,r=Jo()){const i=await wh(e,Lo(Lu(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=su(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.qs.saveNamedQuery(e,n);t=i.withResumeToken(Is.EMPTY_BYTE_STRING,t);return s.Ji=s.Ji.insert(t.targetId,t),s.Bs.updateTargetData(e,t).next(()=>s.Bs.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Bs.addMatchingKeys(e,r,i.targetId)).next(()=>s.qs.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Hu:this.collectionGroups,Ju:e}}}function Rl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Ml{constructor(e){this.key=e}}class Fl{constructor(e){this.key=e}}class Ll{constructor(e,t){this.query=e,this.Yu=t,this.Xu=null,this.hasCachedResults=!1,this.current=!1,this.Zu=Jo(),this.mutatedKeys=Jo(),this.tc=Go(e),this.ec=new bl(this.tc)}get nc(){return this.Yu}sc(e,t){const a=t?t.ic:new Il,u=(t||this).ec;let c=(t||this).mutatedKeys,h=u,l=!1;const d="F"===this.query.limitType&&u.size===this.query.limit?u.last():null,f="L"===this.query.limitType&&u.size===this.query.limit?u.first():null;if(e.inorderTraversal((e,t)=>{const n=u.get(e),r=Uo(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let o=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(a.track({type:3,doc:r}),o=!0):this.rc(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.tc(r,d)||f&&this.tc(r,f)<0)&&(l=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||f)&&(l=!0)),o&&(c=r?(h=h.add(r),s?c.add(e):c.delete(e)):(h=h.delete(e),c.delete(e)))}),null!==this.query.limit)for(;h.size>this.query.limit;){const e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),c=c.delete(e.key),a.track({type:1,doc:e})}return{ec:h,ic:a,zi:l,mutatedKeys:c}}rc(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.ec;this.ec=e.ec,this.mutatedKeys=e.mutatedKeys;const i=e.ic.xu();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Pr()}};return n(e)-n(t)}(e.type,t.type)||this.tc(e.doc,t.doc)),this.oc(n);var s=t?this.uc():[],o=0===this.Zu.size&&this.current?1:0,a=o!==this.Xu;return this.Xu=o,0!==i.length||a?{snapshot:new El(this.query,e.ec,r,i,e.mutatedKeys,0==o,a,!1,!!n&&0<n.resumeToken.approximateByteSize()),cc:s}:{cc:s}}Mu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ec:this.ec,ic:new Il,mutatedKeys:this.mutatedKeys,zi:!1},!1)):{cc:[]}}ac(e){return!this.Yu.has(e)&&!!this.ec.has(e)&&!this.ec.get(e).hasLocalMutations}oc(e){e&&(e.addedDocuments.forEach(e=>this.Yu=this.Yu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Yu=this.Yu.delete(e)),this.current=e.current)}uc(){if(!this.current)return[];const t=this.Zu;this.Zu=Jo(),this.ec.forEach(e=>{this.ac(e.key)&&(this.Zu=this.Zu.add(e.key))});const n=[];return t.forEach(e=>{this.Zu.has(e)||n.push(new Fl(e))}),this.Zu.forEach(e=>{t.has(e)||n.push(new Ml(e))}),n}hc(e){this.Yu=e.ir,this.Zu=Jo();var t=this.sc(e.documents);return this.applyChanges(t,!0)}lc(){return El.fromInitialDocuments(this.query,this.ec,this.mutatedKeys,0===this.Xu,this.hasCachedResults)}}class Ol{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Vl{constructor(e){this.key=e,this.fc=!1}}class Pl{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.dc={},this.wc=new zo(e=>Bo(e),Po),this._c=new Map,this.mc=new Set,this.gc=new fs(ai.comparator),this.yc=new Map,this.Ic=new Wc,this.Tc={},this.Ec=new Map,this.Ac=Sc.Mn(),this.onlineState="Unknown",this.vc=void 0}get isPrimaryClient(){return!0===this.vc}}async function Bl(n,e,t,r,i){n.Rc=(e,s,t)=>async function(e,t,n){let r=t.view.sc(s);r.zi&&(r=await Ih(e.localStore,t.query,!1).then(({documents:e})=>t.view.sc(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return Hl(e,t.targetId,i.cc),i.snapshot}(n,e,t);const s=await Ih(n.localStore,e,!0),o=new Ll(e,s.ir),a=o.sc(s.documents),u=za.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,i),c=o.applyChanges(a,n.isPrimaryClient,u);Hl(n,t,c.cc);var h=new Ol(e,t,o);return n.wc.set(e,h),n._c.has(t)?n._c.get(t).push(e):n._c.set(t,[e]),c.snapshot}async function ql(e,t,n){const r=td(e);try{const e=await function(e,i){const s=e,o=ti.now(),a=i.reduce((e,t)=>e.add(t.key),Jo());let u,c;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=$o,r=Jo();return s.Zi.getEntries(n,a).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=ia(r.transform,e||null);null!=i&&(null===n&&(n=Ws.empty()),n.set(r.field,i))}return n||null}(n,u.get(n.key).overlayedDocument);null!=i&&t.push(new _a(n.key,i,function r(e){const i=[];return ls(e.fields,(e,t)=>{const n=new oi([e]);if(zs(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new ws(i)}(i.value.mapValue),ma.exists(!0)))}return s.mutationQueue.addMutationBatch(n,o,t,i)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:Ho(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Tc[e.currentUser.toKey()];r=r||new fs(Jr),r=r.insert(t,n),e.Tc[e.currentUser.toKey()]=r}(r,e.batchId,n),await Xl(r,e.changes),await ll(r.remoteStore)}catch(e){const t=wl(e,"Failed to persist write");n.reject(t)}}async function Ul(e,t){const r=e;try{const e=await yh(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.yc.get(t);n&&(Br(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.fc=!0:0<e.modifiedDocuments.size?Br(n.fc):0<e.removedDocuments.size&&(Br(n.fc),n.fc=!1))}),await Xl(r,e,t)}catch(e){await wi(e)}}function jl(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.wc.forEach((e,t)=>{var n=t.view.Mu(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.Mu(n)&&(r=!0)}),r&&Dl(t)}(t.eventManager,i),r.length&&t.dc.nu(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function Gl(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.Zi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let o=bi.resolve();return n.forEach(n=>{o=o.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Br(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),o.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Jo();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);$l(n,r,null),zl(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Xl(n,e)}catch(e){await wi(e)}}function zl(e,t){(e.Ec.get(t)||[]).forEach(e=>{e.resolve()}),e.Ec.delete(t)}function $l(e,t,n){const r=e;let i=r.Tc[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Tc[r.currentUser.toKey()]=i}}function Kl(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t._c.get(e))t.wc.delete(r),n&&t.dc.Pc(r,n);t._c.delete(e),t.isPrimaryClient&&t.Ic.Is(e).forEach(e=>{t.Ic.containsKey(e)||Ql(t,e)})}function Ql(e,t){e.mc.delete(t.path.canonicalString());var n=e.gc.get(t);null!==n&&(nl(e.remoteStore,n),e.gc=e.gc.remove(t),e.yc.delete(n),Wl(e))}function Hl(e,t,n){for(const r of n)r instanceof Ml?(e.Ic.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.gc.get(n)||e.mc.has(r)||(Fr("SyncEngine","New document in limbo: "+n),e.mc.add(r),Wl(e))}(e,r)):r instanceof Fl?(Fr("SyncEngine","Document no longer in limbo: "+r.key),e.Ic.removeReference(r.key,t),e.Ic.containsKey(r.key)||Ql(e,r.key)):Pr()}function Wl(e){for(;0<e.mc.size&&e.gc.size<e.maxConcurrentLimboResolutions;){var t=e.mc.values().next().value;e.mc.delete(t);var n=new ai(ii.fromString(t)),t=e.Ac.next();e.yc.set(t,new Vl(n)),e.gc=e.gc.insert(n,t),tl(e.remoteStore,new xu(Lo(Co(n.path)),t,"TargetPurposeLimboResolution",Ri.ct))}}async function Xl(e,t,r){const i=e,s=[],o=[],a=[];i.wc.isEmpty()||(i.wc.forEach((e,n)=>{a.push(i.Rc(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=lh.Li(n.targetId,e),o.push(t))}))}),await Promise.all(a),i.dc.nu(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>bi.forEach(t,t=>bi.forEach(t.Fi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>bi.forEach(t.Bi,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Si(e))throw e;Fr("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Ji.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Ji=r.Ji.insert(t,i)}}}(i.localStore,o))}async function Yl(r,e){const i=r;if(ed(i),td(i),!0===e&&!0!==i.vc){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Jl(i,r.toArray());i.vc=!0,await ml(i.remoteStore,!0);for(const r of e)tl(i.remoteStore,r)}else if(!1===e&&!1!==i.vc){const r=[];let n=Promise.resolve();i._c.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(Kl(i,t),bh(i.localStore,t,!0))),nl(i.remoteStore,t)}),await n,await Jl(i,r),function(){const n=i;n.yc.forEach((e,t)=>{nl(n.remoteStore,t)}),n.Ic.Ts(),n.yc=new Map,n.gc=new fs(ai.comparator)}(),i.vc=!1,await ml(i.remoteStore,!1)}}async function Jl(t,n){const r=t,i=[],s=[];for(const t of n){let e;const h=r._c.get(t);if(h&&0!==h.length){e=await wh(r.localStore,Lo(h[0]));for(const t of h){const n=r.wc.get(t),h=(o=r,a=n,c=u=void 0,c=await Ih((u=o).localStore,a.query,!0),c=a.view.hc(c),u.isPrimaryClient&&Hl(u,a.targetId,c.cc),await c);h.snapshot&&s.push(h.snapshot)}}else{const h=await Eh(r.localStore,t);e=await wh(r.localStore,h),await Bl(r,Zl(h),t,!1,e.resumeToken)}i.push(e)}var o,a,u,c;return r.dc.nu(s),i}function Zl(e){return Ao(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function ed(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Ul.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.yc.get(t);if(r&&r.fc)return Jo().add(r.key);{let e=Jo();const r=n._c.get(t);if(!r)return e;for(const t of r){const r=n.wc.get(t);e=e.unionWith(r.view.nc)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.yc.get(t),s=i&&i.key;if(s){let e=new fs(ai.comparator);e=e.insert(s,Xs.newNoDocument(s,ni.min()));const n=Jo().add(s),i=new Ga(ni.min(),new Map,new fs(Jr),e,n);await Ul(r,i),r.gc=r.gc.remove(s),r.yc.delete(t),Wl(r)}else await bh(r.localStore,t,!1).then(()=>Kl(r,t,n)).catch(wi)}).bind(null,t),t.dc.nu=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.$u(e)&&(r=!0);i.Nu=e}}r&&Dl(n)}).bind(null,t.eventManager),t.dc.Pc=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function td(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=Gl.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(Br(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);$l(r,t,n),zl(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Xl(r,e)}catch(n){await wi(n)}}).bind(null,t),t}class nd{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=$h(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return gh(this.persistence,new dh,e.initialUser,this.serializer)}createPersistence(e){return new th(rh.zs,this.serializer)}createSharedClientState(e){return new Fh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class rd extends nd{constructor(e,t,n){super(),this.Vc=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Vc.initialize(this,e),await td(this.Vc.syncEngine),await ll(this.Vc.remoteStore),await this.persistence.Ii(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return gh(this.persistence,new dh,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new Rc(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new ki(t,this.persistence);return new Ni(e.asyncQueue,n)}createPersistence(e){var t=hh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?yc.withCacheSize(this.cacheSizeBytes):yc.DEFAULT;return new ah(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,Gh(),zh(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new Fh}}class id extends rd{constructor(e,t){super(e,t,!1),this.Vc=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Vc.syncEngine;this.sharedClientState instanceof Mh&&(this.sharedClientState.syncEngine={jr:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Sn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):bi.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await ll(i.remoteStore):"acknowledged"===n||"rejected"===n?($l(i,t,r||null),zl(i,t),i.localStore.mutationQueue.Cn(t)):Pr(),await Xl(i,s)):Fr("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),zr:(async function(e,t,n,r){const i=e;if(i.vc)Fr("SyncEngine","Ignoring unexpected query state notification.");else{var s=i._c.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await _h(i.localStore,jo(s[0])),r=Ga.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,Is.EMPTY_BYTE_STRING);await Xl(i,e,r);break}case"rejected":await bh(i.localStore,t,!0),Kl(i,t,r);break;default:Pr()}}}).bind(null,t),Wr:(async function(e,t,n){const r=ed(e);if(r.vc){for(const e of t)if(r._c.has(e))Fr("SyncEngine","Adding an already active target "+e);else{const t=await Eh(r.localStore,e),n=await wh(r.localStore,t);await Bl(r,Zl(t),n.targetId,!1,n.resumeToken),tl(r.remoteStore,n)}for(const e of n)r._c.has(e)&&await bh(r.localStore,e,!1).then(()=>{nl(r.remoteStore,e),Kl(r,e)}).catch(wi)}}).bind(null,t),$i:(function(e){return e.localStore.persistence.$i()}).bind(null,t),Qr:(async function(e,t){const n=e;return _h(n.localStore,t).then(e=>Xl(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ii(async e=>{await Yl(this.Vc.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}createSharedClientState(e){var t=Gh();if(!Mh.D(t))throw new Ur(qr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=hh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Mh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class sd{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>jl(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Fr("SyncEngine","User change. New user:",t.toKey());const r=await mh(n.localStore,t);n.currentUser=t,(e=n).Ec.forEach(e=>{e.forEach(e=>{e.reject(new Ur(qr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Ec.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await Xl(n,r.er)}}).bind(null,this.syncEngine),await ml(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Tl}createDatastore(e){var t,n,r,i,s=$h(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new jh(t));return n=e.authCredentials,r=e.appCheckCredentials,i=t,e=s,new Xh(n,r,i,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>jl(this.syncEngine,e,0),s=new(Oh.D()?Oh:Lh),new Jh(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new Pl(e,t,n,r,i,s);return o&&(a.vc=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Fr("RemoteStore","RemoteStore shutting down."),t.vu.add(5),await el(t),t.Pu.shutdown(),t.bu.set("Unknown")}(this.remoteStore)}}function od(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class ad{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Sc(this.observer.next,e)}error(e){this.observer.error?this.Sc(this.observer.error,e):Lr("Uncaught Error in snapshot listener:",e.toString())}Dc(){this.muted=!0}Sc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class ud{constructor(e,t){this.Cc=e,this.serializer=t,this.metadata=new jr,this.buffer=new Uint8Array,this.xc=new TextDecoder("utf-8"),this.Nc().then(e=>{e&&e.Qu()?this.metadata.resolve(e.Gu.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.Gu)}`))},e=>this.metadata.reject(e))}close(){return this.Cc.cancel()}async getMetadata(){return this.metadata.promise}async bc(){return await this.getMetadata(),this.Nc()}async Nc(){var e=await this.kc();if(null===e)return null;var t=this.xc.decode(e),n=Number(t);isNaN(n)&&this.Mc(`length string (${t}) is not valid number`);t=await this.$c(n);return new Cl(JSON.parse(t),e.length+n)}Oc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async kc(){for(;this.Oc()<0&&!await this.Fc(););if(0===this.buffer.length)return null;var e=this.Oc();e<0&&this.Mc("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async $c(e){for(;this.buffer.length<e;)await this.Fc()&&this.Mc("Reached the end of bundle when more is expected.");var t=this.xc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Mc(e){throw this.Cc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Fc(){var e=await this.Cc.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class cd{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new Ur(qr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=du(r.serializer)+"/documents",i={documents:t.map(e=>uu(r.serializer,e))},s=await r.vo("BatchGetDocuments",n,i,t.length),o=new Map;s.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){Br(!!t.found),t.found.name,t.found.updateTime;var n=cu(e,t.found.name),r=su(t.found.updateTime),i=t.found.createTime?su(t.found.createTime):ni.min(),s=new Ws({mapValue:{fields:t.found.fields}});return Xs.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){Br(!!t.missing),Br(!!t.readTime);var n=cu(e,t.missing),r=su(t.readTime);return Xs.newNoDocument(n,r)}(n,e):Pr());var n;o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=o.get(e.toString());Br(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Da(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=ai.fromPath(t);this.mutations.push(new Aa(n,this.precondition(n)))}),await async function(e,t){const n=e,r=du(n.serializer)+"/documents",i={writes:t.map(e=>pu(n.serializer,e))};await n.Io("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Pr();t=ni.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new Ur(qr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(ni.min())?ma.exists(!1):ma.updateTime(t):ma.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return ma.exists(!0);if(t.isEqual(ni.min()))throw new Ur(qr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return ma.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class hd{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Bc=n.maxAttempts,this.qo=new Kh(this.asyncQueue,"transaction_retry")}run(){--this.Bc,this.Lc()}Lc(){this.qo.No(async()=>{const t=new cd(this.datastore),e=this.qc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Uc(e)}))}).catch(e=>{this.Uc(e)})})}qc(e){try{var t=this.updateFunction(e);return!Mi(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Uc(e){0<this.Bc&&this.Kc(e)?(--this.Bc,this.asyncQueue.enqueueAndForget(()=>(this.Lc(),Promise.resolve()))):this.deferred.reject(e)}Kc(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!Ma(t)}}class ld{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Nr.UNAUTHENTICATED,this.clientId=Yr.A(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Fr("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Fr("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new Ur(qr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new jr;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=wl(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function dd(e,t){e.asyncQueue.verifyOperationInProgress(),Fr("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await mh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function fd(e,n){e.asyncQueue.verifyOperationInProgress();var t=await md(e);Fr("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>gl(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>gl(n.remoteStore,t)),e._onlineComponents=n}function gd(e){return"FirebaseError"===e.name?e.code===qr.FAILED_PRECONDITION||e.code===qr.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function md(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){Fr("FirestoreClient","Using user provided OfflineComponentProvider");try{await dd(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!gd(n))throw n;Or("Error using user provided cache. Falling back to memory cache: "+n),await dd(t,new nd)}}else Fr("FirestoreClient","Using default OfflineComponentProvider"),await dd(t,new nd);return t._offlineComponents}async function pd(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Fr("FirestoreClient","Using user provided OnlineComponentProvider"),await fd(e,e._uninitializedComponentsProvider._online)):(Fr("FirestoreClient","Using default OnlineComponentProvider"),await fd(e,new sd))),e._onlineComponents}function yd(e){return md(e).then(e=>e.persistence)}function vd(e){return md(e).then(e=>e.localStore)}function wd(e){return pd(e).then(e=>e.remoteStore)}function bd(e){return pd(e).then(e=>e.syncEngine)}async function Id(e){const t=await pd(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=ed(e);let r,i;const s=n.wc.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.lc();else{const e=await wh(n.localStore,Lo(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Bl(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&tl(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.wc.get(t),i=n._c.get(r.targetId);if(1<i.length)return n._c.set(r.targetId,i.filter(e=>!Po(e,t))),void n.wc.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await bh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),nl(n.remoteStore,r.targetId),Kl(n,r.targetId)}).catch(wi)):(Kl(n,r.targetId),await bh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function Ed(e,t,n={}){const r=new jr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,o){const e=new ad({next:e=>{r.enqueueAndForget(()=>xl(n,a));var t=e.docs.has(i);!t&&e.fromCache?o.reject(new Ur(qr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?o.reject(new Ur(qr.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.)')):o.resolve(e)},error:e=>o.reject(e)}),a=new Al(Co(i.path),e,{includeMetadataChanges:!0,Ku:!0});return Sl(n,a)}(await Id(e),e.asyncQueue,t,n,r)),r.promise}function _d(e,t,n={}){const r=new jr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new ad({next:e=>{n.enqueueAndForget(()=>xl(t,o)),e.fromCache&&"server"===r.source?i.reject(new Ur(qr.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),o=new Al(e,s,{includeMetadataChanges:!0,Ku:!0});return Sl(t,o)}(await Id(e),e.asyncQueue,t,n,r)),r.promise}function Td(e,t,n,r){const i=(n=n,t=$h(t),s="string"==typeof n?Va().encode(n):n,n=function(e){if(e instanceof Uint8Array)return od(e,void 0);if(e instanceof ArrayBuffer)return od(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new ud(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=su(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.qs.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(Rl(i));const o=new kl(i,t.localStore,n.serializer);let e=await n.bc();for(;e;){const t=await o.zu(e);t&&r._updateProgress(t),e=await n.bc()}var s=await o.complete();return await Xl(t,s.Ju,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.qs.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.Hu)}catch(t){return Or("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await bd(e),i,r)})}function Sd(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const xd=new Map;function Dd(e,t,n){if(!n)throw new Ur(qr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Ad(e,t,n,r){if(!0===t&&!0===r)throw new Ur(qr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Cd(e){if(!ai.isDocumentKey(e))throw new Ur(qr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Nd(e){if(ai.isDocumentKey(e))throw new Ur(qr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function kd(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":Pr();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function Rd(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new Ur(qr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=kd(e);throw new Ur(qr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Md(e,t){if(t<=0)throw new Ur(qr.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Fd{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new Ur(qr.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.cache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new Ur(qr.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}Ad("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=Sd(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new Ur(qr.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new Ur(qr.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new Ur(qr.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class Ld{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Fd({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new Ur(qr.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new Ur(qr.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 Fd(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new zr;switch(e.type){case"firstParty":return new Hr(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new Ur(qr.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=xd.get(e);t&&(Fr("ComponentProvider","Removing Datastore"),xd.delete(e),t.terminate())}(this),Promise.resolve()}}function Od(n,e,t,r={}){var i;const s=(n=Rd(n,Ld))._getSettings(),o=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==o&&Or("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:o,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=Nr.MOCK_USER;else{e=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e),[a(JSON.stringify({alg:"none",type:"JWT"})),a(JSON.stringify(i)),""].join(".")}(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new Ur(qr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new Nr(s)}n._authCredentials=new $r(new Gr(e,t))}}class Vd{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Bd(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Vd(this.firestore,e,this._key)}}class Pd{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Pd(this.firestore,e,this._query)}}class Bd extends Pd{constructor(e,t,n){super(e,t,Co(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Vd(this.firestore,null,new ai(e))}withConverter(e){return new Bd(this.firestore,e,this._path)}}function qd(e,t,...n){if(e=m(e),Dd("collection","path",t),e instanceof Ld){var r=ii.fromString(t,...n);return Nd(r),new Bd(e,null,r)}if(!(e instanceof Vd||e instanceof Bd))throw new Ur(qr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ii.fromString(t,...n));return Nd(r),new Bd(e.firestore,null,r)}function Ud(e,t,...n){if(e=m(e),Dd("doc","path",t=1===arguments.length?Yr.A():t),e instanceof Ld){var r=ii.fromString(t,...n);return Cd(r),new Vd(e,null,new ai(r))}if(!(e instanceof Vd||e instanceof Bd))throw new Ur(qr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ii.fromString(t,...n));return Cd(r),new Vd(e.firestore,e instanceof Bd?e.converter:null,new ai(r))}function jd(e,t){return e=m(e),t=m(t),(e instanceof Vd||e instanceof Bd)&&(t instanceof Vd||t instanceof Bd)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Gd(e,t){return e=m(e),t=m(t),e instanceof Pd&&t instanceof Pd&&e.firestore===t.firestore&&Po(e._query,t._query)&&e.converter===t.converter}class zd{constructor(){this.Gc=Promise.resolve(),this.Qc=[],this.jc=!1,this.zc=[],this.Wc=null,this.Hc=!1,this.Jc=!1,this.Yc=[],this.qo=new Kh(this,"async_queue_retry"),this.Xc=()=>{var e=zh();e&&Fr("AsyncQueue","Visibility state changed to "+e.visibilityState),this.qo.Mo()};const e=zh();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Xc)}get isShuttingDown(){return this.jc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Zc(),this.ta(e)}enterRestrictedMode(e){if(!this.jc){this.jc=!0,this.Jc=e||!1;const t=zh();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Xc)}}enqueue(e){if(this.Zc(),this.jc)return new Promise(()=>{});const t=new jr;return this.ta(()=>this.jc&&this.Jc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Qc.push(e),this.ea()))}async ea(){if(0!==this.Qc.length){try{await this.Qc[0](),this.Qc.shift(),this.qo.reset()}catch(e){if(!Si(e))throw e;Fr("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Qc.length&&this.qo.No(()=>this.ea())}}ta(e){var t=this.Gc.then(()=>(this.Hc=!0,e().catch(e=>{throw this.Wc=e,this.Hc=!1,Lr("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Hc=!1,e))));return this.Gc=t}enqueueAfterDelay(e,t,n){this.Zc(),-1<this.Yc.indexOf(e)&&(t=0);var r=vl.createAndSchedule(this,e,t,n,e=>this.na(e));return this.zc.push(r),r}Zc(){this.Wc&&Pr()}verifyOperationInProgress(){}async sa(){for(var e;await(e=this.Gc),e!==this.Gc;);}ia(e){for(const t of this.zc)if(t.timerId===e)return!0;return!1}ra(t){return this.sa().then(()=>{this.zc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.zc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.sa()})}oa(e){this.Yc.push(e)}na(e){var t=this.zc.indexOf(e);this.zc.splice(t,1)}}function $d(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class Kd{constructor(){this._progressObserver={},this._taskCompletionResolver=new jr,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var Qd,Hd,Wd;class Xd extends Ld{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new zd,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||Jd(this),this._firestoreClient.terminate()}}function Yd(e){return e._firestoreClient||Jd(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Jd(e){var t,n,r,i,s,o=e._freezeSettings(),a=(n=e._databaseId,r=(null===(a=e._app)||void 0===a?void 0:a.options.appId)||"",i=e._persistenceKey,s=o,new Cs(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Sd(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new ld(e._authCredentials,e._appCheckCredentials,e._queue,a),null!==(a=o.cache)&&void 0!==a&&a._offlineComponentProvider&&null!==(t=o.cache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:o.cache.kind,_offline:o.cache._offlineComponentProvider,_online:o.cache._onlineComponentProvider})}function Zd(e,t,n){const r=new jr;return e.asyncQueue.enqueue(async()=>{try{await dd(e,n),await fd(e,t),r.resolve()}catch(e){const t=e;if(!gd(t))throw t;Or("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function ef(e){return function(e){const t=new jr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;al(n.remoteStore)||Fr("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.Ec.get(e)||[];r.push(t),n.Ec.set(e,r)}catch(e){const n=wl(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await bd(e),t)),t.promise}(Yd(e=Rd(e,Xd)))}function tf(e){return(n=Yd(e=Rd(e,Xd))).asyncQueue.enqueue(async()=>{const e=await yd(n),t=await wd(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.vu.delete(0),Zh(e)}()});var n}function nf(e){return(n=Yd(e=Rd(e,Xd))).asyncQueue.enqueue(async()=>{const e=await yd(n),t=await wd(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.vu.add(0),await el(e),e.bu.set("Offline")}()});var n}function rf(t,e){return n=Yd(t=Rd(t,Xd)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.qs.getNamedQuery(e,t))}(await vd(n),r)).then(e=>e?new Pd(t,null,e.query):null);var n,r}function sf(e){if(e._initialized||e._terminated)throw new Ur(qr.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class of{constructor(e){this._byteString=e}static fromBase64String(e){try{return new of(Is.fromBase64String(e))}catch(e){throw new Ur(qr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new of(Is.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 af{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new Ur(qr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new oi(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class uf{constructor(e){this._methodName=e}}class cf{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new Ur(qr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new Ur(qr.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Jr(this._lat,e._lat)||Jr(this._long,e._long)}}const hf=/^__.*__$/;class lf{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new _a(e,this.data,this.fieldMask,t,this.fieldTransforms):new Ea(e,this.data,t,this.fieldTransforms)}}class df{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new _a(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function ff(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Pr()}}class gf{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.ua(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get ca(){return this.settings.ca}aa(e){return new gf(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ha(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.aa({path:n,la:!1});return r.fa(e),r}da(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.aa({path:n,la:!1});return r.ua(),r}wa(e){return this.aa({path:void 0,la:!0})}_a(e){return Ff(e,this.settings.methodName,this.settings.ma||!1,this.path,this.settings.ga)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}ua(){if(this.path)for(let e=0;e<this.path.length;e++)this.fa(this.path.get(e))}fa(e){if(0===e.length)throw this._a("Document fields must not be empty");if(ff(this.ca)&&hf.test(e))throw this._a('Document fields cannot begin and end with "__"')}}class mf{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||$h(e)}ya(e,t,n,r=!1){return new gf({ca:e,methodName:t,ga:n,path:oi.emptyPath(),la:!1,ma:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function pf(e){var t=e._freezeSettings(),n=$h(e._databaseId);return new mf(e._databaseId,!!t.ignoreUndefinedProperties,n)}function yf(e,t,n,r,i,s={}){const o=e.ya(s.merge||s.mergeFields?2:0,t,n,i);Nf("Data must be an object, but it was:",o,r);var a=Af(r,o);let u,c;if(s.merge)u=new ws(o.fieldMask),c=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=kf(t,r,n);if(!o.contains(i))throw new Ur(qr.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Lf(e,i)||e.push(i)}u=new ws(e),c=o.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=o.fieldTransforms;return new lf(new Ws(a),u,c)}class vf extends uf{_toFieldTransform(e){if(2!==e.ca)throw 1===e.ca?e._a(`${this._methodName}() can only appear at the top level of your update data`):e._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof vf}}function wf(e,t,n){return new gf({ca:3,ga:t.settings.ga,methodName:e._methodName,la:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class bf extends uf{_toFieldTransform(e){return new fa(e.path,new sa)}isEqual(e){return e instanceof bf}}class If extends uf{constructor(e,t){super(e),this.pa=t}_toFieldTransform(e){const t=wf(this,e,!0),n=this.pa.map(e=>Df(e,t)),r=new oa(n);return new fa(e.path,r)}isEqual(e){return this===e}}class Ef extends uf{constructor(e,t){super(e),this.pa=t}_toFieldTransform(e){const t=wf(this,e,!0),n=this.pa.map(e=>Df(e,t)),r=new ua(n);return new fa(e.path,r)}isEqual(e){return this===e}}class _f extends uf{constructor(e,t){super(e),this.Ia=t}_toFieldTransform(e){var t=new ha(e.serializer,na(e.serializer,this.Ia));return new fa(e.path,t)}isEqual(e){return this===e}}function Tf(e,i,s,t){const o=e.ya(1,i,s);Nf("Data must be an object, but it was:",o,t);const a=[],u=Ws.empty();ls(t,(e,t)=>{var n=Mf(i,e,s);t=m(t);var r=o.da(n);if(t instanceof vf)a.push(n);else{const e=Df(t,r);null!=e&&(a.push(n),u.set(n,e))}});var n=new ws(a);return new df(u,n,o.fieldTransforms)}function Sf(e,t,n,r,i,s){const o=e.ya(1,t,n),a=[kf(t,r,n)],u=[i];if(s.length%2!=0)throw new Ur(qr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)a.push(kf(t,s[f])),u.push(s[f+1]);const c=[],h=Ws.empty();for(let g=a.length-1;0<=g;--g)if(!Lf(c,a[g])){const t=a[g];var l=m(l=u[g]);const r=o.da(t);if(l instanceof vf)c.push(t);else{const e=Df(l,r);null!=e&&(c.push(t),h.set(t,e))}}var d=new ws(c);return new df(h,d,o.fieldTransforms)}function xf(e,t,n,r=!1){return Df(n,e.ya(r?4:3,t))}function Df(s,e){if(Cf(s=m(s)))return Nf("Unsupported field value:",e,s),Af(s,e);if(s instanceof uf)return function(e,t){if(!ff(t.ca))throw t._a(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t._a(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(s,e),null;if(void 0===s&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),s instanceof Array){if(e.settings.la&&4!==e.ca)throw e._a("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=Df(i,t.wa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=m(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return na(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=ti.fromDate(e);return{timestampValue:ru(t.serializer,n)}}if(e instanceof ti){n=new ti(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ru(t.serializer,n)}}if(e instanceof cf)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof of)return{bytesValue:iu(t.serializer,e._byteString)};if(e instanceof Vd){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t._a(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:ou(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t._a(`Unsupported field value: ${kd(e)}`)}(0,e)}function Af(e,r){const i={};return ds(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):ls(e,(e,t)=>{var n=Df(t,r.ha(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function Cf(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ti||e instanceof cf||e instanceof of||e instanceof Vd||e instanceof uf)}function Nf(e,t,n){if(!Cf(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=kd(n);throw"an object"===r?t._a(e+" a custom object"):t._a(e+" "+r)}var i}function kf(e,t,n){if((t=m(t))instanceof af)return t._internalPath;if("string"==typeof t)return Mf(e,t);throw Ff("Field path arguments must be of type string or ",e,!1,void 0,n)}const Rf=new RegExp("[~\\*/\\[\\]]");function Mf(t,n,r){if(0<=n.search(Rf))throw Ff(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new af(...n.split("."))._internalPath}catch(e){throw Ff(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Ff(e,t,n,r,i){var s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let u="";return(s||o)&&(u+=" (found",s&&(u+=` in field ${r}`),o&&(u+=` in document ${i}`),u+=")"),new Ur(qr.INVALID_ARGUMENT,a+e+u)}function Lf(e,t){return e.some(e=>e.isEqual(t))}class Of{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Vd(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Vf(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(Pf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Vf extends Of{data(){return super.data()}}function Pf(e,t){return"string"==typeof t?Mf(e,t):(t instanceof af?t:t._delegate)._internalPath}function Bf(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new Ur(qr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class qf{}class Uf extends qf{}function jf(e,t,...n){let r=[];t instanceof qf&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof zf).length,n=e.filter(e=>e instanceof Gf).length;if(1<t||0<t&&0<n)throw new Ur(qr.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class Gf extends Uf{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Gf(e,t,n)}_apply(e){var t=this._parse(e);return Jf(e._query,t),new Pd(e.firestore,e.converter,Oo(e._query,t))}_parse(e){var t=pf(e.firestore);return function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new Ur(qr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){Yf(o,s);const t=[];for(const n of o)t.push(Xf(r,e,n));a={arrayValue:{values:t}}}else a=Xf(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||Yf(o,s),a=xf(n,t,o,"in"===s||"not-in"===s);return no.create(i,s,a)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class zf extends qf{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new zf(e,t)}_parse(t){var e=this._queryConstraints.map(e=>e._parse(t)).filter(e=>0<e.getFilters().length);return 1===e.length?e[0]:ro.create(e,this._getOperator())}_apply(e){const n=this._parse(e);return 0===n.getFilters().length?e:(function(e){let t=e;for(const e of n.getFlattenedFilters())Jf(t,e),t=Oo(t,e)}(e._query),new Pd(e.firestore,e.converter,Oo(e._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class $f extends Uf{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new $f(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new Ur(qr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new Ur(qr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new eo(t,n);return n=i,null!==ko(e=e)||null!==(r=Ro(e))&&Zf(0,r,n.field),i}(e._query,this._field,this._direction);return new Pd(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Do(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Kf extends Uf{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new Kf(e,t,n)}_apply(e){return new Pd(e.firestore,e.converter,Vo(e._query,this._limit,this._limitType))}}class Qf extends Uf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Qf(e,t,n)}_apply(e){var t,n=Wf(e,this.type,this._docOrFields,this._inclusive);return new Pd(e.firestore,e.converter,(t=e._query,e=n,new Do(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class Hf extends Uf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Hf(e,t,n)}_apply(e){var t,n=Wf(e,this.type,this._docOrFields,this._inclusive);return new Pd(e.firestore,e.converter,(t=e._query,e=n,new Do(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function Wf(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Of)return function(e,t,n,r,i){if(!r)throw new Ur(qr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Fo(e))if(n.field.isKeyField())s.push(Bs(t,r.key));else{const e=r.data.field(n.field);if(xs(e))throw new Ur(qr.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new Ys(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=pf(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new Ur(qr.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let u=0;u<i.length;u++){const c=i[u];if(o[u].field.isKeyField()){if("string"!=typeof c)throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!Mo(e)&&-1!==c.indexOf("/"))throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(ii.fromString(c));if(!ai.isDocumentKey(n))throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new ai(n);a.push(Bs(t,i))}else{const e=xf(n,r,c);a.push(e)}}return new Ys(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function Xf(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new Ur(qr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Mo(t)&&-1!==n.indexOf("/"))throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(ii.fromString(n));if(!ai.isDocumentKey(r))throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Bs(e,new ai(r))}if(n instanceof Vd)return Bs(e,n._key);throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${kd(n)}.`)}function Yf(e,t){if(!Array.isArray(e)||0===e.length)throw new Ur(qr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Jf(e,t){if(t.isInequality()){const r=Ro(e),i=t.field;if(null!==r&&!r.isEqual(i))throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${i.toString()}'`);var n=ko(e);null!==n&&Zf(0,i,n)}const r=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new Ur(qr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new Ur(qr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function Zf(e,t,n){if(!n.isEqual(t))throw new Ur(qr.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class eg{convertValue(e,t="none"){switch(Ms(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Ts(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Ss(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw Pr()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return ls(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new cf(Ts(e.latitude),Ts(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=Ds(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(As(e));default:return null}}convertTimestamp(e){var t=_s(e);return new ti(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=ii.fromString(e);Br(Su(n));const r=new Ns(n.get(1),n.get(3)),i=new ai(n.popFirst(5));return r.isEqual(t)||Lr(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function tg(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class ng extends eg{constructor(e){super(),this.firestore=e}convertBytes(e){return new of(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Vd(this.firestore,null,t)}}class rg{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class ig extends Of{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new sg(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(Pf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class sg extends ig{data(e={}){return super.data(e)}}class og{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new rg(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new sg(this._firestore,this._userDataWriter,e.key,e,new rg(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new Ur(qr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new sg(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rg(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new sg(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rg(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Pr()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function ag(e,t){return e instanceof ig&&t instanceof ig?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof og&&t instanceof og&&e._firestore===t._firestore&&Gd(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class ug extends eg{constructor(e){super(),this.firestore=e}convertBytes(e){return new of(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Vd(this.firestore,null,t)}}function cg(t){t=Rd(t,Vd);const n=Rd(t.firestore,Xd),e=Yd(n),r=new ug(n);return function(e,t){const n=new jr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new Ur(qr.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=wl(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await vd(e),t,n)),n.promise}(e,t._key).then(e=>new ig(n,r,t._key,e,new rg(null!==e&&e.hasLocalMutations,!0),t.converter))}function hg(t){t=Rd(t,Pd);const n=Rd(t.firestore,Xd),e=Yd(n),r=new ug(n);return function(e,t){const n=new jr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await Ih(e,t,!0),s=new Ll(t,i.ir),o=s.sc(i.documents),a=s.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=wl(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await vd(e),t,n)),n.promise}(e,t._query).then(e=>new og(n,r,t,e))}function lg(e,t,n){e=Rd(e,Vd);var r=Rd(e.firestore,Xd),i=tg(e.converter,t,n);return mg(r,[yf(pf(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,ma.none())])}function dg(e,t,n,...r){e=Rd(e,Vd);var i=Rd(e.firestore,Xd),s=pf(i);let o;return o="string"==typeof(t=m(t))||t instanceof af?Sf(s,"updateDoc",e._key,t,n,r):Tf(s,"updateDoc",e._key,t),mg(i,[o.toMutation(e._key,ma.exists(!0))])}function fg(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||$d(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if($d(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let o,a,u;if(t instanceof Vd)a=Rd(t.firestore,Xd),u=Co(t._key.path),o={next:e=>{n[i]&&n[i](pg(a,t,e))},error:n[i+1],complete:n[i+2]};else{const c=Rd(t,Pd);a=Rd(c.firestore,Xd),u=c._query;const h=new ug(a);o={next:e=>{n[i]&&n[i](new og(a,h,c,e))},error:n[i+1],complete:n[i+2]},Bf(t._query)}return function(e,t,n,r){const i=new ad(r),s=new Al(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Sl(await Id(e),s)),()=>{i.Dc(),e.asyncQueue.enqueueAndForget(async()=>xl(await Id(e),s))}}(Yd(a),u,s,o)}function gg(e,t){return function(e,t){const n=new ad(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.ku.add(t),t.next()}(await Id(e),n)),()=>{n.Dc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.ku.delete(t)}(await Id(e),n))}}(Yd(e=Rd(e,Xd)),$d(t)?t:{next:t})}function mg(e,t){return function(e,t){const n=new jr;return e.asyncQueue.enqueueAndForget(async()=>ql(await bd(e),t,n)),n.promise}(Yd(e),t)}function pg(e,t,n){var r=n.docs.get(t._key),i=new ug(e);return new ig(e,i,t._key,r,new rg(n.hasPendingWrites,n.fromCache),t.converter)}const yg={maxAttempts:5};class vg{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=pf(e)}set(e,t,n){this._verifyNotCommitted();const r=wg(e,this._firestore),i=tg(r.converter,t,n),s=yf(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,ma.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=wg(e,this._firestore);let s;return s="string"==typeof(t=m(t))||t instanceof af?Sf(this._dataReader,"WriteBatch.update",i._key,t,n,r):Tf(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,ma.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=wg(e,this._firestore);return this._mutations=this._mutations.concat(new Da(t._key,ma.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new Ur(qr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function wg(e,t){if((e=m(e)).firestore!==t)throw new Ur(qr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class bg extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=pf(e)}get(e){const n=wg(e,this._firestore),r=new ng(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Pr();const t=e[0];if(t.isFoundDocument())return new Of(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Of(this._firestore,r,n._key,null,n.converter);throw Pr()})}set(e,t,n){var r=wg(e,this._firestore),i=tg(r.converter,t,n),i=yf(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=wg(e,this._firestore),s="string"==typeof(t=m(t))||t instanceof af?Sf(this._dataReader,"Transaction.update",i._key,t,n,r):Tf(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=wg(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=wg(e,this._firestore),n=new ug(this._firestore);return super.get(e).then(e=>new ig(this._firestore,n,t._key,e._document,new rg(!1,!1),t.converter))}}function Ig(t,n,e){t=Rd(t,Xd);var r=Object.assign(Object.assign({},yg),e);return function(){if(r.maxAttempts<1)throw new Ur(qr.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(t,n,r){const i=new jr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await pd(t).then(e=>e.datastore);new hd(t.asyncQueue,e,r,n,i).run()}),i.promise}(Yd(t),e=>n(new bg(t,e)),r)}Qd=Hg.SDK_VERSION,kr=Qd,Hg._registerComponent(new p("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new Xd(new Kr(e.getProvider("auth-internal")),new Xr(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new Ur(qr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ns(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:!0},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),Hg.registerVersion(Cr,"3.13.0",void 0),Hg.registerVersion(Cr,"3.13.0","esm2017");function Eg(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new Ur("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function _g(){if("undefined"==typeof Uint8Array)throw new Ur("unimplemented","Uint8Arrays are not available in this environment.")}function Tg(){if("undefined"==typeof atob)throw new Ur("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Sg{constructor(e){this._delegate=e}static fromBase64String(e){return Tg(),new Sg(of.fromBase64String(e))}static fromUint8Array(e){return _g(),new Sg(of.fromUint8Array(e))}toBase64(){return Tg(),this._delegate.toBase64()}toUint8Array(){return _g(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function xg(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class Dg{enableIndexedDbPersistence(e,t){return function(e,t){sf(e=Rd(e,Xd));var n=Yd(e);if(n._uninitializedComponentsProvider)throw new Ur(qr.FAILED_PRECONDITION,"SDK cache is already specified.");Or("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new sd;return Zd(n,i,new rd(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){sf(e=Rd(e,Xd));var t=Yd(e);if(t._uninitializedComponentsProvider)throw new Ur(qr.FAILED_PRECONDITION,"SDK cache is already specified.");Or("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new sd;return Zd(t,r,new id(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new Ur(qr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new jr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Ei.D())return Promise.resolve();var t=e+"main";await Ei.delete(t)}(hh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Ag{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Ns||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Or("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){Od(this._delegate,e,t,n)}enableNetwork(){return tf(this._delegate)}disableNetwork(){return nf(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Ad("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return ef(this._delegate)}onSnapshotsInSync(e){return gg(this._delegate,e)}get app(){if(!this._appCompat)throw new Ur("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new jg(this,qd(this._delegate,e))}catch(e){throw Fg(e,"collection()","Firestore.collection()")}}doc(e){try{return new Mg(this,Ud(this._delegate,e))}catch(e){throw Fg(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Bg(this,function(e,t){if(e=Rd(e,Ld),Dd("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new Ur(qr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Pd(e,null,(t=t,new Do(ii.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Fg(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Ig(this._delegate,e=>t(new Ng(this,e)))}batch(){return Yd(this._delegate),new kg(new vg(this._delegate,e=>mg(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Yd(t=Rd(t,Xd)),r=new Kd,Td(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return rf(this._delegate,e).then(e=>e?new Bg(this,e):null)}}class Cg extends eg{constructor(e){super(),this.firestore=e}convertBytes(e){return new Sg(new of(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Mg.forKey(t,this.firestore,null)}}class Ng{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Cg(e)}get(e){const t=Gg(e);return this._delegate.get(t).then(e=>new Vg(this._firestore,new ig(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Gg(e);return n?(Eg("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=Gg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=Gg(e);return this._delegate.delete(t),this}}class kg{constructor(e){this._delegate=e}set(e,t,n){var r=Gg(e);return n?(Eg("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=Gg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=Gg(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Rg{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new sg(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Pg(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=Rg.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Rg(e,new Cg(e),t),r.set(t,i)),i}}Rg.INSTANCES=new WeakMap;class Mg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Cg(e)}static forPath(e,t,n){if(e.length%2!=0)throw new Ur("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Mg(t,new Vd(t._delegate,n,new ai(e)))}static forKey(e,t,n){return new Mg(t,new Vd(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new jg(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new jg(this.firestore,qd(this._delegate,e))}catch(e){throw Fg(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Vd&&jd(this._delegate,e)}set(e,t){t=Eg("DocumentReference.set",t);try{return t?lg(this._delegate,e,t):lg(this._delegate,e)}catch(e){throw Fg(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?dg(this._delegate,e):dg(this._delegate,e,t,...n)}catch(e){throw Fg(e,"updateDoc()","DocumentReference.update()")}}delete(){return mg(Rd((e=this._delegate).firestore,Xd),[new Da(e._key,ma.none())]);var e}onSnapshot(...e){var t=Lg(e),n=Og(e,e=>new Vg(this.firestore,new ig(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return fg(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?cg:"server"===(null==e?void 0:e.source)?function(t){t=Rd(t,Vd);const n=Rd(t.firestore,Xd);return Ed(Yd(n),t._key,{source:"server"}).then(e=>pg(n,t,e))}:function(t){t=Rd(t,Vd);const n=Rd(t.firestore,Xd);return Ed(Yd(n),t._key).then(e=>pg(n,t,e))})(this._delegate),t.then(e=>new Vg(this.firestore,new ig(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Mg(this.firestore,e?this._delegate.withConverter(Rg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Fg(e,t,n){return e.message=e.message.replace(t,n),e}function Lg(e){for(const t of e)if("object"==typeof t&&!xg(t))return t;return{}}function Og(e,t){var n;let r;return r=xg(e[0])?e[0]:xg(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class Vg{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Mg(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return ag(this._delegate,e._delegate)}}class Pg extends Vg{data(e){var t=this._delegate.data(e);return void 0!==t||Pr(),t}}class Bg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Cg(e)}where(e,t,n){try{return new Bg(this.firestore,jf(this._delegate,(r=n,i=t,s=Pf("where",e),Gf._create(s,i,r))))}catch(e){throw Fg(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new Bg(this.firestore,jf(this._delegate,([n,r="asc"]=[e,t],i=r,s=Pf("orderBy",n),$f._create(s,i))))}catch(e){throw Fg(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new Bg(this.firestore,jf(this._delegate,(Md("limit",t=e),Kf._create("limit",t,"F"))))}catch(e){throw Fg(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Bg(this.firestore,jf(this._delegate,(Md("limitToLast",t=e),Kf._create("limitToLast",t,"L"))))}catch(e){throw Fg(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Bg(this.firestore,jf(this._delegate,function(...e){return Qf._create("startAt",e,!0)}(...e)))}catch(e){throw Fg(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Bg(this.firestore,jf(this._delegate,function(...e){return Qf._create("startAfter",e,!1)}(...e)))}catch(e){throw Fg(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Bg(this.firestore,jf(this._delegate,function(...e){return Hf._create("endBefore",e,!1)}(...e)))}catch(e){throw Fg(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Bg(this.firestore,jf(this._delegate,function(...e){return Hf._create("endAt",e,!0)}(...e)))}catch(e){throw Fg(e,"endAt()","Query.endAt()")}}isEqual(e){return Gd(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?hg:"server"===(null==e?void 0:e.source)?function(t){t=Rd(t,Pd);const n=Rd(t.firestore,Xd),e=Yd(n),r=new ug(n);return _d(e,t._query,{source:"server"}).then(e=>new og(n,r,t,e))}:function(t){t=Rd(t,Pd);const n=Rd(t.firestore,Xd),e=Yd(n),r=new ug(n);return Bf(t._query),_d(e,t._query).then(e=>new og(n,r,t,e))})(this._delegate),t.then(e=>new Ug(this.firestore,new og(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Lg(e),n=Og(e,e=>new Ug(this.firestore,new og(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return fg(this._delegate,t,n)}withConverter(e){return new Bg(this.firestore,e?this._delegate.withConverter(Rg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class qg{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Pg(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Ug{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Bg(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new Pg(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new qg(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Pg(this._firestore,e))})}isEqual(e){return ag(this._delegate,e._delegate)}}class jg extends Bg{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new Mg(this.firestore,e):null}doc(e){try{return void 0===e?new Mg(this.firestore,Ud(this._delegate)):new Mg(this.firestore,Ud(this._delegate,e))}catch(e){throw Fg(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Rd(e.firestore,Xd),r=Ud(e),i=tg(e.converter,t);return mg(n,[yf(pf(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,ma.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Mg(this.firestore,e))}isEqual(e){return jd(this._delegate,e._delegate)}withConverter(e){return new jg(this.firestore,e?this._delegate.withConverter(Rg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Gg(e){return Rd(e,Vd)}const zg={Firestore:Ag,GeoPoint:cf,Timestamp:ti,Blob:Sg,Transaction:Ng,WriteBatch:kg,DocumentReference:Mg,DocumentSnapshot:Vg,Query:Bg,QueryDocumentSnapshot:Pg,QuerySnapshot:Ug,CollectionReference:jg,FieldPath:class $g{constructor(...e){this._delegate=new af(...e)}static documentId(){return new $g(oi.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof af&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Kg{constructor(e){this._delegate=e}static serverTimestamp(){const e=new bf("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Kg(e)}static delete(){const e=new vf("deleteField");return e._methodName="FieldValue.delete",new Kg(e)}static arrayUnion(...e){const t=function(...e){return new If("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Kg(t)}static arrayRemove(...e){const t=function(...e){return new Ef("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Kg(t)}static increment(e){const t=new _f("increment",e);return t._methodName="FieldValue.increment",new Kg(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,Rr.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Hd=t.default,Wd=(e,t)=>new Ag(e,t,new Dg),Hd.INTERNAL.registerComponent(new p("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Wd(t,n)},"PUBLIC").setServiceProps(Object.assign({},zg))),Hd.registerVersion("@firebase/firestore-compat","0.3.12")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-firestore-compat.js - be sure to load firebase-app.js first.")}});
- //# sourceMappingURL=firebase-firestore-compat.js.map
|