!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(Wg,Hg){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(Wg);function n(t){const n=[];let r=0;for(let i=0;i>6|192:(55296==(64512&e)&&i+1>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>6,t=63&c;u||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const i=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,s=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},a=()=>{try{return i()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||s()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function h(){return!function(){var e=null===(e=a())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class d extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,f.prototype.create)}}class f{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(g,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new d(i,s,n)}}const g=/\{\$([^}]+)}/g;function m(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;var i=e[a],s=t[a];if(p(i)&&p(s)){if(!m(i,s))return!1}else if(i!==s)return!1}for(const o of r)if(!n.includes(o))return!1;return!0}function p(e){return null!==e&&"object"==typeof e}function y(e){return e&&e._delegate?e._delegate:e}class v{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}(Hd=l=l||{})[Hd.DEBUG=0]="DEBUG",Hd[Hd.VERBOSE=1]="VERBOSE",Hd[Hd.INFO=2]="INFO",Hd[Hd.WARN=3]="WARN",Hd[Hd.ERROR=4]="ERROR",Hd[Hd.SILENT=5]="SILENT";const w={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},_=l.INFO,b={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},I=(e,t,...n)=>{if(!(t>>0),N=0;function k(e,t,n){return e.call.apply(e.bind,arguments)}function R(t,n,e){if(!t)throw Error();if(2{};x.addEventListener("test",n,t),x.removeEventListener("test",n,t)}catch(e){}return e}();function j(e){return/^[\s\xa0]*$/.test(e)}function G(){var e=x.navigator;return(e=e&&e.userAgent)?e:""}function z(e){return-1!=G().indexOf(e)}function K(e){return K[" "](e),e}K[" "]=function(){};var $,Q=z("Opera"),W=z("Trident")||z("MSIE"),H=z("Edge"),Y=H||W,X=z("Gecko")&&!(-1!=G().toLowerCase().indexOf("webkit")&&!z("Edge"))&&!(z("Trident")||z("MSIE"))&&!z("Edge"),J=-1!=G().toLowerCase().indexOf("webkit")&&!z("Edge");function Z(){var e=x.document;return e?e.documentMode:void 0}e:{var ee="",te=(te=G(),X?/rv:([^\);]+)(\)|;)/.exec(te):H?/Edge\/([\d\.]+)/.exec(te):W?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(te):J?/WebKit\/(\S+)/.exec(te):Q?/(?:Version)[ \/]?(\S+)/.exec(te):void 0);if(te&&(ee=te?te[1]:""),W){te=Z();if(null!=te&&te>parseFloat(ee)){$=String(te);break e}}$=ee}var ne=x.document&&W&&(Z()||parseInt($,10))||void 0;function re(e,t){if(q.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(X){e:{try{K(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:ie[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&re.$.h.call(this)}}O(re,q);var ie={2:"touch",3:"pen",4:"mouse"};re.prototype.h=function(){re.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var se="closure_listenable_"+(1e6*Math.random()|0),ae=0;function oe(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=++ae,this.fa=this.ia=!1}function ue(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function ce(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function he(e){const t={};for(const n in e)t[n]=e[n];return t}const le="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function de(t){let n,r;for(let i=1;i>>0);function Se(t){return"function"==typeof t?t:(t[Te]||(t[Te]=function(e){return t.handleEvent(e)}),t[Te])}function xe(){F.call(this),this.i=new fe(this),(this.S=this).J=null}function De(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 q(t,e):t instanceof q?t.target=t.target||e:(a=t,de(t=new q(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Ce(s,r,!0,t)&&a;if(a=Ce(s=t.g=e,r,!0,t)&&a,a=Ce(s,r,!1,t)&&a,n)for(i=0;inew ke,e=>e.reset());class ke{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 Re,Le=!1,Me=new class{constructor(){this.h=this.g=null}add(e,t){const n=Ne.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Oe=()=>{const e=x.Promise.resolve(void 0);Re=()=>{e.then(Fe)}};var Fe=()=>{for(var e;e=function(){var e=Me;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){x.setTimeout(()=>{throw e},0)}(e)}var t=Ne;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Le=!1};function Pe(e,t){xe.call(this),this.h=e||1,this.g=t||x,this.j=L(this.qb,this),this.l=Date.now()}function Ve(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Be(e,t,n){if("function"==typeof e)n&&(e=L(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=L(e.handleEvent,e)}return 2147483647{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&&(x.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Ue(e){F.call(this),this.h=e,this.g={}}O(Ue,F);var je=[];function Ge(e,t,n,r){Array.isArray(n)||(n&&(je[0]=n.toString()),n=je);for(var i=0;ia.length?mt:(a=a.slice(u,u+o),s.o=u+o,a)))==mt){4==t&&(e.s=4,Ze(14),r=!1),$e(e.j,e.m,null,"[Incomplete Response]");break}if(i==gt){e.s=4,Ze(15),$e(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}$e(e.j,e.m,i,null),St(e,i)}var s,a,o,u;vt(e)&&0!=e.o&&(e.h.g=e.h.g.slice(e.o),e.o=0),4!=t||0!=n.length||e.h.h||(e.s=1,Ze(16),r=!1),e.i=e.i&&r,r?0>4&15).toString(16)+(15&e).toString(16)}Ct.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Ft(t,Vt,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Ft(t,Vt,!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)?qt:Bt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Ft(n,jt)),e.join("")};var Vt=/[#\/\?@]/g,Bt=/[#\?:]/g,qt=/[#\?]/g,Ut=/[#\?@]/g,jt=/#/g;function Gt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function zt(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.j}function Jt(e){return e.h?1:e.g?e.g.size:0}function Zt(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function en(e,t){e.g?e.g.add(t):e.h=t}function tn(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function nn(t){if(null!=t.h)return t.i.concat(t.h.F);if(null==t.g||0===t.g.size)return V(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.F);return e}}Yt.prototype.cancel=function(){if(this.i=nn(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 rn,sn=class{stringify(e){return x.JSON.stringify(e,void 0)}parse(e){return x.JSON.parse(e,void 0)}};function an(){this.g=new sn}function on(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function un(e){this.l=e.ec||null,this.j=e.ob||!1}function cn(e,t){xe.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=hn,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}O(un,it),un.prototype.g=function(){return new cn(this.l,this.j)},un.prototype.i=(rn={},function(){return rn}),O(cn,xe);var hn=0;function ln(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function dn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,fn(e)}function fn(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(E=cn.prototype).open=function(e,t){if(this.readyState!=hn)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,fn(this)},E.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||x).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},E.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,dn(this)),this.readyState=hn},E.$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,fn(this)),this.g&&(this.readyState=3,fn(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(void 0!==x.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;ln(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},E.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?dn:fn)(this),3==this.readyState&&ln(this))},E.Za=function(e){this.g&&(this.response=this.responseText=e,dn(this))},E.Ya=function(e){this.g&&(this.response=e,dn(this))},E.ka=function(){this.g&&dn(this)},E.setRequestHeader=function(e,t){this.v.append(e,t)},E.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},E.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(cn.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var gn=x.JSON.parse;function mn(e){xe.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=pn,this.L=this.M=!1}O(mn,xe);var pn="",yn=/^https?$/i,vn=["POST","PUT"];function wn(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,_n(e),In(e)}function _n(e){e.F||(e.F=!0,De(e,"complete"),De(e,"error"))}function bn(e){if(e.h&&void 0!==S&&(!e.C[1]||4!=Tn(e)||2!=e.da()))if(e.v&&4==Tn(e))Be(e.La,0,e);else if(De(e,"readystatechange"),4==Tn(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(Dt)[1]||null)&&x.self&&x.self.location&&(r=x.self.location.protocol.slice(0,-1)),n=!yn.test(r?r.toLowerCase():"")),t=n),t)De(e,"complete"),De(e,"success");else{e.m=6;try{var a=2{}:null;e.g=null,e.C=null,t||De(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function En(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(x.clearTimeout(e.A),e.A=null)}function Tn(e){return e.g?e.g.readyState:0}function Sn(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case pn:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function xn(e){let n="";return ce(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Dn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=xn(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Lt(e,t,n))}function Cn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function An(e){this.Ga=0,this.j=[],this.l=new Ke,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=Cn("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=Cn("baseRetryDelayMs",5e3,e),this.hb=Cn("retryDelaySeedMs",1e4,e),this.eb=Cn("forwardChannelMaxRetries",2,e),this.xa=Cn("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Yt(e&&e.concurrentRequestLimit),this.Ja=new an,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=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=tt(L(r.Na,r,i),Gn(r,r.C)),r.C++,0))))&&(2!=a||!Vn(e)))switch(s&&0>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function nr(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}(E=mn.prototype).Oa=function(e){this.M=e},E.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||dt).g(),this.C=this.u?st(this.u):st(dt),this.g.onreadystatechange=L(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void wn(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=x.FormData&&e instanceof x.FormData,0<=P(vn,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{En(this),0>>r&255;return e};var rr={};function ir(e){return-128<=e&&e<128?(t=e,n=function(e){return new nr([0|e],e<0?-1:0)},r=rr,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new nr([0|e],e<0?-1:0);var t,n,r}function sr(e){if(isNaN(e)||!isFinite(e))return or;if(e<0)return dr(sr(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=ar;return new nr(t,0)}var ar=4294967296,or=ir(0),ur=ir(1),cr=ir(16777216);function hr(e){if(0==e.h){for(var t=0;t>>16,e[t]&=65535,t++}function mr(e,t){this.g=e,this.h=t}function pr(e,t){if(hr(t))throw Error("division by zero");if(hr(e))return new mr(or,or);if(lr(e))return t=pr(dr(e),t),new mr(dr(t.g),dr(t.h));if(lr(t))return t=pr(e,dr(t)),new mr(dr(t.g),t.h);if(30>>31;return new nr(n,e.h)}function vr(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new nr(i,e.h)}(E=nr.prototype).ea=function(){if(lr(this))return-dr(this).ea();for(var e=0,t=1,n=0;n>>0).toString(e);if(hr(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},E.D=function(e){return e<0?0:e>>16)+(this.D(i)>>>16)+(e.D(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new nr(n,-2147483648&n[n.length-1]?-1:0)},E.R=function(e){if(hr(this)||hr(e))return or;if(lr(this))return lr(e)?dr(this).R(dr(e)):dr(dr(this).R(e));if(lr(e))return dr(this.R(dr(e)));if(this.X(cr)<0&&e.X(cr)<0)return sr(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>>16,a=65535&this.D(r),o=e.D(i)>>>16,u=65535&e.D(i);n[2*r+2*i]+=a*u,gr(n,2*r+2*i),n[2*r+2*i+1]+=s*u,gr(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,gr(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,gr(n,2*r+2*i+2)}for(r=0;r`${this.name}: [code=${this.code}]: ${this.message}`}}class Gr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class zr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Kr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(kr.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 Qr{constructor(e){this.t=e,this.currentUser=kr.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 Gr;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new Gr,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{Or("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(Or("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new Gr))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(Or("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(qr("string"==typeof e.accessToken),new zr(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 qr(null===e||"string"==typeof e),new kr(e)}}class Wr{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=kr.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Hr{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Wr(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(kr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Yr{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0{null!=e.error&&Or("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,Or("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{Or("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):Or("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(qr("string"==typeof e.token),this.R=e.token,new Yr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Jr{static newId(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;er(e,n[t]))}function ti(e){return e+"\0"}class ni{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new jr(Ur.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new jr(Ur.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new jr(Ur.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new jr(Ur.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ni.fromMillis(Date.now())}static fromDate(e){return ni.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ni(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Zr(this.nanoseconds,e.nanoseconds):Zr(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 ri{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ri(e)}static min(){return new ri(new ni(0,0))}static max(){return new ri(new ni(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 ii{constructor(e,t,n){void 0===t?t=0:t>e.length&&Br(),void 0===n?n=e.length-t:n>e.length-t&&Br(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ii.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ii?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.lengthi)return 1}return e.lengtht.length?1:0}}class si extends ii{construct(e,t,n){return new si(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new jr(Ur.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0(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 jr(Ur.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(;r2===e.kind)}function li(e){return e.fields.filter(e=>2!==e.kind)}ci.UNKNOWN_ID=-1;class di{constructor(e,t){this.fieldPath=e,this.kind=t}}class fi{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new fi(0,pi.min())}}function gi(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=ri.fromTimestamp(1e9===r?new ni(n+1,0):new ni(n,r));return new pi(r,ui.empty(),t)}function mi(e){return new pi(e.readTime,e.key,-1)}class pi{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new pi(ri.min(),ui.empty(),-1)}static max(){return new pi(ri.max(),ui.empty(),-1)}}function yi(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ui.comparator(e.documentKey,t.documentKey),0!==n?n:Zr(e.largestBatchId,t.largestBatchId))}const vi="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class wi{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function _i(e){if(e.code!==Ur.FAILED_PRECONDITION||e.message!==vi)throw e;Or("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&&Br(),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(o,u){return new bi((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e{i[a]=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 Gr,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{e.error?this.V.reject(new Si(n,e.error)):this.V.resolve()},this.transaction.onerror=e=>{var t=Ni(e.target.error);this.V.reject(new Si(n,t))}}static open(e,t,n,r){try{return new Ii(t,e.transaction(r,n))}catch(e){throw new Si(t,e)}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(Or("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Di(t)}}class Ei{constructor(e,t,n){this.name=e,this.version=t,this.p=n,12.2===Ei.S(u())&&Fr("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 Or("SimpleDb","Removing database:",e),Ci(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{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new Si(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 jr(Ur.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 jr(Ur.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 Si(s,t))},i.onupgradeneeded=e=>{Or("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.p.N(t,i.transaction,e.oldVersion,this.version).next(()=>{Or("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.B&&(this.db.onversionchange=e=>this.B(e)),this.db}L(t){this.B=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.O(e);const t=Ii.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.g(),e)).catch(e=>(t.abort(e),bi.reject(e))).toPromise();return s.catch(()=>{}),await t.m,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Or("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 Ti{constructor(e){this.k=e,this.q=!1,this.K=null}get isDone(){return this.q}get $(){return this.K}set cursor(e){this.k=e}done(){this.q=!0}U(e){this.K=e}delete(){return Ci(this.k.delete())}}class Si extends jr{constructor(e,t){super(Ur.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function xi(e){return"IndexedDbTransactionError"===e.name}class Di{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Or("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Or("SimpleDb","PUT",this.store.name,"",e),this.store.put(e)),Ci(n)}add(e){return Or("SimpleDb","ADD",this.store.name,e,e),Ci(this.store.add(e))}get(t){return Ci(this.store.get(t)).next(e=>(Or("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Or("SimpleDb","DELETE",this.store.name,e),Ci(this.store.delete(e))}count(){return Or("SimpleDb","COUNT",this.store.name),Ci(this.store.count())}W(e,n){const t=this.options(e,n),r=t.index?this.store.index(t.index):this.store;if("function"==typeof r.getAll){const e=r.getAll(t.range);return new bi((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{const e=this.cursor(t),n=[];return this.G(e,(e,t)=>{n.push(t)}).next(()=>n)}}j(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)}})}H(e,t){Or("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.J=!1;var r=this.cursor(n);return this.G(r,(e,t,n)=>n.delete())}Y(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.G(r,t)}Z(i){const e=this.cursor({});return new bi((n,r)=>{e.onerror=e=>{var t=Ni(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()}})}G(e,s){const a=[];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 Ti(t),r=s(t.primaryKey,t.value,n);if(r instanceof bi){const e=r.catch(e=>(n.done(),bi.reject(e)));a.push(e)}n.isDone?i():null===n.$?t.continue():t.continue(n.$)}else i()}}).next(()=>bi.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.J?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Ci(e){return new bi((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Ni(e.target.error);r(t)}})}let Ai=!1;function Ni(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 jr("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 ki{constructor(e,t){this.asyncQueue=e,this.X=t,this.task=null}start(){this.ee(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}ee(e){Or("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Or("IndexBackfiller",`Documents written: ${await this.X.te()}`)}catch(e){xi(e)?Or("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await _i(e)}await this.ee(6e4)})}}class Ri{constructor(e,t){this.localStore=e,this.persistence=t}async te(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.ne(e,t))}ne(e,t){const n=new Set;let r=t,i=!0;return bi.doWhile(()=>!0===i&&0this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(Or("IndexBackfiller",`Processing collection: ${t}`),this.re(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}re(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.ie(n,e)).next(e=>(Or("IndexBackfiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}ie(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=mi(t);0this.se(e),this.oe=e=>t.writeSequenceNumber(e))}se(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.oe&&this.oe(e),e}}function Mi(e){return null==e}function Oi(e){return 0===e&&1/e==-1/0}function Fi(e){return"number"==typeof e&&Number.isInteger(e)&&!Oi(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Pi(e){let t="";for(let n=0;n__PRIVATE_lastReasonableEscapeIndex)&&Br(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Br()}a=n+2}return new si(r)}Li._e=-1;const qi=["userId","batchId"];function Ui(e,t){return[e,Pi(t)]}function ji(e,t,n){return[e,Pi(t),n]}const Gi={},zi=["prefixPath","collectionGroup","readTime","documentId"],Ki=["prefixPath","collectionGroup","documentId"],$i=["collectionGroup","readTime","prefixPath","documentId"],Qi=["canonicalId","targetId"],Wi=["targetId","path"],Hi=["path","targetId"],Yi=["collectionId","parent"],Xi=["indexId","uid"],Ji=["uid","sequenceNumber"],Zi=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],es=["indexId","uid","orderedDocumentKey"],ts=["userId","collectionPath","documentId"],ns=["userId","collectionPath","largestBatchId"],rs=["userId","collectionGroup","largestBatchId"],is=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ss=[...is,"documentOverlays"],as=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],os=as,us=[...os,"indexConfiguration","indexState","indexEntries"];class cs extends wi{constructor(e,t){super(),this.ae=e,this.currentSequenceNumber=t}}function hs(e,t){var n=e;return Ei.M(n.ae,t)}function ls(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ds(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function fs(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class gs{constructor(e,t){this.comparator=e,this.root=t||ps.EMPTY}insert(e,t){return new gs(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ps.BLACK,null,null))}remove(e){return new gs(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ps.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(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 ms(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ms(this.root,e,this.comparator,!1)}getReverseIterator(){return new ms(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ms(this.root,e,this.comparator,!0)}}class ms{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(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 vs(this.data.getIterator())}getIteratorFrom(e){return new vs(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size{t=t.add(e)}),t}isEqual(e){if(!(e instanceof ys))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 ys(this.comparator);return t.data=e,t}}class vs{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function ws(e){return e.hasNext()?e.getNext():void 0}class _s{constructor(e){(this.fields=e).sort(oi.comparator)}static empty(){return new _s([])}unionWith(e){let t=new ys(oi.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new _s(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return ei(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;neOs(e,t))}function Ps(e,t){if(e===t)return 0;var n,r,i,s,a=Ms(e),o=Ms(t);if(a!==o)return Zr(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Zr(e.booleanValue,t.booleanValue);case 2:return r=t,i=Ss((n=e).integerValue||n.doubleValue),s=Ss(r.integerValue||r.doubleValue),in.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 Qs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Ws(e,t){var n=Ps(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=Ps(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Ys{constructor(e){this.value=e}static empty(){return new Ys({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;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());Ks(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Os(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;rn[e]=t);for(const e of t)delete n[e]}clone(){return new Ys($s(this.value))}}class Xs{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Xs(e,0,ri.min(),ri.min(),ri.min(),Ys.empty(),0)}static newFoundDocument(e,t,n,r){return new Xs(e,1,t,ri.min(),n,r,0)}static newNoDocument(e,t){return new Xs(e,2,t,ri.min(),ri.min(),Ys.empty(),0)}static newUnknownDocument(e,t){return new Xs(e,3,t,ri.min(),ri.min(),Ys.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(ri.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=Ys.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ys.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ri.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 Js{constructor(e,t){this.position=e,this.inclusive=t}}function Zs(e,t,n){let r=0;for(let i=0;i":return 0=":return 0<=e;default:return Br()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class ia extends na{constructor(e,t){super(),this.filters=e,this.op=t,this.ue=null}static create(e,t){return new ia(e,t)}matches(t){return sa(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ue||(this.ue=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ue}getFilters(){return Object.assign([],this.filters)}}function sa(e){return"and"===e.op}function aa(e){return"or"===e.op}function oa(e){return ua(e)&&sa(e)}function ua(e){for(const t of e.filters)if(t instanceof ia)return!1;return!0}function ca(e,t){var n=e.filters.concat(t);return ia.create(n,e.op)}function ha(e){return e instanceof ra?`${(t=e).field.canonicalString()} ${t.op} ${Bs(t.value)}`:e instanceof ia?(e=e).op.toString()+" {"+e.getFilters().map(ha).join(" ,")+"}":"Filter";var t}class la extends ra{constructor(e,t,n){super(e,t,n),this.key=ui.fromName(n.referenceValue)}matches(e){var t=ui.comparator(e.key,this.key);return this.matchesComparison(t)}}class da extends ra{constructor(e,t){super(e,"in",t),this.keys=ga(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class fa extends ra{constructor(e,t){super(e,"not-in",t),this.keys=ga(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function ga(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ui.fromName(e.referenceValue))}class ma extends ra{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return js(t)&&Fs(t.arrayValue,this.value)}}class pa extends ra{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Fs(this.value.arrayValue,t)}}class ya extends ra{constructor(e,t){super(e,"not-in",t)}matches(e){if(Fs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Fs(this.value.arrayValue,t)}}class va extends ra{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!js(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Fs(this.value.arrayValue,e))}}class wa{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ce=null}}function _a(e,t=null,n=[],r=[],i=null,s=null,a=null){return new wa(e,t,n,r,i,s,a)}function ba(e){const t=e;if(null===t.ce){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 ra)return e.field.canonicalString()+e.op.toString()+Bs(e.value);if(oa(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=>Bs(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Bs(e)).join(",")),t.ce=e}return t.ce}function Ia(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;ie&&r(t,i.filters[n]),!0):void Br();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!ea(e.startAt,t.startAt)&&ea(e.endAt,t.endAt)}function Ea(e){return ui.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Ta(e,t){return e.filters.filter(e=>e instanceof ra&&e.field.isEqual(t))}function Sa(t,n,r){let i=Ls,s=!0;for(const r of Ta(t,n)){let e=Ls,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Ls:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?qs(ks.empty(),ui.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Br();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Ls}Ws({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?qs(ks.empty(),ui.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Rs:Br(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Rs}0{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t}(n);e.forEach(e=>{t.has(e.canonicalString())||e.isKeyField()||n.le.push(new ta(e,r))}),t.has(oi.keyField().canonicalString())||n.le.push(new ta(oi.keyField(),r))}return n.le}function La(e){const t=e;return t.he||(t.he=function(e,t){if("F"===e.limitType)return _a(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new ta(e.field,t)});var n=e.endAt?new Js(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Js(e.startAt.position,e.startAt.inclusive):null;return _a(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,Ra(e))),t.he}function Ma(e,t){var n=e.filters.concat([t]);return new Da(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Oa(e,t,n){return new Da(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Fa(e,t){return Ia(La(e),La(t))&&e.limitType===t.limitType}function Pa(e){return`${ba(La(e))}|lt:${e.limitType}`}function Va(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0ha(e)).join(", ")}]`),Mi(e.limit)||(t+=", limit: "+e.limit),0function(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=>Bs(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Bs(e)).join(",")),`Target(${t})`}(La(e))}; limitType=${e.limitType})`}function Ba(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ui.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of Ra(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=Ra(t),r=Zs(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=Ra(t),r=Zs(n,t,i),n.inclusive?0<=r:0{let n=!1;for(const r of Ra(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ui.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Ps(r,i):Br()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Br()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class ja{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{for(const[e,n]of t)r(e,n)})}isEmpty(){return fs(this.inner)}size(){return this.innerSize}}const Ga=new gs(ui.comparator);const za=new gs(ui.comparator);function Ka(...e){let t=za;for(const n of e)t=t.insert(n.key,n);return t}function $a(e){let n=za;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function Qa(){return new ja(e=>e.toString(),(e,t)=>e.isEqual(t))}const Wa=new gs(ui.comparator),Ha=new ys(ui.comparator);function Ya(...e){let t=Ha;for(const n of e)t=t.add(n);return t}const Xa=new ys(Zr);function Ja(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:Oi(t)?"-0":t}}function Za(e){return{integerValue:""+e}}function eo(e,t){return Fi(t)?Za(t):Ja(e,t)}class to{constructor(){this._=void 0}}function no(e,t){return e instanceof uo?Us(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class ro extends to{}class io extends to{constructor(e){super(),this.elements=e}}function so(e,t){const n=ho(t);for(const t of e.elements)n.some(e=>Os(e,t))||n.push(t);return{arrayValue:{values:n}}}class ao extends to{constructor(e){super(),this.elements=e}}function oo(e,t){let n=ho(t);for(const t of e.elements)n=n.filter(e=>!Os(e,t));return{arrayValue:{values:n}}}class uo extends to{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function co(e){return Ss(e.integerValue||e.doubleValue)}function ho(e){return js(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lo{constructor(e,t){this.field=e,this.transform=t}}class fo{constructor(e,t){this.version=e,this.transformResults=t}}class go{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new go}static exists(e){return new go(void 0,e)}static updateTime(e){return new go(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 mo(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class po{}function yo(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new xo(e.key,go.none()):new bo(e.key,e.data,go.none());{const i=e.data,s=Ys.empty();let t=new ys(oi.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1e.field))}(e,t,n,r):(t=t,n=n,mo(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function _o(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&&ei(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof io&&t instanceof io||e instanceof ao&&t instanceof ao?ei(e.elements,t.elements,Os):e instanceof uo&&t instanceof uo?Os(e.Ie,t.Ie):e instanceof ro&&t instanceof ro)}(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 bo extends po{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 Io extends po{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 Eo(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 To(e,t,n){const r=new Map;qr(e.length===n.length);for(let h=0;h{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=yo(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(ri.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Ya())}isEqual(e){return this.batchId===e.batchId&&ei(this.mutations,e.mutations,(e,t)=>_o(e,t))&&ei(this.baseMutations,e.baseMutations,(e,t)=>_o(e,t))}}class Ao{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){qr(e.mutations.length===n.length);let r=Wa;var i=e.mutations;for(let s=0;ss.insert(e)),s}insert(t){if(0!==this.Te){const n=Fo(t),[r,i]=Po(n);for(let e=0;e{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:Br()}}),new Uo(this.ye,this.we,n,r,i)}Fe(){this.Se=!1,this.pe=Wo()}Me(e,t){this.Se=!0,this.pe=this.pe.insert(e,t)}xe(e){this.Se=!0,this.pe=this.pe.remove(e)}Oe(){this.ge+=1}Ne(){--this.ge,qr(0<=this.ge)}Be(){this.Se=!0,this.we=!0}}class $o{constructor(e){this.Le=e,this.ke=new Map,this.qe=Ga,this.Qe=Qo(),this.Ke=new gs(Zr)}$e(e){for(const t of e.Ve)e.me&&e.me.isFoundDocument()?this.Ue(t,e.me):this.We(t,e.key,e.me);for(const n of e.removedTargetIds)this.We(n,e.key,e.me)}Ge(n){this.forEachTarget(n,e=>{const t=this.ze(e);switch(n.state){case 0:this.je(e)&&t.Ce(n.resumeToken);break;case 1:t.Ne(),t.be||t.Fe(),t.Ce(n.resumeToken);break;case 2:t.Ne(),t.be||this.removeTarget(e);break;case 3:this.je(e)&&(t.Be(),t.Ce(n.resumeToken));break;case 4:this.je(e)&&(this.He(e),t.Ce(n.resumeToken));break;default:Br()}})}forEachTarget(e,n){0{this.je(t)&&n(t)})}Je(e){const t=e.targetId,n=e.fe.count,r=this.Ye(t);if(r){var i=r.target;if(Ea(i))if(0===n){const e=new ui(i.path);this.We(t,e,Xs.newNoDocument(e,ri.min()))}else qr(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),s=n?this.et(n,e,r):1;if(0!==s){this.He(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}}}}}Xe(e){var t=e.fe.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=xs(n).toUint8Array()}catch(e){if(e instanceof bs)return Pr("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new Vo(i,r,t)}catch(e){return Pr(e instanceof Bo?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Te?null:s}et(e,t,n){return t.fe.count===n-this.rt(e,t.targetId)?0:2}rt(n,r){const e=this.Le.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Le.nt(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.We(r,e,null),i++)}),i}it(r){const i=new Map;this.ke.forEach((e,t)=>{var n=this.Ye(t);if(n){if(e.current&&Ea(n.target)){const i=new ui(n.target.path);null!==this.qe.get(i)||this.st(t,i)||this.We(t,i,Xs.newNoDocument(i,r))}e.De&&(i.set(t,e.ve()),e.Fe())}});let s=Ya();this.Qe.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.qe.forEach((e,t)=>t.setReadTime(r));var e=new qo(r,i,this.Ke,this.qe,s);return this.qe=Ga,this.Qe=Qo(),this.Ke=new gs(Zr),e}Ue(e,t){var n;this.je(e)&&(n=this.st(e,t.key)?2:0,this.ze(e).Me(t.key,n),this.qe=this.qe.insert(t.key,t),this.Qe=this.Qe.insert(t.key,this.ot(t.key).add(e)))}We(e,t,n){if(this.je(e)){const r=this.ze(e);this.st(e,t)?r.Me(t,1):r.xe(t),this.Qe=this.Qe.insert(t,this.ot(t).delete(e)),n&&(this.qe=this.qe.insert(t,n))}}removeTarget(e){this.ke.delete(e)}Ze(e){var t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Oe(e){this.ze(e).Oe()}ze(e){let t=this.ke.get(e);return t||(t=new Ko,this.ke.set(e,t)),t}ot(e){let t=this.Qe.get(e);return t||(t=new ys(Zr),this.Qe=this.Qe.insert(e,t)),t}je(e){var t=null!==this.Ye(e);return t||Or("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){var t=this.ke.get(e);return t&&t.be?null:this.Le._t(e)}He(t){this.ke.set(t,new Ko),this.Le.getRemoteKeysForTarget(t).forEach(e=>{this.We(t,e,null)})}st(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Qo(){return new gs(ui.comparator)}function Wo(){return new gs(ui.comparator)}const Ho={asc:"ASCENDING",desc:"DESCENDING"},Yo={"<":"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"},Xo={and:"AND",or:"OR"};class Jo{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Zo(e,t){return e.useProto3Json||Mi(t)?t:{value:t}}function eu(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 tu(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function nu(e){return qr(!!e),ri.fromTimestamp((t=Ts(e),new ni(t.seconds,t.nanos)));var t}function ru(e,t){return iu(e,t).canonicalString()}function iu(e,t){const n=(e=e,new si(["projects",e.projectId,"databases",e.database]).child("documents"));return void 0===t?n:n.child(t)}function su(e){var t=si.fromString(e);return qr(Eu(t)),t}function au(e,t){return ru(e.databaseId,t.path)}function ou(e,t){const n=su(t);if(n.get(1)!==e.databaseId.projectId)throw new jr(Ur.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 jr(Ur.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ui(lu(n))}function uu(e,t){return ru(e.databaseId,t)}function cu(e){var t=su(e);return 4===t.length?si.emptyPath():lu(t)}function hu(e){return new si(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function lu(e){return qr(4t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof Do))return Br();n={verify:au(e,t.key)}}return 0function(e){var t=e.transform;if(t instanceof ro)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof io)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof ao)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof uo)return{fieldPath:e.field.canonicalString(),increment:t.Ie};throw Br()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,eu(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:Br())),n;var r}function mu(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?go.updateTime(nu(i.updateTime)):void 0!==i.exists?go.exists(i.exists):go.none():go.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)qr("REQUEST_TIME"===t.setToServerValue),n=new ro;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new io(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new ao(e)}else"increment"in t?n=new uo(e,t.increment):Br();var r=oi.fromServerFormat(t.fieldPath);return new lo(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=ou(t,e.update.name),a=new Ys({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new _s(t.map(e=>oi.fromServerFormat(e)))}(e.updateMask);return new Io(s,a,t,n,r)}return new bo(s,a,n,r)}if(e.delete){const r=ou(t,e.delete);return new xo(r,n)}if(e.verify){const r=ou(t,e.verify);return new Do(r,n)}return Br()}function pu(e,t){return{documents:[uu(e,t.path)]}}function yu(e,t){const n={structuredQuery:{}},r=t.path;let i;null!==t.collectionGroup?(i=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=uu(e,i);var s=function(e){if(0!==e.length)return function n(e){return e instanceof ra?function(e){if("=="===e.op){if(zs(e.value))return{unaryFilter:{field:bu(e.field),op:"IS_NAN"}};if(Gs(e.value))return{unaryFilter:{field:bu(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(zs(e.value))return{unaryFilter:{field:bu(e.field),op:"IS_NOT_NAN"}};if(Gs(e.value))return{unaryFilter:{field:bu(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:bu(e.field),op:wu(e.op),value:e.value}}}(e):e instanceof ia?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:_u(e.op),filters:t}}}(e):Br()}(ia.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:bu(e.field),direction:(e=e.dir,Ho[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);s=Zo(e,t.limit);return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),{ut:n,parent:i}}function vu(e){let t=cu(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0";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 Br()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return ia.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Br()}}(e.compositeFilter.op))}(e):Br()}(e);return t instanceof ia&&oa(t)?t.getFilters():[t]}(s.where));let c=[];s.orderBy&&(c=s.orderBy.map(e=>function(e){return new ta(Iu(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let h=null;s.limit&&(h=(e=s.limit,Mi(n="object"==typeof e?e.value:e)?null:n));let l=null;s.startAt&&(l=(r=s.startAt,i=!!r.before,n=r.values||[],new Js(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new Js(s,i))),Ca(t,o,c,u,h,"F",l,d)}function wu(e){return Yo[e]}function _u(e){return Xo[e]}function bu(e){return{fieldPath:e.canonicalString()}}function Iu(e){return oi.fromServerFormat(e.fieldPath)}function Eu(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class Tu{constructor(e,t,n,r,i=ri.min(),s=ri.min(),a=Is.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Tu(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Tu(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Tu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Tu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Su{constructor(e){this.ct=e}}function xu(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Du(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:au(i=e.ct,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:eu(i,e.version.toTimestamp()),createTime:eu(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Cu(t.version)};else{if(!t.isUnknownDocument())return Br();r.unknownDocument={path:n.path.toArray(),version:Cu(t.version)}}var i;return r}function Du(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Cu(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Au(e){var t=new ni(e.seconds,e.nanoseconds);return ri.fromTimestamp(t)}function Nu(t,e){const n=(e.baseMutations||[]).map(e=>mu(t.ct,e));for(let s=0;smu(t.ct,e)),i=ni.fromMillis(e.localWriteTimeMs);return new Co(e.batchId,i,n,r)}function ku(e){var t,n=Au(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?Au(e.lastLimboFreeSnapshotVersion):ri.min(),i=void 0!==e.query.documents?(qr(1===(t=e.query).documents.length),La(Aa(cu(t.documents[0])))):La(vu(e.query));return new Tu(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,Is.fromBase64String(e.resumeToken))}function Ru(e,t){var n=Cu(t.snapshotVersion),r=Cu(t.lastLimboFreeSnapshotVersion),i=Ea(t.target)?pu(e.ct,t.target):yu(e.ct,t.target).ut,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:ba(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Lu(e){var t=vu({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Oa(t,t.limit,"L"):t}function Mu(e,t){return new No(t.largestBatchId,mu(e.ct,t.overlayMutation))}function Ou(e,t){var n=t.path.lastSegment();return[e,Pi(t.path.popLast()),n]}function Fu(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:Cu(r.readTime),documentKey:Pi(r.documentKey.path),largestBatchId:r.largestBatchId}}class Pu{getBundleMetadata(e,t){return Vu(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:Au(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return Vu(e).put({bundleId:(t=t).id,createTime:Cu(nu(t.createTime)),version:t.version})}getNamedQuery(e,t){return Bu(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:Lu(e.bundledQuery),readTime:Au(e.readTime)}})}saveNamedQuery(e,t){return Bu(e).put({name:(t=t).name,readTime:Cu(nu(t.readTime)),bundledQuery:t.bundledQuery})}}function Vu(e){return hs(e,"bundles")}function Bu(e){return hs(e,"namedQueries")}class qu{constructor(e,t){this.serializer=e,this.userId=t}static lt(e,t){var n=t.uid||"";return new qu(e,n)}getOverlay(e,t){return Uu(e).get(Ou(this.userId,t)).next(e=>e?Mu(this.serializer,e):null)}getOverlays(e,t){const n=Qa();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 No(i,t);s.push(this.ht(r,n))}),bi.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Pi(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(Uu(n).H("collectionPathOverlayIndex",t))}),bi.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Qa(),i=Pi(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return Uu(e).W("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=Mu(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=Qa();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Uu(e).Y({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=Mu(this.serializer,t);s.size()s)}ht(e,t){return Uu(e).put(function(e,t,n){var[,r,i]=Ou(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:gu(e.ct,n.mutation)}}(this.serializer,this.userId,t))}}function Uu(e){return hs(e,"documentOverlays")}class ju{constructor(){}Pt(e,t){this.It(e,t),t.Tt()}It(e,t){var n,r;"nullValue"in e?this.Et(t,5):"booleanValue"in e?(this.Et(t,10),t.dt(e.booleanValue?1:0)):"integerValue"in e?(this.Et(t,15),t.dt(Ss(e.integerValue))):"doubleValue"in e?(n=Ss(e.doubleValue),isNaN(n)?this.Et(t,13):(this.Et(t,15),Oi(n)?t.dt(0):t.dt(n))):"timestampValue"in e?(r=e.timestampValue,this.Et(t,20),"string"==typeof r?t.At(r):(t.At(`${r.seconds||""}`),t.dt(r.nanos||0))):"stringValue"in e?(this.Rt(e.stringValue,t),this.Vt(t)):"bytesValue"in e?(this.Et(t,30),t.ft(xs(e.bytesValue)),this.Vt(t)):"referenceValue"in e?this.gt(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.Et(t,45),t.dt(r.latitude||0),t.dt(r.longitude||0)):"mapValue"in e?Qs(e)?this.Et(t,Number.MAX_SAFE_INTEGER):(this.yt(e.mapValue,t),this.Vt(t)):"arrayValue"in e?(this.wt(e.arrayValue,t),this.Vt(t)):Br()}Rt(e,t){this.Et(t,25),this.St(e,t)}St(e,t){t.At(e)}yt(e,t){var n=e.fields||{};this.Et(t,55);for(const e of Object.keys(n))this.Rt(e,t),this.It(n[e],t)}wt(e,t){var n=e.values||[];this.Et(t,50);for(const e of n)this.It(e,t)}gt(e,t){this.Et(t,37),ui.fromName(e).path.forEach(e=>{this.Et(t,60),this.St(e,t)})}Et(e,t){e.dt(t)}Vt(e){e.dt(2)}}function Gu(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)}ju.bt=new ju;class zu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Dt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ct(n.value),n=t.next();this.vt()}Ft(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Mt(n.value),n=t.next();this.xt()}Ot(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ct(e);else if(e<2048)this.Ct(960|e>>>6),this.Ct(128|63&e);else if(t<"\ud800"||"\udbff">>12),this.Ct(128|63&e>>>6),this.Ct(128|63&e);else{const e=t.codePointAt(0);this.Ct(240|e>>>18),this.Ct(128|63&e>>>12),this.Ct(128|63&e>>>6),this.Ct(128|63&e)}}this.vt()}Nt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Mt(e);else if(e<2048)this.Mt(960|e>>>6),this.Mt(128|63&e);else if(t<"\ud800"||"\udbff">>12),this.Mt(128|63&e>>>6),this.Mt(128|63&e);else{const e=t.codePointAt(0);this.Mt(240|e>>>18),this.Mt(128|63&e>>>12),this.Mt(128|63&e>>>6),this.Mt(128|63&e)}}this.xt()}Bt(e){var t=this.Lt(e),n=Gu(t);this.kt(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;roi.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Zt=e.orderBy,this.Xt=[];for(const t of e.filters){const e=t;e.isInequality()?this.Yt=this.Yt.add(e):this.Xt.push(e)}}get en(){return 1=this.Zt.length||!this.sn(this.Zt[s++],e))return!1}return!0}on(){if(this.en)return null;let e=new ys(oi.comparator);const t=[];for(const n of this.Xt)n.field.isKeyField()||("array-contains"===n.op||"array-contains-any"===n.op?t.push(new di(n.field,2)):e.has(n.field)||(e=e.add(n.field),t.push(new di(n.field,0))));for(const r of this.Zt)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new di(r.field,"asc"===r.dir?0:1)));return new ci(ci.UNKNOWN_ID,this.collectionId,t,fi.empty())}nn(e){for(const t of this.Xt)if(this.rn(t,e))return!0;return!1}rn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function Ju(e){if(0===e.getFilters().length)return[];const t=function t(e){if(qr(e instanceof ra||e instanceof ia),e instanceof ra)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=ia.create(n,e.op);return r=ic(r),tc(r)?r:(qr(r instanceof ia),qr(sa(r)),qr(1nc(e,t)))}(function t(n){var e;if(qr(n instanceof ra||n instanceof ia),n instanceof ra){if(n instanceof pa){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>ra.create(n.field,"==",e)))||[];return ia.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return ia.create(r,n.op)}(e));return qr(tc(t)),Zu(t)||ec(t)?[t]:t.getFilters()}function Zu(e){return e instanceof ra}function ec(e){return e instanceof ia&&oa(e)}function tc(e){return Zu(e)||ec(e)||function(e){if(e instanceof ia&&aa(e)){for(const t of e.getFilters())if(!Zu(t)&&!ec(t))return!1;return!0}return!1}(e)}function nc(e,t){var n,r;return qr(e instanceof ra||e instanceof ia),qr(t instanceof ra||t instanceof ia),ic(e instanceof ra?t instanceof ra?(n=e,r=t,ia.create([n,r],"and")):rc(e,t):t instanceof ra?rc(t,e):function(e,t){if(qr(0nc(e,r));return ia.create(i,"or")}(e,t))}function rc(t,e){if(sa(e))return ca(e,t.getFilters());var n=e.filters.map(e=>nc(t,e));return ia.create(n,"or")}function ic(t){if(qr(t instanceof ra||t instanceof ia),t instanceof ra)return t;const e=t.getFilters();if(1===e.length)return ic(e[0]);if(ua(t))return t;const n=e.map(e=>ic(e)),r=[];return n.forEach(e=>{e instanceof ra?r.push(e):e instanceof ia&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:ia.create(r,t.op)}class sc{constructor(){this._n=new ac}addToCollectionParentIndex(e,t){return this._n.add(t),bi.resolve()}getCollectionParents(e,t){return bi.resolve(this._n.getEntries(t))}addFieldIndex(e,t){return bi.resolve()}deleteFieldIndex(e,t){return bi.resolve()}deleteAllFieldIndexes(e){return bi.resolve()}createTargetIndexes(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(pi.min())}getMinOffsetFromCollectionGroup(e,t){return bi.resolve(pi.min())}updateCollectionGroup(e,t,n){return bi.resolve()}updateIndexEntries(e,t){return bi.resolve()}}class ac{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ys(si.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 ys(si.comparator)).toArray()}}const oc=new Uint8Array(0);class uc{constructor(e,t){this.databaseId=t,this.an=new ac,this.un=new ja(e=>ba(e),(e,t)=>Ia(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.an.has(t))return bi.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.an.add(t)});r={collectionId:n,parent:Pi(r)};return cc(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[ti(n),""],!1,!0);return cc(e).W(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Bi(t.parent))}return r})}addFieldIndex(e,t){const n=lc(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=dc(e);return i.next(e=>{n.put(Fu(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=lc(e),r=dc(e),i=hc(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){const t=lc(e),n=hc(e),r=dc(e);return t.H().next(()=>n.H()).next(()=>r.H())}createTargetIndexes(n,e){return bi.forEach(this.cn(e),t=>this.getIndexType(n,t).next(e=>{if(0===e||1===e){const e=new Xu(t).on();if(null!=e)return this.addFieldIndex(n,e)}}))}getDocumentsMatchingTarget(e,h){const l=hc(e);let d=!0;const n=new Map;return bi.forEach(this.cn(h),t=>this.ln(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let c=Ya();const d=[];return bi.forEach(n,(e,t)=>{var n;Or("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${ba(h)}`);var r=function(e,t){var n=hi(t);if(void 0===n)return null;for(const t of Ta(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),i=function(e,t){const n=new Map;for(const r of li(t))for(const t of Ta(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of li(t)){const t=(0===i.kind?Sa:xa)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Js(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of li(t)){const t=(0===i.kind?xa:Sa)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Js(n,r)}(t,e),o=this.hn(e,t,s),u=this.hn(e,t,a),i=this.Pn(e,t,i),i=this.In(e.indexId,r,o,s.inclusive,u,a.inclusive,i);return bi.forEach(i,e=>l.j(e,h.limit).next(e=>{e.forEach(e=>{var t=ui.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),d.push(t))})}))}).next(()=>d)}return bi.resolve(null)})}cn(t){let e=this.un.get(t);return e||(e=0===t.filters.length?[t]:Ju(ia.create(t.filters,"and")).map(e=>_a(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.un.set(t,e),e)}In(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;hthis.En(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}En(e,t,n,r){const i=new Wu(e,ui.empty(),t,n);return r?i:i.Jt()}dn(e,t,n,r){const i=new Wu(e,ui.empty(),t,n);return r?i.Jt():i}ln(e,t){const r=new Xu(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.ln(e,t).next(e=>{e?0!==n&&e.fields.lengthfunction(e){return null!==e.limit}(t)&&1e instanceof ra&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=lc(e),r=dc(e);return(t?n.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.W()).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 fi(e.sequenceNumber,new pi(Au(e.readTime),new ui(Bi(e.documentKey)),e.largestBatchId)):fi.empty(),r=t.fields.map(([e,t])=>new di(oi.fromServerFormat(e),t)),new ci(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:Zr(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=lc(e),s=dc(e);return this.gn(e).next(t=>i.W("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>bi.forEach(e,e=>s.put(Fu(e.indexId,this.uid,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.pn(i,t,n).next(e=>{var t=this.yn(r,n);return e.isEqual(t)?bi.resolve():this.wn(i,r,n,e,t)}))))})}Sn(e,t,n,r){return hc(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Rn(n,t.key),documentKey:t.key.path.toArray()})}bn(e,t,n,r){return hc(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Rn(n,t.key),t.key.path.toArray()])}pn(e,n,r){const t=hc(e);let i=new ys(Hu);return t.Y({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Rn(r,n)])},(e,t)=>{i=i.add(new Wu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}yn(e,t){let n=new ys(Hu);var r=this.An(t,e);if(null==r)return n;const i=hi(t);if(null!=i){var s=e.data.field(i.fieldPath);if(js(s))for(const i of s.arrayValue.values||[])n=n.add(new Wu(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new Wu(t.indexId,e.key,oc,r));return n}wn(t,n,r,e,i){Or("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=ws(s),u=ws(a);for(;o||u;){let e=!1,t=!1;if(o&&u){const r=n(o,u);r<0?t=!0:0{s.push(this.Sn(t,n,r,e))},e=>{s.push(this.bn(t,n,r,e))}),bi.waitFor(s)}gn(e){let r=1;return dc(e).Y({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)=>Hu(e,t)).filter((e,t,n)=>!t||0!==Hu(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=Hu(i,e),s=Hu(i,t);if(0===n)r[0]=e.Jt();else if(0this.ln(t,e).next(e=>e||Br())).next(fc)}}function cc(e){return hs(e,"collectionParents")}function hc(e){return hs(e,"indexEntries")}function lc(e){return hs(e,"indexConfiguration")}function dc(e){return hs(e,"indexState")}function fc(e){qr(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i(o++,n.delete()));s.push(u.next(()=>{qr(1===o)}));const c=[];for(const e of n.mutations){const r=ji(t,e.key.path,n.batchId);s.push(i.delete(r)),c.push(e.key)}return bi.waitFor(s).next(()=>c)}function yc(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 Br();t=e.noDocument}return JSON.stringify(t).length}mc.DEFAULT_COLLECTION_PERCENTILE=10,mc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,mc.DEFAULT=new mc(41943040,mc.DEFAULT_COLLECTION_PERCENTILE,mc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),mc.DISABLED=new mc(-1,0,0);class vc{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Cn={}}static lt(e,t,n,r){qr(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new vc(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return _c(e).Y({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=bc(h),m=_c(h);return m.add({}).next(e=>{qr("number"==typeof e);const t=new Co(e,l,d,f),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>gu(i.ct,e)),u=a.mutations.map(e=>gu(i.ct,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var i,s,a,o,u;let c=new ys((e,t)=>Zr(e.canonicalString(),t.canonicalString()));for(const h of f){const l=ji(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,Gi))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.Cn[e]=t.keys()}),bi.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return _c(e).get(t).next(e=>e?(qr(e.userId===this.userId),Nu(this.serializer,e)):null)}vn(e,n){return this.Cn[n]?bi.resolve(this.Cn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Cn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return _c(e).Y({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(qr(t.batchId>=r),i=Nu(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return _c(e).Y({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 _c(e).W("userMutationsIndex",t).next(e=>e.map(e=>Nu(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=Ui(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return bc(a).Y({range:t},(e,t,n)=>{var[r,i,s]=e,i=Bi(i);if(r===this.userId&&o.path.isEqual(i))return _c(a).get(s).next(e=>{if(!e)throw Br();qr(e.userId===this.userId),u.push(Nu(this.serializer,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new ys(Zr);const n=[];return e.forEach(a=>{var e=Ui(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=bc(t).Y({range:e},(e,t,n)=>{var[r,i,s]=e,i=Bi(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),bi.waitFor(n).next(()=>this.Fn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=Ui(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new ys(Zr);return bc(e).Y({range:r},(e,t,n)=>{var[r,i,s]=e,i=Bi(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(u=u.add(s)):n.done()}).next(()=>this.Fn(e,u))}Fn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(_c(t).get(e).next(e=>{if(null===e)throw Br();qr(e.userId===this.userId),n.push(Nu(this.serializer,e))}))}),bi.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return pc(t.ae,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.Mn(n.batchId)}),bi.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}Mn(e){delete this.Cn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return bi.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return bc(n).Y({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Bi(e[1]);r.push(t)}else n.done()}).next(()=>{qr(0===r.length)})})}containsKey(e,t){return wc(e,this.userId,t)}xn(e){return Ic(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function wc(e,s,t){const n=Ui(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return bc(e).Y({range:r,J:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function _c(e){return hs(e,"mutations")}function bc(e){return hs(e,"documentMutations")}function Ic(e){return hs(e,"mutationQueues")}class Ec{constructor(e){this.On=e}next(){return this.On+=2,this.On}static Nn(){return new Ec(0)}static Bn(){return new Ec(-1)}}class Tc{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.Ln(n).next(e=>{const t=new Ec(e.highestTargetId);return e.highestTargetId=t.next(),this.kn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Ln(e).next(e=>ri.fromTimestamp(new ni(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Ln(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Ln(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.kn(t,e)))}addTargetData(t,n){return this.qn(t,n).next(()=>this.Ln(t).next(e=>(e.targetCount+=1,this.Qn(n,e),this.kn(t,e))))}updateTargetData(e,t){return this.qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Sc(t).delete(e.targetId)).next(()=>this.Ln(t)).next(e=>(qr(0{var n=ku(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>bi.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Sc(e).Y((e,t)=>{var n=ku(t);r(n)})}Ln(e){return xc(e).get("targetGlobalKey").next(e=>(qr(null!==e),e))}kn(e,t){return xc(e).put("targetGlobalKey",t)}qn(e,t){return Sc(e).put(Ru(this.serializer,t))}Qn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Ln(e).next(e=>e.targetCount)}getTargetData(e,i){var t=ba(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return Sc(e).Y({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=ku(t);Ia(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=Dc(n);return e.forEach(e=>{var t=Pi(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=Dc(n);return bi.forEach(e,e=>{var t=Pi(e.path);return bi.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=Dc(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=Dc(e);let i=Ya();return r.Y({range:n,J:!0},(e,t,n)=>{var r=Bi(e[1]),r=new ui(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Pi(t.path),n=IDBKeyRange.bound([n],[ti(n)],!1,!0);let r=0;return Dc(e).Y({index:"documentTargetsIndex",J:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0e?ku(e):null)}}function Sc(e){return hs(e,"targets")}function xc(e){return hs(e,"targetGlobal")}function Dc(e){return hs(e,"targetDocuments")}function Cc([e,t],[n,r]){var i=Zr(e,n);return 0===i?Zr(t,r):i}class Ac{constructor(e){this.Kn=e,this.buffer=new ys(Cc),this.$n=0}Un(){return++this.$n}Wn(e){var t=[e,this.Un()];if(this.buffer.size{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){xi(e)?Or("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await _i(e)}await this.zn(3e5)})}}class kc{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.Hn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return bi.resolve(Li._e);const n=new Ac(t);return this.jn.forEachTarget(e,e=>n.Wn(e.sequenceNumber)).next(()=>this.jn.Jn(e,e=>n.Wn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Or("LruGarbageCollector","Garbage collection skipped; disabled"),bi.resolve(gc)):this.getCacheSize(t).next(e=>e(i=e>this.params.maximumSequenceNumbersToCollect?(Or("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),Mr()<=l.DEBUG&&Or("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),bi.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class Rc{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new kc(e,t))}Hn(e){const n=this.Zn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Zn(e){let t=0;return this.Jn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Jn(e,n){return this.Xn(e,(e,t)=>n(t))}addReference(e,t,n){return 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)}er(t,n){let r=!1;return Ic(t).Z(e=>wc(t,e,n).next(e=>(e&&(r=!0),bi.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Xn(n,(t,e)=>{if(e<=r){const r=this.er(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,ri.min()),Dc(n).delete(function(e){return[0,Pi(e.path)]}(t))))});s.push(r)}}).next(()=>bi.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Lc(e,t)}Xn(e,r){const t=Dc(e);let i,s=Li._e;return t.Y({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==Li._e&&r(new ui(Bi(i)),s),s=n,i=t):s=Li._e}).next(()=>{s!==Li._e&&r(new ui(Bi(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Lc(e,t){return Dc(e).put((e=e.currentSequenceNumber,{targetId:0,path:Pi(t.path),sequenceNumber:e}))}class Mc{constructor(){this.changes=new ja(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 Oc{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Bc(e).put(n)}removeEntry(e,t,n){return Bc(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Du(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.tr(t,e)))}getEntry(e,n){let r=Xs.newInvalidDocument(n);return Bc(e).Y({index:"documentKeyIndex",range:IDBKeyRange.only(qc(n))},(e,t)=>{r=this.nr(n,t)}).next(()=>r)}rr(e,n){let r={size:0,document:Xs.newInvalidDocument(n)};return Bc(e).Y({index:"documentKeyIndex",range:IDBKeyRange.only(qc(n))},(e,t)=>{r={document:this.nr(n,t),size:yc(t)}}).next(()=>r)}getEntries(e,t){let r=Ga;return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n)}).next(()=>r)}sr(e,t){let r=Ga,i=new gs(ui.comparator);return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n),i=i.insert(e,yc(t))}).next(()=>({documents:r,_r:i}))}ir(e,t,i){if(t.isEmpty())return bi.resolve();let n=new ys(jc);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(qc(n.first()),qc(n.last())),s=n.getIterator();let a=s.getNext();return Bc(e).Y({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ui.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&jc(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.U(qc(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,r,i){const s=n.path,a=[s.popLast().toArray(),s.lastSegment(),Du(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Bc(e).W(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let t=Ga;for(const i of e){const e=this.nr(ui.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Ba(n,e)||r.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=Ga;var r=Uc(t,n),a=Uc(t,pi.max());return Bc(e).Y({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.nr(ui.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 Pc(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return Vc(e).get("remoteDocumentGlobalKey").next(e=>(qr(!!e),e))}tr(e,t){return Vc(e).put("remoteDocumentGlobalKey",t)}nr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=fu(e.ct,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ui.fromSegments(t.noDocument.path),i=Au(t.noDocument.readTime);n=Xs.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Br();{const e=ui.fromSegments(t.unknownDocument.path),s=Au(t.unknownDocument.version);n=Xs.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new ni(t[0],t[1]),ri.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(ri.min()))return e}return Xs.newInvalidDocument(e)}}function Fc(e){return new Oc(e)}class Pc extends Mc{constructor(e,t){super(),this.ar=e,this.trackRemovals=t,this.ur=new ja(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,u=new ys((e,t)=>Zr(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.ur.get(e);if(a.push(this.ar.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=xu(this.ar.serializer,t);u=u.add(e.path.popLast());var i=yc(r);o+=i-n.size,a.push(this.ar.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=xu(this.ar.serializer,t.convertToNoDocument(ri.min()));a.push(this.ar.addEntry(s,e,o))}}),u.forEach(e=>{a.push(this.ar.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ar.updateMetadata(s,o)),bi.waitFor(a)}getFromCache(e,t){return this.ar.rr(e,t).next(e=>(this.ur.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ar.sr(e,t).next(({documents:n,_r:e})=>(e.forEach((e,t)=>{this.ur.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function Vc(e){return hs(e,"remoteDocumentGlobal")}function Bc(e){return hs(e,"remoteDocumentsV14")}function qc(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Uc(e,t){const n=t.documentKey.path.toArray();return[e,Du(t.readTime),n.slice(0,n.length-2),0(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&wo(r.mutation,e,_s.empty(),ni.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Ya()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Ya()){const r=Qa();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=Ka();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=Qa();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Ya()))}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=Ga;const a=Qa(),o=Qa();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof Io)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),wo(n.mutation,t,n.mutation.getFieldMask(),ni.now())):a.set(t.key,_s.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new Gc(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=Qa();let u=new gs((e,t)=>e-t),c=Ya();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||_s.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||Ya()).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=Qa();r.forEach(e=>{var t;c.has(e)||(null!==(t=yo(a.get(e),o.get(e)))&&i.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return bi.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n,r){return i=t,ui.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):ka(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0bi.forEach(e,(t,e)=>(r{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,Ya())).next(e=>({batchId:r,changes:$a(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ui(t)).next(e=>{let t=Ka();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s,a){const o=i.collectionGroup;let u=Ka();return this.indexManager.getCollectionParents(r,o).next(e=>bi.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new Da(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s,a).next(e=>{e.forEach((e,t)=>{u=u.insert(e,t)})})}).next(()=>u))}getDocumentsMatchingCollectionQuery(t,s,n,r){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a,r))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Xs.newInvalidDocument(n)))});let i=Ka();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&wo(n.mutation,t,_s.empty(),ni.now()),Ba(s,t)&&(i=i.insert(e,t))}),i})}}class Kc{constructor(e){this.serializer=e,this.cr=new Map,this.lr=new Map}getBundleMetadata(e,t){return bi.resolve(this.cr.get(t))}saveBundleMetadata(e,t){return this.cr.set(t.id,{id:t.id,version:t.version,createTime:nu(t.createTime)}),bi.resolve()}getNamedQuery(e,t){return bi.resolve(this.lr.get(t))}saveNamedQuery(e,t){return this.lr.set(t.name,{name:(t=t).name,query:Lu(t.bundledQuery),readTime:nu(t.readTime)}),bi.resolve()}}class $c{constructor(){this.overlays=new gs(ui.comparator),this.hr=new Map}getOverlay(e,t){return bi.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Qa();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.ht(n,r,t)}),bi.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.hr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.hr.delete(n)),bi.resolve()}getOverlaysForCollection(e,t,n){const r=Qa(),i=t.length+1,s=new ui(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return bi.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new gs((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=Qa(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=Qa(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return bi.resolve(a)}ht(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.hr.get(r.largestBatchId).delete(n.key);this.hr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new No(t,n));let i=this.hr.get(t);void 0===i&&(i=Ya(),this.hr.set(t,i)),this.hr.set(t,i.add(n.key))}}class Qc{constructor(){this.Pr=new ys(Wc.Ir),this.Tr=new ys(Wc.Er)}isEmpty(){return this.Pr.isEmpty()}addReference(e,t){var n=new Wc(e,t);this.Pr=this.Pr.add(n),this.Tr=this.Tr.add(n)}dr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ar(new Wc(e,t))}Rr(e,t){e.forEach(e=>this.removeReference(e,t))}Vr(e){const t=new ui(new si([])),n=new Wc(t,e),r=new Wc(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Ar(e),i.push(e.key)}),i}mr(){this.Pr.forEach(e=>this.Ar(e))}Ar(e){this.Pr=this.Pr.delete(e),this.Tr=this.Tr.delete(e)}gr(e){var t=new ui(new si([])),n=new Wc(t,e),t=new Wc(t,e+1);let r=Ya();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Wc(e,0),t=this.Pr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Wc{constructor(e,t){this.key=e,this.pr=t}static Ir(e,t){return ui.comparator(e.key,t.key)||Zr(e.pr,t.pr)}static Er(e,t){return Zr(e.pr,t.pr)||ui.comparator(e.key,t.key)}}class Hc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.yr=1,this.wr=new ys(Wc.Ir)}checkEmpty(e){return bi.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.yr;this.yr++,0n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return bi.resolve(0===this.mutationQueue.length?-1:this.yr-1)}getAllMutationBatches(e){return bi.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Wc(t,0),r=new Wc(t,Number.POSITIVE_INFINITY),i=[];return this.wr.forEachInRange([n,r],e=>{var t=this.Sr(e.pr);i.push(t)}),bi.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new ys(Zr);return t.forEach(e=>{var t=new Wc(e,0),n=new Wc(e,Number.POSITIVE_INFINITY);this.wr.forEachInRange([t,n],e=>{r=r.add(e.pr)})}),bi.resolve(this.Dr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ui.isDocumentKey(i)||(i=i.child(""));var s=new Wc(new ui(i),0);let a=new ys(Zr);return this.wr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.pr)),!0)},s),bi.resolve(this.Dr(a))}Dr(e){const n=[];return e.forEach(e=>{var t=this.Sr(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){qr(0===this.Cr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.wr;return bi.forEach(r.mutations,e=>{var t=new Wc(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.wr=i})}Mn(e){}containsKey(e,t){var n=new Wc(t,0),n=this.wr.firstAfterOrEqual(n);return bi.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,bi.resolve()}Cr(e,t){return this.br(e)}br(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Sr(e){var t=this.br(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Yc{constructor(e){this.vr=e,this.docs=new gs(ui.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.vr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return bi.resolve(n?n.document.mutableCopy():Xs.newInvalidDocument(t))}getEntries(e,t){let n=Ga;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=Ga;const s=t.path,a=new ui(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||yi(mi(a),n)<=0||(r.has(a.key)||Ba(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return bi.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Br()}Fr(e,t){return bi.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Xc(this)}getSize(e){return bi.resolve(this.size)}}class Xc extends Mc{constructor(e){super(),this.ar=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ar.addEntry(n,t)):this.ar.removeEntry(e)}),bi.waitFor(r)}getFromCache(e,t){return this.ar.getEntry(e,t)}getAllFromCache(e,t){return this.ar.getEntries(e,t)}}class Jc{constructor(e){this.persistence=e,this.Mr=new ja(e=>ba(e),Ia),this.lastRemoteSnapshotVersion=ri.min(),this.highestTargetId=0,this.Or=0,this.Nr=new Qc,this.targetCount=0,this.Br=Ec.Nn()}forEachTarget(e,n){return this.Mr.forEach((e,t)=>n(t)),bi.resolve()}getLastRemoteSnapshotVersion(e){return bi.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return bi.resolve(this.Or)}allocateTargetId(e){return this.highestTargetId=this.Br.next(),bi.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Or&&(this.Or=t),bi.resolve()}qn(e){this.Mr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Br=new Ec(t),this.highestTargetId=t),e.sequenceNumber>this.Or&&(this.Or=e.sequenceNumber)}addTargetData(e,t){return this.qn(t),this.targetCount+=1,bi.resolve()}updateTargetData(e,t){return this.qn(t),bi.resolve()}removeTargetData(e,t){return this.Mr.delete(t.target),this.Nr.Vr(t.targetId),--this.targetCount,bi.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Mr.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Mr.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),bi.waitFor(a).next(()=>s)}getTargetCount(e){return bi.resolve(this.targetCount)}getTargetData(e,t){var n=this.Mr.get(t)||null;return bi.resolve(n)}addMatchingKeys(e,t,n){return this.Nr.dr(t,n),bi.resolve()}removeMatchingKeys(t,e,n){this.Nr.Rr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),bi.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Nr.Vr(t),bi.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Nr.gr(t);return bi.resolve(n)}containsKey(e,t){return bi.resolve(this.Nr.containsKey(t))}}class Zc{constructor(e,t){this.Lr={},this.overlays={},this.kr=new Li(0),this.qr=!1,this.qr=!0,this.referenceDelegate=e(this),this.Qr=new Jc(this),this.indexManager=new sc,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Kr(e),new Yc(e)),this.serializer=new Su(t),this.$r=new Kc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.qr=!1,Promise.resolve()}get started(){return this.qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new $c,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Lr[e.toKey()];return n||(n=new Hc(t,this.referenceDelegate),this.Lr[e.toKey()]=n),n}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.$r}runTransaction(e,t,n){Or("MemoryPersistence","Starting transaction:",e);const r=new eh(this.kr.next());return this.referenceDelegate.Ur(),n(r).next(e=>this.referenceDelegate.Wr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gr(t,n){return bi.or(Object.values(this.Lr).map(e=>()=>e.containsKey(t,n)))}}class eh extends wi{constructor(e){super(),this.currentSequenceNumber=e}}class th{constructor(e){this.persistence=e,this.zr=new Qc,this.jr=null}static Hr(e){return new th(e)}get Jr(){if(this.jr)return this.jr;throw Br()}addReference(e,t,n){return this.zr.addReference(n,t),this.Jr.delete(n.toString()),bi.resolve()}removeReference(e,t,n){return this.zr.removeReference(n,t),this.Jr.add(n.toString()),bi.resolve()}markPotentiallyOrphaned(e,t){return this.Jr.add(t.toString()),bi.resolve()}removeTarget(e,t){this.zr.Vr(t.targetId).forEach(e=>this.Jr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Jr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ur(){this.jr=new Set}Wr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return bi.forEach(this.Jr,e=>{const t=ui.fromPath(e);return this.Yr(n,t).next(e=>{e||r.removeEntry(t,ri.min())})}).next(()=>(this.jr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Yr(e,t).next(e=>{e?this.Jr.delete(t.toString()):this.Jr.add(t.toString())})}Kr(e){return 0}Yr(e,t){return bi.or([()=>bi.resolve(this.zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gr(e,t)])}}class nh{constructor(e){this.serializer=e}N(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",qi,{unique:!0}),s.createObjectStore("documentMutations"),rh(t),t.createObjectStore("remoteDocuments"));let a=bi.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),rh(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ri.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").W().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",qi,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return bi.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Xr(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ei(i)))),n<7&&7<=r&&(a=a.next(()=>this.ti(i))),n<8&&8<=r&&(a=a.next(()=>this.ni(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.ri(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:ts});t.createIndex("collectionPathOverlayIndex",ns,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",rs,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:zi});t.createIndex("documentKeyIndex",Ki),t.createIndex("collectionGroupIndex",$i)}(t)).next(()=>this.ii(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.si(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Xi}).createIndex("sequenceNumberIndex",Ji,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Zi}).createIndex("documentKeyIndex",es,{unique:!1})}(t))),a}ei(t){let n=0;return t.store("remoteDocuments").Y((e,t)=>{n+=yc(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Xr(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.W().next(e=>bi.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.W("userMutationsIndex",e).next(e=>bi.forEach(e,e=>{qr(e.userId===n.userId);var t=Nu(this.serializer,e);return pc(r,n.userId,t).next(()=>{})}))}))}ti(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Y((e,t)=>{const n=new si(e),r=[0,Pi(n)];s.push(a.get(r).next(e=>e?bi.resolve():(e=>a.put({targetId:0,path:Pi(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>bi.waitFor(s))})}ni(e,t){e.createObjectStore("collectionParents",{keyPath:Yi});const n=t.store("collectionParents"),r=new ac,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Pi(r)})}};return t.store("remoteDocuments").Y({J:!0},(e,t)=>{const n=new si(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Y({J:!0},([,e],t)=>{const n=Bi(e);return i(n.popLast())}))}ri(e){const r=e.store("targets");return r.Y((e,t)=>{var n=ku(t),n=Ru(this.serializer,n);return r.put(n)})}ii(e,a){const t=a.store("remoteDocuments"),o=[];return t.Y((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ui(si.fromString(s.document.name).popFirst(5)):s.noDocument?ui.fromSegments(s.noDocument.path):s.unknownDocument?ui.fromSegments(s.unknownDocument.path):Br()).path.toArray(),i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};var s;o.push(n.put(i))}).next(()=>bi.waitFor(o))}si(e,s){const t=s.store("mutations"),a=Fc(this.serializer),o=new Zc(th.Hr,this.serializer.ct);return t.W().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Ya();Nu(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),bi.forEach(r,(e,t)=>{var n=new kr(t),r=qu.lt(this.serializer,n),i=o.getIndexManager(n),n=vc.lt(n,this.serializer,i,o.referenceDelegate);return new zc(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new cs(s,Li._e),e).next()})})}}function rh(e){e.createObjectStore("targetDocuments",{keyPath:Wi}).createIndex("documentTargetsIndex",Hi,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Qi,{unique:!0}),e.createObjectStore("targetGlobal")}const ih="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 sh{constructor(e,t,n,r,i,s,a,o,u,c,h=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.oi=i,this.window=s,this.document=a,this._i=u,this.ai=c,this.ui=h,this.kr=null,this.qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.li=null,this.hi=null,this.Pi=Number.NEGATIVE_INFINITY,this.Ii=e=>Promise.resolve(),!sh.D())throw new jr(Ur.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new Rc(this,r),this.Ti=t+"main",this.serializer=new Su(o),this.Ei=new Ei(this.Ti,this.ui,new nh(this.serializer)),this.Qr=new Tc(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Fc(this.serializer),this.$r=new Pu,this.window&&this.window.localStorage?this.di=this.window.localStorage:(this.di=null,!1===c&&Fr("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Ai().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new jr(Ur.FAILED_PRECONDITION,ih);return this.Ri(),this.Vi(),this.mi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Qr.getHighestSequenceNumber(e))}).then(e=>{this.kr=new Li(e,this._i)}).then(()=>{this.qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}fi(t){return this.Ii=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.oi.enqueueAndForget(async()=>{this.started&&await this.Ai()}))}Ai(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>oh(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.gi(t).next(e=>{e||(this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)))})}).next(()=>this.pi(t)).next(e=>this.isPrimary&&!e?this.yi(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(xi(e))return Or("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Or("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.oi.enqueueRetryable(()=>this.Ii(e)),this.isPrimary=e})}gi(e){return ah(e).get("owner").next(e=>bi.resolve(this.Si(e)))}bi(e){return oh(e).delete(this.clientId)}async Di(){if(this.isPrimary&&!this.Ci(this.Pi,18e5)){this.Pi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=hs(e,"clientMetadata");return r.W().next(e=>{const t=this.vi(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return bi.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.di)for(const t of e)this.di.removeItem(this.Fi(t.clientId))}}mi(){this.hi=this.oi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ai().then(()=>this.Di()).then(()=>this.mi()))}Si(e){return!!e&&e.ownerId===this.clientId}pi(t){return this.ai?bi.resolve(!0):ah(t).get("owner").next(e=>{if(null!==e&&this.Ci(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)){if(this.Si(e)&&this.networkEnabled)return!0;if(!this.Si(e)){if(!e.allowTabSynchronization)throw new jr(Ur.FAILED_PRECONDITION,ih);return!1}}return!(!this.networkEnabled||!this.inForeground)||oh(t).W().next(e=>void 0===this.vi(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&Or("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.qr=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Oi(),this.Ni(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new cs(e,Li._e);return this.yi(t).next(()=>this.bi(t))}),this.Ei.close(),this.Bi()}vi(e,t){return e.filter(e=>this.Ci(e.updateTimeMs,t)&&!this.Mi(e.clientId))}Li(){return this.runTransaction("getActiveClients","readonly",e=>oh(e).W().next(e=>this.vi(e,18e5).map(e=>e.clientId)))}get started(){return this.qr}getMutationQueue(e,t){return vc.lt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new uc(e,this.serializer.ct.databaseId)}getDocumentOverlayCache(e){return qu.lt(this.serializer,e)}getBundleCache(){return this.$r}runTransaction(t,n,r){Or("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=15===(e=this.ui)?us:14===e?os:13===e?as:12===e?ss:11===e?is:void Br();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new cs(e,this.kr?this.kr.next():Li._e),"readwrite-primary"===n?this.gi(a).next(e=>!!e||this.pi(a)).next(e=>{if(!e)throw Fr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)),new jr(Ur.FAILED_PRECONDITION,vi);return r(a)}).next(e=>this.wi(a).next(()=>e)):this.ki(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ki(e){return ah(e).get("owner").next(e=>{if(null!==e&&this.Ci(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)&&!this.Si(e)&&!(this.ai||this.allowTabSynchronization&&e.allowTabSynchronization))throw new jr(Ur.FAILED_PRECONDITION,ih)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return ah(e).put("owner",t)}static D(){return Ei.D()}yi(e){const t=ah(e);return t.get("owner").next(e=>this.Si(e)?(Or("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):bi.resolve())}Ci(e,t){var n=Date.now();return!(e ${n}`),1))}Ri(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.li=()=>{this.oi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ai()))},this.document.addEventListener("visibilitychange",this.li),this.inForeground="visible"===this.document.visibilityState)}Oi(){this.li&&(this.document.removeEventListener("visibilitychange",this.li),this.li=null)}Vi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();var e=/(?:Version|Mobile)\/1[456]/;h()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.oi.enterRestrictedMode(!0),this.oi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}Ni(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Mi(e){var t;try{var n=null!==(null===(t=this.di)||void 0===t?void 0:t.getItem(this.Fi(e)));return Or("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Fr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this.di)try{this.di.setItem(this.Fi(this.clientId),String(Date.now()))}catch(e){Fr("Failed to set zombie client id.",e)}}Bi(){if(this.di)try{this.di.removeItem(this.Fi(this.clientId))}catch(e){}}Fi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function ah(e){return hs(e,"owner")}function oh(e){return hs(e,"clientMetadata")}function uh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class ch{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.qi=n,this.Qi=r}static Ki(e,t){let n=Ya(),r=Ya();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 ch(e,t.fromCache,n,r)}}class hh{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class lh{constructor(){this.$i=!1,this.Ui=!1,this.Wi=100,this.Gi=h()?8:0{i.result=e}).next(()=>{if(!i.result)return this.Hi(n,r,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){const t=new hh;return this.Ji(n,r,t).next(e=>{if(i.result=e,this.Ui)return this.Yi(n,r,t,e.size)})}}).next(()=>i.result)}Yi(e,t,n,r){return n.documentReadCountthis.Gi*r?(Mr()<=l.DEBUG&&Or("QueryEngine","The SDK decides to create cache indexes for query:",Va(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,La(t))):bi.resolve())}ji(i,s){if(Na(s))return bi.resolve(null);let t=La(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Oa(s,null,"F"),t=La(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=Ya(...e);return this.zi.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Zi(s,n);return this.Xi(s,t,r,e.readTime)?this.ji(i,Oa(s,null,"F")):this.es(i,t,s,e)}))})))}Hi(n,r,i,s){return Na(r)||s.isEqual(ri.min())?bi.resolve(null):this.zi.getDocuments(n,i).next(e=>{var t=this.Zi(r,e);return this.Xi(r,t,i,s)?bi.resolve(null):(Mr()<=l.DEBUG&&Or("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Va(r)),this.es(n,t,r,gi(s,-1)).next(e=>e))})}Zi(n,e){let r=new ys(Ua(n));return e.forEach((e,t)=>{Ba(n,t)&&(r=r.add(t))}),r}Xi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class dh{constructor(e,t,n,r){this.persistence=e,this.ts=t,this.serializer=r,this.ns=new gs(Zr),this.rs=new ja(e=>ba(e),Ia),this.ss=new Map,this.os=e.getRemoteDocumentCache(),this.Qr=e.getTargetCache(),this.$r=e.getBundleCache(),this._s(n)}_s(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new zc(this.os,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.os.setIndexManager(this.indexManager),this.ts.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ns))}}function fh(e,t,n,r){return new dh(e,t,n,r)}async function gh(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a._s(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Ya();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({us:e,removedBatchIds:t,addedBatchIds:n}))})})}function mh(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Qr.getLastRemoteSnapshotVersion(e))}function ph(e,c){const h=e,l=c.snapshotVersion;let d=h.ns;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h.os.newChangeBuffer({trackRemovals:!0});d=h.ns;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Qr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Qr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==c.targetMismatches.get(n)?e=e.withResumeToken(Is.EMPTY_BYTE_STRING,ri.min()).withLastLimboFreeSnapshotVersion(ri.min()):0{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(yh(o,e,c.documentUpdates).next(e=>{t=e.cs,n=e.ls})),!l.isEqual(ri.min())){const c=h.Qr.getLastRemoteSnapshotVersion(o).next(e=>h.Qr.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return bi.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.ns=d,e))}function yh(e,s,t){let n=Ya(),a=Ya();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=Ga;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(ri.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0{let n;return i.Qr.getTargetData(t,r).next(e=>e?(n=e,bi.resolve(n)):i.Qr.allocateTargetId(t).next(e=>(n=new Tu(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Qr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.ns.get(e.targetId);return(null===t||0r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!xi(e))throw e;Or("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ns=r.ns.remove(t),r.rs.delete(i.target)}function _h(e,n,r){const i=e;let s=ri.min(),a=Ya();return i.persistence.runTransaction("Execute query","readwrite",t=>function(e,t,n){const r=e,i=r.rs.get(n);return void 0!==i?bi.resolve(r.ns.get(i)):r.Qr.getTargetData(t,n)}(i,t,La(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Qr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.ts.getDocumentsMatchingQuery(t,n,r?s:ri.min(),r?a:Ya())).next(e=>(Eh(i,qa(n),e),{documents:e,hs:a})))}function bh(e,t){const n=e,r=n.Qr,i=n.ns.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r._t(e,t).next(e=>e?e.target:null))}function Ih(e,t){const n=e,r=n.ss.get(t)||ri.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.os.getAllFromCollectionGroup(e,t,gi(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Eh(n,t,e),e))}function Eh(e,t,n){let r=e.ss.get(t)||ri.min();n.forEach((e,t)=>{0this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ss,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ns(this.ps)}isActiveQueryTarget(n){let r=!1;return this.ps.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Bs(e,"pending")}updateMutationState(e,t,n){this.Bs(e,t,n),this.Ls(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(xh(this.persistenceKey,e)))||(n=Ch.Es(e,n))&&(t=n.state)),this.ks.As(e),this.Ms(),t}removeLocalQueryTarget(e){this.ks.Rs(e),this.Ms()}isLocalQueryTarget(e){return this.ks.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(xh(this.persistenceKey,e))}updateQueryState(e,t,n){this.qs(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Ls(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Qs(e)}notifyBundleLoaded(e){this.Ks(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.fs),this.removeItem(this.ws),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Or("SharedClientState","READ",e,t),t}setItem(e,t){Or("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Or("SharedClientState","REMOVE",e),this.storage.removeItem(e)}gs(e){const i=e;i.storageArea===this.storage&&(Or("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.ws?this.oi.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.bs.test(i.key)){if(null==i.newValue){var e=this.$s(i.key);return this.Us(e,null)}e=this.Ws(i.key,i.newValue);if(e)return this.Us(e.clientId,e)}else if(this.Ds.test(i.key)){if(null!==i.newValue){var t=this.Gs(i.key,i.newValue);if(t)return this.zs(t)}}else if(this.Cs.test(i.key)){if(null!==i.newValue){t=this.js(i.key,i.newValue);if(t)return this.Hs(t)}}else if(i.key===this.vs){if(null!==i.newValue){var n=this.xs(i.newValue);if(n)return this.Os(n)}}else if(i.key===this.Ss){n=function(e){let t=Li._e;if(null!=e)try{var n=JSON.parse(e);qr("number"==typeof n),t=n}catch(e){Fr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==Li._e&&this.sequenceNumberHandler(n)}else if(i.key===this.Fs){const r=this.Js(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Ys(e)))}}else this.ys.push(i)}):Fr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get ks(){return this.ps.get(this.Vs)}Ms(){this.setItem(this.ws,this.ks.ds())}Bs(e,t,n){const r=new Dh(this.currentUser,e,t,n),i=Sh(this.persistenceKey,this.currentUser,e);this.setItem(i,r.ds())}Ls(e){var t=Sh(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Qs(e){var t={clientId:this.Vs,onlineState:e};this.storage.setItem(this.vs,JSON.stringify(t))}qs(e,t,n){const r=xh(this.persistenceKey,e),i=new Ch(e,t,n);this.setItem(r,i.ds())}Ks(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Fs,t)}$s(e){var t=this.bs.exec(e);return t?t[1]:null}Ws(e,t){var n=this.$s(e);return Ah.Es(n,t)}Gs(e,t){var n=this.Ds.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Dh.Es(new kr(n),r,t)}js(e,t){var n=this.Cs.exec(e),n=Number(n[1]);return Ch.Es(n,t)}xs(e){return Nh.Es(e)}Js(e){return JSON.parse(e)}async zs(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Zs(e.batchId,e.state,e.error);Or("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Hs(e){return this.syncEngine.Xs(e.targetId,e.state,e.error)}Us(e,t){const n=t?this.ps.insert(e,t):this.ps.remove(e),r=this.Ns(this.ps),i=this.Ns(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.eo(s,a).then(()=>{this.ps=n})}Os(e){this.ps.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ns(e){let n=Xa;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Lh{constructor(){this.no=new kh,this.ro={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.no.As(e),this.ro[e]||"not-current"}updateQueryState(e,t,n){this.ro[e]=t}removeLocalQueryTarget(e){this.no.Rs(e)}isLocalQueryTarget(e){return this.no.activeTargetIds.has(e)}clearQueryState(e){delete this.ro[e]}getAllActiveQueryTargets(){return this.no.activeTargetIds}isActiveQueryTarget(e){return this.no.activeTargetIds.has(e)}start(){return this.no=new kh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Mh{io(e){}shutdown(){}}class Oh{constructor(){this.so=()=>this.oo(),this._o=()=>this.ao(),this.uo=[],this.co()}io(e){this.uo.push(e)}shutdown(){window.removeEventListener("online",this.so),window.removeEventListener("offline",this._o)}co(){window.addEventListener("online",this.so),window.addEventListener("offline",this._o)}oo(){Or("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.uo)e(0)}ao(){Or("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.uo)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Fh=null;function Ph(){return null===Fh?Fh=268435456+Math.round(2147483648*Math.random()):Fh++,"0x"+Fh.toString(16)}const Vh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Bh{constructor(e){this.lo=e.lo,this.ho=e.ho}Po(e){this.Io=e}To(e){this.Eo=e}onMessage(e){this.Ao=e}close(){this.ho()}send(e){this.lo(e)}Ro(){this.Io()}Vo(e){this.Eo(e)}mo(e){this.Ao(e)}}const qh="WebChannelConnection";class Uh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.fo=t+"://"+e.host,this.po=`projects/${n}/databases/${r}`,this.yo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get wo(){return!1}So(t,e,n,r,i){const s=Ph(),a=this.bo(t,e.toUriEncodedString());Or("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.po,"x-goog-request-params":this.yo};return this.Do(o,r,i),this.Co(t,a,o,n).then(e=>(Or("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw Pr("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}vo(e,t,n,r,i,s){return this.So(e,t,n,r,i)}Do(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+Rr,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)}bo(e,t){var n=Vh[e];return`${this.fo}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Co(u,t,n,r){const c=Ph();return new Promise((s,a)=>{const o=new Dr;o.setWithCredentials(!0),o.listenOnce(Ir.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case br.NO_ERROR:var e=o.getResponseJson();Or(qh,`XHR for RPC '${u}' ${c} received:`,JSON.stringify(e)),s(e);break;case br.TIMEOUT:Or(qh,`RPC '${u}' ${c} timed out`),a(new jr(Ur.DEADLINE_EXCEEDED,"Request time out"));break;case br.HTTP_ERROR:var t=o.getStatus();if(Or(qh,`RPC '${u}' ${c} failed with status:`,t,"response text:",o.getResponseText()),0{d?Or(qh,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(l||(Or(qh,`Opening RPC '${i}' stream ${s} transport.`),h.open(),l=!0),Or(qh,`RPC '${i}' stream ${s} sending:`,e),h.send(e))},ho:()=>h.close()}),g=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return g(h,xr.EventType.OPEN,()=>{d||Or(qh,`RPC '${i}' stream ${s} transport opened.`)}),g(h,xr.EventType.CLOSE,()=>{d||(d=!0,Or(qh,`RPC '${i}' stream ${s} transport closed`),f.Vo())}),g(h,xr.EventType.ERROR,e=>{d||(d=!0,Pr(qh,`RPC '${i}' stream ${s} transport errored:`,e),f.Vo(new jr(Ur.UNAVAILABLE,"The operation could not be completed")))}),g(h,xr.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];qr(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Or(qh,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=wr[e];if(void 0!==t)return Lo(t)}(n),t=r.message;void 0===e&&(e=Ur.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,f.Vo(new jr(e,t)),h.close()}else Or(qh,`RPC '${i}' stream ${s} received:`,e),f.mo(e)}}),g(a,Er.STAT_EVENT,e=>{e.stat===Tr?Or(qh,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===Sr&&Or(qh,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{f.Ro()},0),f}}function jh(){return"undefined"!=typeof window?window:null}function Gh(){return"undefined"!=typeof document?document:null}function zh(e){return new Jo(e,!0)}class Kh{constructor(e,t,n=1e3,r=1.5,i=6e4){this.oi=e,this.timerId=t,this.Mo=n,this.xo=r,this.Oo=i,this.No=0,this.Bo=null,this.Lo=Date.now(),this.reset()}reset(){this.No=0}ko(){this.No=this.Oo}qo(e){this.cancel();var t=Math.floor(this.No+this.Qo()),n=Math.max(0,Date.now()-this.Lo),r=Math.max(0,t-n);0(this.Lo=Date.now(),e())),this.No*=this.xo,this.Nothis.Oo&&(this.No=this.Oo)}Ko(){null!==this.Bo&&(this.Bo.skipDelay(),this.Bo=null)}cancel(){null!==this.Bo&&(this.Bo.cancel(),this.Bo=null)}Qo(){return(Math.random()-.5)*this.No}}class $h{constructor(e,t,n,r,i,s,a,o){this.oi=e,this.$o=n,this.Uo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Wo=0,this.Go=null,this.zo=null,this.stream=null,this.jo=new Kh(e,t)}Ho(){return 1===this.state||5===this.state||this.Jo()}Jo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Yo()}async stop(){this.Ho()&&await this.close(0)}Zo(){this.state=0,this.jo.reset()}Xo(){this.Jo()&&null===this.Go&&(this.Go=this.oi.enqueueAfterDelay(this.$o,6e4,()=>this.e_()))}t_(e){this.n_(),this.stream.send(e)}async e_(){if(this.Jo())return this.close(0)}n_(){this.Go&&(this.Go.cancel(),this.Go=null)}r_(){this.zo&&(this.zo.cancel(),this.zo=null)}async close(e,t){this.n_(),this.r_(),this.jo.cancel(),this.Wo++,4!==e?this.jo.reset():t&&t.code===Ur.RESOURCE_EXHAUSTED?(Fr(t.toString()),Fr("Using maximum backoff delay to prevent overloading the backend."),this.jo.ko()):t&&t.code===Ur.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.i_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.To(t)}i_(){}auth(){this.state=1;const e=this.s_(this.Wo),n=this.Wo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Wo===n&&this.o_(e,t)},t=>{e(()=>{var e=new jr(Ur.UNKNOWN,"Fetching auth token failed: "+t.message);return this.__(e)})})}o_(e,t){const n=this.s_(this.Wo);this.stream=this.a_(e,t),this.stream.Po(()=>{n(()=>(this.state=2,this.zo=this.oi.enqueueAfterDelay(this.Uo,1e4,()=>(this.Jo()&&(this.state=3),Promise.resolve())),this.listener.Po()))}),this.stream.To(e=>{n(()=>this.__(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Yo(){this.state=5,this.jo.qo(async()=>{this.state=0,this.start()})}__(e){return Or("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}s_(t){return e=>{this.oi.enqueueAndForget(()=>this.Wo===t?e():(Or("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class Qh extends $h{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}a_(e,t){return this.connection.Fo("Listen",e,t)}onMessage(e){this.jo.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:Br(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.useProto3Json?(qr(void 0===f||"string"==typeof f),Is.fromBase64String(f||"")):(qr(void 0===f||f instanceof Uint8Array),Is.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?Ur.UNKNOWN:Lo(f.code),new jr(o,f.message||""));n=new zo(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var s=ou(e,u.document.name),o=nu(u.document.updateTime),c=u.document.createTime?nu(u.document.createTime):ri.min(),h=new Ys({mapValue:{fields:u.document.fields}}),c=Xs.newFoundDocument(s,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new jo(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=ou(e,h.document),c=h.readTime?nu(h.readTime):ri.min(),c=Xs.newNoDocument(u,c),h=h.removedTargetIds||[];n=new jo([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=ou(e,l.document),l=l.removedTargetIds||[];n=new jo([],l,d,null)}else{if(!("filter"in t))return Br();{t.filter;const e=t.filter;e.targetId;var{count:l=0,unchangedNames:d}=e,l=new ko(l,d),d=e.targetId;n=new Go(d,l)}}var o,f;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ri.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?nu(t.readTime):ri.min()}(e);return this.listener.u_(t,n)}c_(e){const t={};t.database=hu(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=Ea(r)?{documents:pu(e,r)}:{query:yu(e,r).ut},n.targetId=t.targetId,0function(e,t){let n=e.updateTime?nu(e.updateTime):nu(t);return n.isEqual(ri.min())&&(n=nu(t)),new fo(n,e.transformResults||[])}(e,i))):[]),n=nu(e.commitTime);return this.listener.T_(n,t)}var r,i;return qr(!e.writeResults||0===e.writeResults.length),this.h_=!0,this.listener.E_()}d_(){const e={};e.database=hu(this.serializer),this.t_(e)}I_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>gu(this.serializer,e))};this.t_(t)}}class Hh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.A_=!1}R_(){if(this.A_)throw new jr(Ur.FAILED_PRECONDITION,"The client has already been terminated.")}So(n,r,i,s){return this.R_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.So(n,iu(r,i),s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Ur.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new jr(Ur.UNKNOWN,e.toString())})}vo(n,r,i,s,a){return this.R_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.vo(n,iu(r,i),s,e,t,a)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Ur.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new jr(Ur.UNKNOWN,e.toString())})}terminate(){this.A_=!0,this.connection.terminate()}}class Yh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.m_=0,this.f_=null,this.g_=!0}p_(){0===this.m_&&(this.y_("Unknown"),this.f_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.f_=null,this.w_("Backend didn't respond within 10 seconds."),this.y_("Offline"),Promise.resolve())))}S_(e){"Online"===this.state?this.y_("Unknown"):(this.m_++,1<=this.m_&&(this.b_(),this.w_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.y_("Offline")))}set(e){this.b_(),this.m_=0,"Online"===e&&(this.g_=!1),this.y_(e)}y_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}w_(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.g_?(Fr(t),this.g_=!1):Or("OnlineStateTracker",t)}b_(){null!==this.f_&&(this.f_.cancel(),this.f_=null)}}class Xh{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.D_=[],this.C_=new Map,this.v_=new Set,this.F_=[],this.M_=i,this.M_.io(e=>{n.enqueueAndForget(async()=>{al(this)&&(Or("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.v_.add(4),await Zh(t),t.x_.set("Unknown"),t.v_.delete(4),await Jh(t)}(this))})}),this.x_=new Yh(n,r)}}async function Jh(e){if(al(e))for(const t of e.F_)await t(!0)}async function Zh(e){for(const t of e.F_)await t(!1)}function el(e,t){const n=e;n.C_.has(t.targetId)||(n.C_.set(t.targetId,t),sl(n)?il(n):pl(n).Jo()&&nl(n,t))}function tl(e,t){const n=e,r=pl(n);n.C_.delete(t),r.Jo()&&rl(n,t),0===n.C_.size&&(r.Jo()?r.Xo():al(n)&&n.x_.set("Unknown"))}function nl(e,t){var n;e.O_.Oe(t.targetId),(0t.remoteSyncer.getRemoteKeysForTarget(e),_t:e=>t.C_.get(e)||null,nt:()=>t.datastore.serializer.databaseId}),pl(t).start(),t.x_.p_()}function sl(e){return al(e)&&!pl(e).Ho()&&0mh(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Or("RemoteStore","Retrying IndexedDB access"),await n(),e.v_.delete(1),await Jh(e)})}function cl(t,n){return n().catch(e=>ul(t,e,n))}async function hl(e){const t=e,n=yl(t);let r=0(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.D_.length&&n.Xo();break}r=e.batchId,function(e,t){e.D_.push(t);const n=yl(e);n.Jo()&&n.P_&&n.I_(t.mutations)}(t,e)}catch(e){await ul(t,e)}var i;ll(t)&&dl(t)}function ll(e){return al(e)&&!yl(e).Ho()&&0e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await hl(e)}var n}(e,t),ll(e)&&dl(e)}async function gl(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Or("RemoteStore","RemoteStore received new credentials");var r=al(n);n.v_.add(3),await Zh(n),r&&n.x_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.v_.delete(3),await Jh(n)}async function ml(e,t){const n=e;t?(n.v_.delete(2),await Jh(n)):(n.v_.add(2),await Zh(n),n.x_.set("Unknown"))}function pl(t){return t.N_||(t.N_=function(e,t,n){const r=e;return r.R_(),new Qh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Po:(async function(n){n.C_.forEach((e,t)=>{nl(n,e)})}).bind(null,t),To:(async function(e,t){ol(e),sl(e)?(e.x_.S_(t),il(e)):e.x_.set("Unknown")}).bind(null,t),u_:(async function(e,t,n){if(e.x_.set("Online"),t instanceof zo&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.C_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.C_.delete(r),e.O_.removeTarget(r))}(e,t)}catch(n){Or("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await ul(e,n)}else if(t instanceof jo?e.O_.$e(t):t instanceof Go?e.O_.Je(t):e.O_.Ge(t),!n.isEqual(ri.min()))try{const t=await mh(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.O_.it(r);return e.targetChanges.forEach((e,t)=>{if(0{const n=i.C_.get(e);var r;n&&(i.C_.set(e,n.withResumeToken(Is.EMPTY_BYTE_STRING,n.snapshotVersion)),rl(i,e),r=new Tu(n.target,e,t,n.sequenceNumber),nl(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){Or("RemoteStore","Failed to raise snapshot:",t),await ul(e,t)}}).bind(null,t)}),t.F_.push(async e=>{e?(t.N_.Zo(),sl(t)?il(t):t.x_.set("Unknown")):(await t.N_.stop(),ol(t))})),t.N_}function yl(t){return t.B_||(t.B_=function(e,t,n){const r=e;return r.R_(),new Wh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Po:(async function(e){yl(e).d_()}).bind(null,t),To:fl.bind(null,t),E_:(async function(e){const t=yl(e);for(const n of e.D_)t.I_(n.mutations)}).bind(null,t),T_:(async function(e,t,n){const r=e.D_.shift(),i=Ao.from(r,t,n);await cl(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await hl(e)}).bind(null,t)}),t.F_.push(async e=>{e?(t.B_.Zo(),await hl(t)):(await t.B_.stop(),0{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new vl(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new jr(Ur.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(Fr("AsyncQueue",`${t}: ${e}`),xi(e))return new jr(Ur.UNAVAILABLE,`${t}: ${e}`);throw e}class _l{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ui.comparator(e.key,t.key):(e,t)=>ui.comparator(e.key,t.key),this.keyedMap=Ka(),this.sortedSet=new gs(this.comparator)}static emptySet(e){return new _l(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 _l))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 _l;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class bl{constructor(){this.L_=new gs(ui.comparator)}track(e){var t=e.doc.key,n=this.L_.get(t);!n||0!==e.type&&3===n.type?this.L_=this.L_.insert(t,e):3===e.type&&1!==n.type?this.L_=this.L_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.L_=this.L_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.L_=this.L_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.L_=this.L_.remove(t):1===e.type&&2===n.type?this.L_=this.L_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.L_=this.L_.insert(t,{type:2,doc:e.doc}):Br()}k_(){const n=[];return this.L_.inorderTraversal((e,t)=>{n.push(t)}),n}}class Il{constructor(e,t,n,r,i,s,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new Il(e,t,_l.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)&&Fa(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;rPa(e),Fa),this.onlineState="Unknown",this.K_=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 El),i)try{s.q_=await n.onListen(r)}catch(e){const n=wl(e,`Initialization of query '${Va(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.Q_.push(t),t.U_(n.onlineState),!s.q_||t.W_(s.q_)&&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.Q_.indexOf(t);0<=e&&(s.Q_.splice(e,1),i=0===s.Q_.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Dl(e){e.K_.forEach(e=>{e.next()})}class Cl{constructor(e,t,n){this.query=e,this.G_=t,this.z_=!1,this.j_=null,this.onlineState="Unknown",this.options=n||{}}W_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Il(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.z_?this.H_(e)&&(this.G_.next(e),t=!0):this.J_(e,this.onlineState)&&(this.Y_(e),t=!0),this.j_=e,t}onError(e){this.G_.error(e)}U_(e){this.onlineState=e;let t=!1;return this.j_&&!this.z_&&this.J_(this.j_,e)&&(this.Y_(this.j_),t=!0),t}J_(e,t){return!e.fromCache||(!this.options.Z_||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}H_(e){if(0yh(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Qr.removeMatchingKeysForTargetId(t,u.targetId).next(()=>i.Qr.addMatchingKeys(t,s,u.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.cs,e.ls)).next(()=>e.cs)))}(this.localStore,new Nl(this.serializer),this.documents,this.ta.id),t=this.ra(this.documents);for(const e of this.queries)await async function(e,n,r=Ya()){const i=await vh(e,La(Lu(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=nu(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.$r.saveNamedQuery(e,n);t=i.withResumeToken(Is.EMPTY_BYTE_STRING,t);return s.ns=s.ns.insert(t.targetId,t),s.Qr.updateTargetData(e,t).next(()=>s.Qr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Qr.addMatchingKeys(e,r,i.targetId)).next(()=>s.$r.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,ia:this.collectionGroups,sa:e}}}function Rl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Ll{constructor(e){this.key=e}}class Ml{constructor(e){this.key=e}}class Ol{constructor(e,t){this.query=e,this.oa=t,this._a=null,this.hasCachedResults=!1,this.current=!1,this.aa=Ya(),this.mutatedKeys=Ya(),this.ua=Ua(e),this.ca=new _l(this.ua)}get la(){return this.oa}ha(e,t){const o=t?t.Pa:new bl,u=(t||this).ca;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=Ba(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Ia(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0this.query.limit;){const e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),c=c.delete(e.key),o.track({type:1,doc:e})}return{ca:h,Pa:o,Xi:l,mutatedKeys:c}}Ia(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){var i=this.ca;this.ca=e.ca,this.mutatedKeys=e.mutatedKeys;const s=e.Pa.k_();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Br()}};return n(e)-n(t)}(e.type,t.type)||this.ua(e.doc,t.doc)),this.Ta(n),r=null!=r&&r;var a=t&&!r?this.Ea():[],o=0===this.aa.size&&this.current&&!r?1:0,u=o!==this._a;return this._a=o,0!==s.length||u?{snapshot:new Il(this.query,e.ca,i,s,e.mutatedKeys,0==o,u,!1,!!n&&0this.oa=this.oa.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.oa=this.oa.delete(e)),this.current=e.current)}Ea(){if(!this.current)return[];const t=this.aa;this.aa=Ya(),this.ca.forEach(e=>{this.Aa(e.key)&&(this.aa=this.aa.add(e.key))});const n=[];return t.forEach(e=>{this.aa.has(e)||n.push(new Ml(e))}),this.aa.forEach(e=>{t.has(e)||n.push(new Ll(e))}),n}Ra(e){this.oa=e.hs,this.aa=Ya();var t=this.ha(e.documents);return this.applyChanges(t,!0)}Va(){return Il.fromInitialDocuments(this.query,this.ca,this.mutatedKeys,0===this._a,this.hasCachedResults)}}class Fl{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Pl{constructor(e){this.key=e,this.ma=!1}}class Vl{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.fa={},this.ga=new ja(e=>Pa(e),Fa),this.pa=new Map,this.ya=new Set,this.wa=new gs(ui.comparator),this.Sa=new Map,this.ba=new Qc,this.Da={},this.Ca=new Map,this.va=Ec.Bn(),this.onlineState="Unknown",this.Fa=void 0}get isPrimaryClient(){return!0===this.Fa}}async function Bl(r,e,t,n,i){r.Ma=(e,t,n)=>async function(e,t,n,r){let i=t.view.ha(n);i.Xi&&(i=await _h(e.localStore,t.query,!1).then(({documents:e})=>t.view.ha(e,i)));var s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s,a);return Wl(e,t.targetId,a.da),a.snapshot}(r,e,t,n);const s=await _h(r.localStore,e,!0),a=new Ol(e,s.hs),o=a.ha(s.documents),u=Uo.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),c=a.applyChanges(o,r.isPrimaryClient,u);Wl(r,t,c.da);var h=new Fl(e,t,a);return r.ga.set(e,h),r.pa.has(t)?r.pa.get(t).push(e):r.pa.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,a=ni.now(),o=i.reduce((e,t)=>e.add(t.key),Ya());let u,c;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=Ga,r=Ya();return s.os.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=no(r.transform,e||null);null!=i&&(null===n&&(n=Ys.empty()),n.set(r.field,i))}return n||null}(n,u.get(n.key).overlayedDocument);null!=i&&t.push(new Io(n.key,i,function r(e){const i=[];return ds(e.fields,(e,t)=>{const n=new oi([e]);if(Ks(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 _s(i)}(i.value.mapValue),go.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:$a(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Da[e.currentUser.toKey()];r=r||new gs(Zr),r=r.insert(t,n),e.Da[e.currentUser.toKey()]=r}(r,e.batchId,n),await Yl(r,e.changes),await hl(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 ph(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Sa.get(t);n&&(qr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0{var n=t.view.U_(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.Q_)e.U_(n)&&(r=!0)}),r&&Dl(t)}(t.eventManager,i),r.length&&t.fa.u_(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.os.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=bi.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);qr(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Ya();for(let n=0;ni.localDocuments.getDocuments(e,t))})}(n.localStore,t);Kl(n,r,null),zl(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Yl(n,e)}catch(e){await _i(e)}}function zl(e,t){(e.Ca.get(t)||[]).forEach(e=>{e.resolve()}),e.Ca.delete(t)}function Kl(e,t,n){const r=e;let i=r.Da[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Da[r.currentUser.toKey()]=i}}function $l(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.pa.get(e))t.ga.delete(r),n&&t.fa.xa(r,n);t.pa.delete(e),t.isPrimaryClient&&t.ba.Vr(e).forEach(e=>{t.ba.containsKey(e)||Ql(t,e)})}function Ql(e,t){e.ya.delete(t.path.canonicalString());var n=e.wa.get(t);null!==n&&(tl(e.remoteStore,n),e.wa=e.wa.remove(t),e.Sa.delete(n),Hl(e))}function Wl(e,t,n){for(const r of n)r instanceof Ll?(e.ba.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.wa.get(n)||e.ya.has(r)||(Or("SyncEngine","New document in limbo: "+n),e.ya.add(r),Hl(e))}(e,r)):r instanceof Ml?(Or("SyncEngine","Document no longer in limbo: "+r.key),e.ba.removeReference(r.key,t),e.ba.containsKey(r.key)||Ql(e,r.key)):Br()}function Hl(e){for(;0{o.push(i.Ma(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=ch.Ki(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.fa.u_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>bi.forEach(t,t=>bi.forEach(t.qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>bi.forEach(t.Qi,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!xi(e))throw e;Or("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ns.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.ns=r.ns.insert(t,i)}}}(i.localStore,a))}async function Xl(r,e){const i=r;if(ed(i),td(i),!0===e&&!0!==i.Fa){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Jl(i,r.toArray());i.Fa=!0,await ml(i.remoteStore,!0);for(const r of e)el(i.remoteStore,r)}else if(!1===e&&!1!==i.Fa){const r=[];let n=Promise.resolve();i.pa.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>($l(i,t),wh(i.localStore,t,!0))),tl(i.remoteStore,t)}),await n,await Jl(i,r),function(e){const n=e;n.Sa.forEach((e,t)=>{tl(n.remoteStore,t)}),n.ba.mr(),n.Sa=new Map,n.wa=new gs(ui.comparator)}(i),i.Fa=!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.pa.get(t);if(h&&0!==h.length){e=await vh(r.localStore,La(h[0]));for(const t of h){const n=r.ga.get(t),h=(a=r,o=n,c=u=void 0,c=await _h((u=a).localStore,o.query,!0),c=o.view.Ra(c),u.isPrimaryClient&&Wl(u,o.targetId,c.da),await c);h.snapshot&&s.push(h.snapshot)}}else{const h=await bh(r.localStore,t);e=await vh(r.localStore,h),await Bl(r,Zl(h),t,!1,e.resumeToken)}i.push(e)}var a,o,u,c;return r.fa.u_(s),i}function Zl(e){return Ca(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.Sa.get(t);if(r&&r.ma)return Ya().add(r.key);{let e=Ya();const r=n.pa.get(t);if(!r)return e;for(const t of r){const r=n.ga.get(t);e=e.unionWith(r.view.la)}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.Sa.get(t),s=i&&i.key;if(s){let e=new gs(ui.comparator);e=e.insert(s,Xs.newNoDocument(s,ri.min()));const n=Ya().add(s),i=new qo(ri.min(),new Map,new gs(Zr),e,n);await Ul(r,i),r.wa=r.wa.remove(s),r.Sa.delete(t),Hl(r)}else await wh(r.localStore,t,!1).then(()=>$l(r,t,n)).catch(_i)}).bind(null,t),t.fa.u_=(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.Q_)t.W_(e)&&(r=!0);i.q_=e}}r&&Dl(n)}).bind(null,t.eventManager),t.fa.xa=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.Q_)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=>(qr(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);Kl(r,t,n),zl(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Yl(r,e)}catch(n){await _i(n)}}).bind(null,t),t}class nd{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=zh(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 fh(this.persistence,new lh,e.initialUser,this.serializer)}createPersistence(e){return new Zc(th.Hr,this.serializer)}createSharedClientState(e){return new Lh}async terminate(){var e;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(e=this.indexBackfillerScheduler)||void 0===e||e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class rd extends nd{constructor(e,t,n){super(),this.Na=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Na.initialize(this,e),await td(this.Na.syncEngine),await hl(this.Na.remoteStore),await this.persistence.fi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return fh(this.persistence,new lh,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new Nc(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Ri(t,this.persistence);return new ki(e.asyncQueue,n)}createPersistence(e){var t=uh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?mc.withCacheSize(this.cacheSizeBytes):mc.DEFAULT;return new sh(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,jh(),Gh(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new Lh}}class id extends rd{constructor(e,t){super(e,t,!1),this.Na=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Na.syncEngine;this.sharedClientState instanceof Rh&&(this.sharedClientState.syncEngine={Zs:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.vn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):bi.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await hl(i.remoteStore):"acknowledged"===n||"rejected"===n?(Kl(i,t,r||null),zl(i,t),i.localStore.mutationQueue.Mn(t)):Br(),await Yl(i,s)):Or("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Xs:(async function(e,t,n,r){const i=e;if(i.Fa)Or("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.pa.get(t);if(s&&0{tl(r.remoteStore,e),$l(r,e)}).catch(_i)}}).bind(null,t),Li:(function(e){return e.localStore.persistence.Li()}).bind(null,t),Ys:(async function(e,t){const n=e;return Ih(n.localStore,t).then(e=>Yl(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.fi(async e=>{await Xl(this.Na.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=jh();if(!Rh.D(t))throw new jr(Ur.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=uh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Rh(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)){Or("SyncEngine","User change. New user:",t.toKey());const i=await gh(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.Ca.forEach(e=>{e.forEach(e=>{e.reject(new jr(Ur.CANCELLED,r))})}),e.Ca.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await Yl(n,i.us)}var r}).bind(null,this.syncEngine),await ml(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Tl}createDatastore(e){var t,n,r,i=zh(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new Uh(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new Hh(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>jl(this.syncEngine,e,0),e=new(Oh.D()?Oh:Mh),new Xh(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Vl(e,t,n,r,i,s);return a&&(o.Fa=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e;await async function(e){const t=e;Or("RemoteStore","RemoteStore shutting down."),t.v_.add(5),await Zh(t),t.M_.shutdown(),t.x_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate()}}function ad(t,n=10240){let r=0;return{async read(){if(r{this.muted||e(t)},0)}}class ud{constructor(e,t){this.ka=e,this.serializer=t,this.metadata=new Gr,this.buffer=new Uint8Array,this.qa=new TextDecoder("utf-8"),this.Qa().then(e=>{e&&e.ea()?this.metadata.resolve(e.X_.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.X_)}`))},e=>this.metadata.reject(e))}close(){return this.ka.cancel()}async getMetadata(){return this.metadata.promise}async Oa(){return await this.getMetadata(),this.Qa()}async Qa(){var e=await this.Ka();if(null===e)return null;var t=this.qa.decode(e),n=Number(t);isNaN(n)&&this.$a(`length string (${t}) is not valid number`);t=await this.Ua(n);return new Al(JSON.parse(t),e.length+n)}Wa(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ka(){for(;this.Wa()<0&&!await this.Ga(););if(0===this.buffer.length)return null;var e=this.Wa();e<0&&this.$a("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 Ua(e){for(;this.buffer.lengthau(r.serializer,e))},i=await r.vo("BatchGetDocuments",r.serializer.databaseId,si.emptyPath(),n,t.length),s=new Map;i.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){qr(!!t.found),t.found.name,t.found.updateTime;var n=ou(e,t.found.name),r=nu(t.found.updateTime),i=t.found.createTime?nu(t.found.createTime):ri.min(),s=new Ys({mapValue:{fields:t.found.fields}});return Xs.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){qr(!!t.missing),qr(!!t.readTime);var n=ou(e,t.missing),r=nu(t.readTime);return Xs.newNoDocument(n,r)}(n,e):Br());var n;s.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=s.get(e.toString());qr(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new xo(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=ui.fromPath(t);this.mutations.push(new Do(n,this.precondition(n)))}),await async function(e,t){const n=e,r={writes:t.map(e=>gu(n.serializer,e))};await n.So("Commit",n.serializer.databaseId,si.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Br();t=ri.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new jr(Ur.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(ri.min())?go.exists(!1):go.updateTime(t):go.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return go.exists(!0);if(t.isEqual(ri.min()))throw new jr(Ur.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return go.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.za=n.maxAttempts,this.jo=new Kh(this.asyncQueue,"transaction_retry")}ja(){--this.za,this.Ha()}Ha(){this.jo.qo(async()=>{const t=new cd(this.datastore),e=this.Ja(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Ya(e)}))}).catch(e=>{this.Ya(e)})})}Ja(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}}Ya(e){0(this.Ha(),Promise.resolve()))):this.deferred.reject(e)}Za(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!Ro(t)}}class ld{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=kr.UNAUTHENTICATED,this.clientId=Jr.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Or("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Or("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new jr(Ur.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Gr;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(),Or("FirestoreClient","Initializing OfflineComponentProvider");var n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await gh(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);Or("FirestoreClient","Initializing OnlineComponentProvider"),await n.initialize(t,e.configuration),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===Ur.FAILED_PRECONDITION||e.code===Ur.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){Or("FirestoreClient","Using user provided OfflineComponentProvider");try{await dd(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!gd(n))throw n;Pr("Error using user provided cache. Falling back to memory cache: "+n),await dd(t,new nd)}}else Or("FirestoreClient","Using default OfflineComponentProvider"),await dd(t,new nd);return t._offlineComponents}async function pd(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Or("FirestoreClient","Using user provided OnlineComponentProvider"),await fd(e,e._uninitializedComponentsProvider._online)):(Or("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 _d(e){return pd(e).then(e=>e.syncEngine)}async function bd(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.ga.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Va();else{const e=await vh(n.localStore,La(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Bl(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&el(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ga.get(t),i=n.pa.get(r.targetId);if(1!Fa(e,t))),void n.ga.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await wh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),tl(n.remoteStore,r.targetId),$l(n,r.targetId)}).catch(_i)):($l(n,r.targetId),await wh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function Id(e,t,n={}){const r=new Gr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new od({next:e=>{r.enqueueAndForget(()=>xl(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new jr(Ur.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new jr(Ur.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new Cl(Aa(i.path),e,{includeMetadataChanges:!0,Z_:!0});return Sl(n,o)}(await bd(e),e.asyncQueue,t,n,r)),r.promise}function Ed(e,t,n={}){const r=new Gr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new od({next:e=>{n.enqueueAndForget(()=>xl(t,a)),e.fromCache&&"server"===r.source?i.reject(new jr(Ur.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new Cl(e,s,{includeMetadataChanges:!0,Z_:!0});return Sl(t,a)}(await bd(e),e.asyncQueue,t,n,r)),r.promise}function Td(e,t,n,r){const i=(n=n,t=zh(t),s="string"==typeof n?Mo().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return ad(e,t);if(e instanceof ArrayBuffer)return ad(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new 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=nu(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.$r.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(Rl(i));const a=new kl(i,t.localStore,n.serializer);let e=await n.Oa();for(;e;){const t=await a.na(e);t&&r._updateProgress(t),e=await n.Oa()}var s=await a.complete();return await Yl(t,s.sa,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.$r.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.ia)}catch(t){return Pr("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await _d(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 jr(Ur.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Cd(e,t,n,r){if(!0===t&&!0===r)throw new jr(Ur.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Ad(e){if(!ui.isDocumentKey(e))throw new jr(Ur.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Nd(e){if(ui.isDocumentKey(e))throw new jr(Ur.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{var e=Gh();e&&Or("AsyncQueue","Visibility state changed to "+e.visibilityState),this.jo.Ko()};const e=Gh();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this._u)}get isShuttingDown(){return this.tu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.au(),this.uu(e)}enterRestrictedMode(e){if(!this.tu){this.tu=!0,this.su=e||!1;const t=Gh();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this._u)}}enqueue(e){if(this.au(),this.tu)return new Promise(()=>{});const t=new Gr;return this.uu(()=>this.tu&&this.su?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.eu.push(e),this.cu()))}async cu(){if(0!==this.eu.length){try{await this.eu[0](),this.eu.shift(),this.jo.reset()}catch(e){if(!xi(e))throw e;Or("AsyncQueue","Operation failed with retryable error: "+e)}0this.cu())}}uu(e){var t=this.Xa.then(()=>(this.iu=!0,e().catch(e=>{throw this.ru=e,this.iu=!1,Fr("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.iu=!1,e))));return this.Xa=t}enqueueAfterDelay(e,t,n){this.au(),-1this.lu(e));return this.nu.push(r),r}au(){this.ru&&Br()}verifyOperationInProgress(){}async hu(){for(var e;await(e=this.Xa),e!==this.Xa;);}Pu(e){for(const t of this.nu)if(t.timerId===e)return!0;return!1}Iu(t){return this.hu().then(()=>{this.nu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.nu)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.hu()})}Tu(e){this.ou.push(e)}lu(e){var t=this.nu.indexOf(e);this.nu.splice(t,1)}}function Kd(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class $d{constructor(){this._progressObserver={},this._taskCompletionResolver=new Gr,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,Wd,Hd,Yd,Xd;class Jd extends Od{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||ef(this),this._firestoreClient.terminate()}}function Zd(e){return e._firestoreClient||ef(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function ef(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new Ns(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,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function tf(e,t,n){const r=new Gr;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;Pr("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function nf(e){return function(e){const t=new Gr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;al(n.remoteStore)||Or("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Ca.get(e)||[];r.push(t),n.Ca.set(e,r)}catch(e){const n=wl(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await _d(e),t)),t.promise}(Zd(e=Rd(e,Jd)))}function rf(e){return(n=Zd(e=Rd(e,Jd))).asyncQueue.enqueue(async()=>{const e=await yd(n),t=await wd(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.v_.delete(0),Jh(t)}(t)});var n}function sf(e){return(n=Zd(e=Rd(e,Jd))).asyncQueue.enqueue(async()=>{const e=await yd(n),t=await wd(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.v_.add(0),await Zh(t),t.x_.set("Offline")}(t)});var n}function af(t,e){return n=Zd(t=Rd(t,Jd)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.$r.getNamedQuery(e,t))}(await vd(n),r)).then(e=>e?new Pd(t,null,e.query):null);var n,r}function of(e){if(e._initialized||e._terminated)throw new jr(Ur.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 uf{constructor(e){this._byteString=e}static fromBase64String(e){try{return new uf(Is.fromBase64String(e))}catch(e){throw new jr(Ur.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new uf(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 cf{constructor(...e){for(let t=0;tt.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}Eu(){if(this.path)for(let e=0;eu.covers(e.field))}else u=null,c=a.fieldTransforms;return new ff(new Ys(o),u,c)}class _f extends hf{_toFieldTransform(e){if(2!==e.du)throw 1===e.du?e.pu(`${this._methodName}() can only appear at the top level of your update data`):e.pu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof _f}}function bf(e,t,n){return new pf({du:3,wu:t.settings.wu,methodName:e._methodName,Vu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class If extends hf{_toFieldTransform(e){return new lo(e.path,new ro)}isEqual(e){return e instanceof If}}class Ef extends hf{constructor(e,t){super(e),this.bu=t}_toFieldTransform(e){const t=bf(this,e,!0),n=this.bu.map(e=>Af(e,t)),r=new io(n);return new lo(e.path,r)}isEqual(e){return e instanceof Ef&&m(this.bu,e.bu)}}class Tf extends hf{constructor(e,t){super(e),this.bu=t}_toFieldTransform(e){const t=bf(this,e,!0),n=this.bu.map(e=>Af(e,t)),r=new ao(n);return new lo(e.path,r)}isEqual(e){return e instanceof Tf&&m(this.bu,e.bu)}}class Sf extends hf{constructor(e,t){super(e),this.Du=t}_toFieldTransform(e){var t=new uo(e.serializer,eo(e.serializer,this.Du));return new lo(e.path,t)}isEqual(e){return e instanceof Sf&&this.Du===e.Du}}function xf(e,i,s,t){const a=e.Su(1,i,s);Rf("Data must be an object, but it was:",a,t);const o=[],u=Ys.empty();ds(t,(e,t)=>{var n=Of(i,e,s);t=y(t);var r=a.fu(n);if(t instanceof _f)o.push(n);else{const e=Af(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new _s(o);return new gf(u,n,a.fieldTransforms)}function Df(e,t,n,r,i,s){const a=e.Su(1,t,n),o=[Lf(t,r,n)],u=[i];if(s.length%2!=0)throw new jr(Ur.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{var n=Af(t,r.Ru(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function kf(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ni||e instanceof lf||e instanceof uf||e instanceof Vd||e instanceof hf)}function Rf(e,t,n){if(!kf(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.pu(e+" a custom object"):t.pu(e+" "+r)}var i}function Lf(e,t,n){if((t=y(t))instanceof cf)return t._internalPath;if("string"==typeof t)return Of(e,t);throw Ff("Field path arguments must be of type string or ",e,!1,void 0,n)}const Mf=new RegExp("[~\\*/\\[\\]]");function Of(t,n,r){if(0<=n.search(Mf))throw Ff(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new cf(...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(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(s||a)&&(u+=" (found",s&&(u+=` in field ${r}`),a&&(u+=` in document ${i}`),u+=")"),new jr(Ur.INVALID_ARGUMENT,o+e+u)}function Pf(e,t){return e.some(e=>e.isEqual(t))}class Vf{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 Bf(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(qf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Bf extends Vf{data(){return super.data()}}function qf(e,t){return"string"==typeof t?Of(e,t):(t instanceof cf?t:t._delegate)._internalPath}function Uf(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new jr(Ur.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class jf{}class Gf extends jf{}function zf(e,t,...n){let r=[];t instanceof jf&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof $f).length,n=e.filter(e=>e instanceof Kf).length;if(1e._parse(t)).filter(e=>0a.length)throw new jr(Ur.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new lf(Ss(e.latitude),Ss(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=Cs(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(As(e));default:return null}}convertTimestamp(e){var t=Ts(e);return new ni(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=si.fromString(e);qr(Eu(n));const r=new ks(n.get(1),n.get(3)),i=new ui(n.popFirst(5));return r.isEqual(t)||Fr(`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 ng(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class rg extends tg{constructor(e){super(),this.firestore=e}convertBytes(e){return new uf(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Vd(this.firestore,null,t)}}class ig{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class sg extends Vf{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 ag(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(qf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class ag extends sg{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 ig(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 ag(this._firestore,this._userDataWriter,e.key,e,new ig(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 jr(Ur.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 ag(s._firestore,s._userDataWriter,e.doc.key,e.doc,new ig(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 ag(s._firestore,s._userDataWriter,e.doc.key,e.doc,new ig(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 Br()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function ug(e,t){return e instanceof sg&&t instanceof sg?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 cg extends tg{constructor(e){super(),this.firestore=e}convertBytes(e){return new uf(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Vd(this.firestore,null,t)}}function hg(t){t=Rd(t,Vd);const n=Rd(t.firestore,Jd),e=Zd(n),r=new cg(n);return function(e,t){const n=new Gr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new jr(Ur.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 sg(n,r,t._key,e,new ig(null!==e&&e.hasLocalMutations,!0),t.converter))}function lg(t){t=Rd(t,Pd);const n=Rd(t.firestore,Jd),e=Zd(n),r=new cg(n);return function(e,t){const n=new Gr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await _h(e,t,!0),s=new Ol(t,i.hs),a=s.ha(i.documents),o=s.applyChanges(a,!1);n.resolve(o.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 dg(e,t,n){e=Rd(e,Vd);var r=Rd(e.firestore,Jd),i=ng(e.converter,t,n);return pg(r,[wf(vf(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,go.none())])}function fg(e,t,n,...r){e=Rd(e,Vd);var i=Rd(e.firestore,Jd),s=vf(i);let a;return a="string"==typeof(t=y(t))||t instanceof cf?Df(s,"updateDoc",e._key,t,n,r):xf(s,"updateDoc",e._key,t),pg(i,[a.toMutation(e._key,go.exists(!0))])}function gg(t,...n){var e;t=y(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||Kd(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(Kd(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Vd)o=Rd(t.firestore,Jd),u=Aa(t._key.path),a={next:e=>{n[i]&&n[i](yg(o,t,e))},error:n[i+1],complete:n[i+2]};else{const c=Rd(t,Pd);o=Rd(c.firestore,Jd),u=c._query;const h=new cg(o);a={next:e=>{n[i]&&n[i](new og(o,h,c,e))},error:n[i+1],complete:n[i+2]},Uf(t._query)}return function(e,t,n,r){const i=new od(r),s=new Cl(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Sl(await bd(e),s)),()=>{i.La(),e.asyncQueue.enqueueAndForget(async()=>xl(await bd(e),s))}}(Zd(o),u,s,a)}function mg(e,t){return function(e,t){const n=new od(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.K_.add(t),t.next()}(await bd(e),n)),()=>{n.La(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.K_.delete(t)}(await bd(e),n))}}(Zd(e=Rd(e,Jd)),Kd(t)?t:{next:t})}function pg(e,t){return function(e,t){const n=new Gr;return e.asyncQueue.enqueueAndForget(async()=>ql(await _d(e),t,n)),n.promise}(Zd(e),t)}function yg(e,t,n){var r=n.docs.get(t._key),i=new cg(e);return new sg(e,i,t._key,r,new ig(n.hasPendingWrites,n.fromCache),t.converter)}const vg={maxAttempts:5};class wg{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=vf(e)}set(e,t,n){this._verifyNotCommitted();const r=_g(e,this._firestore),i=ng(r.converter,t,n),s=wf(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,go.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=_g(e,this._firestore);let s;return s="string"==typeof(t=y(t))||t instanceof cf?Df(this._dataReader,"WriteBatch.update",i._key,t,n,r):xf(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,go.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=_g(e,this._firestore);return this._mutations=this._mutations.concat(new xo(t._key,go.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0{if(!e||1!==e.length)return Br();const t=e[0];if(t.isFoundDocument())return new Vf(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Vf(this._firestore,r,n._key,null,n.converter);throw Br()})}set(e,t,n){var r=_g(e,this._firestore),i=ng(r.converter,t,n),i=wf(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=_g(e,this._firestore),s="string"==typeof(t=y(t))||t instanceof cf?Df(this._dataReader,"Transaction.update",i._key,t,n,r):xf(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=_g(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=_g(e,this._firestore),n=new cg(this._firestore);return super.get(e).then(e=>new sg(this._firestore,n,t._key,e._document,new ig(!1,!1),t.converter))}}function Ig(t,n,e){t=Rd(t,Jd);var r=Object.assign(Object.assign({},vg),e);return function(e){if(e.maxAttempts<1)throw new jr(Ur.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new Gr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await pd(t).then(e=>e.datastore);new hd(t.asyncQueue,e,r,n,i).ja()}),i.promise}(Zd(t),e=>n(new bg(t,e)),r)}Wd=!0,Hd=Hg.SDK_VERSION,Rr=Hd,Hg._registerComponent(new v("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new Jd(new Qr(e.getProvider("auth-internal")),new Xr(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new jr(Ur.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new ks(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:Wd},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),Hg.registerVersion(Nr,"4.4.2",Qd),Hg.registerVersion(Nr,"4.4.2","esm2017");function Eg(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new jr("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Tg(){if("undefined"==typeof Uint8Array)throw new jr("unimplemented","Uint8Arrays are not available in this environment.")}function Sg(){if("undefined"==typeof atob)throw new jr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class xg{constructor(e){this._delegate=e}static fromBase64String(e){return Sg(),new xg(uf.fromBase64String(e))}static fromUint8Array(e){return Tg(),new xg(uf.fromUint8Array(e))}toBase64(){return Sg(),this._delegate.toBase64()}toUint8Array(){return Tg(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Dg(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 Cg{enableIndexedDbPersistence(e,t){return function(e,t){of(e=Rd(e,Jd));var n=Zd(e);if(n._uninitializedComponentsProvider)throw new jr(Ur.FAILED_PRECONDITION,"SDK cache is already specified.");Pr("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new sd;return tf(n,i,new rd(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){of(e=Rd(e,Jd));var t=Zd(e);if(t._uninitializedComponentsProvider)throw new jr(Ur.FAILED_PRECONDITION,"SDK cache is already specified.");Pr("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new sd;return tf(t,r,new id(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new jr(Ur.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Gr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Ei.D())return Promise.resolve();var t=e+"main";await Ei.delete(t)}(uh(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 ks||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Pr("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={}){Fd(this._delegate,e,t,n)}enableNetwork(){return rf(this._delegate)}disableNetwork(){return sf(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Cd("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 nf(this._delegate)}onSnapshotsInSync(e){return mg(this._delegate,e)}get app(){if(!this._appCompat)throw new jr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Gg(this,qd(this._delegate,e))}catch(e){throw Og(e,"collection()","Firestore.collection()")}}doc(e){try{return new Mg(this,Ud(this._delegate,e))}catch(e){throw Og(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new qg(this,function(e,t){if(e=Rd(e,Od),Dd("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new jr(Ur.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Pd(e,null,(t=t,new Da(si.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Og(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Ig(this._delegate,e=>t(new kg(this,e)))}batch(){return Zd(this._delegate),new Rg(new wg(this._delegate,e=>pg(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Zd(t=Rd(t,Jd)),r=new $d,Td(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return af(this._delegate,e).then(e=>e?new qg(this,e):null)}}class Ng extends tg{constructor(e){super(),this.firestore=e}convertBytes(e){return new xg(new uf(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Mg.forKey(t,this.firestore,null)}}class kg{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Ng(e)}get(e){const t=zg(e);return this._delegate.get(t).then(e=>new Vg(this._firestore,new sg(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=zg(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=zg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=zg(e);return this._delegate.delete(t),this}}class Rg{constructor(e){this._delegate=e}set(e,t,n){var r=zg(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=zg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=zg(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Lg{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new ag(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Bg(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=Lg.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Lg(e,new Ng(e),t),r.set(t,i)),i}}Lg.INSTANCES=new WeakMap;class Mg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Ng(e)}static forPath(e,t,n){if(e.length%2!=0)throw new jr("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 ui(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 Gg(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Gg(this.firestore,qd(this._delegate,e))}catch(e){throw Og(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=y(e))instanceof Vd&&jd(this._delegate,e)}set(e,t){t=Eg("DocumentReference.set",t);try{return t?dg(this._delegate,e,t):dg(this._delegate,e)}catch(e){throw Og(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?fg(this._delegate,e):fg(this._delegate,e,t,...n)}catch(e){throw Og(e,"updateDoc()","DocumentReference.update()")}}delete(){return pg(Rd((e=this._delegate).firestore,Jd),[new xo(e._key,go.none())]);var e}onSnapshot(...e){var t=Fg(e),n=Pg(e,e=>new Vg(this.firestore,new sg(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return gg(this._delegate,t,n)}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,Vd);const n=Rd(t.firestore,Jd);return Id(Zd(n),t._key,{source:"server"}).then(e=>yg(n,t,e))}:function(t){t=Rd(t,Vd);const n=Rd(t.firestore,Jd);return Id(Zd(n),t._key).then(e=>yg(n,t,e))})(this._delegate),t.then(e=>new Vg(this.firestore,new sg(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(Lg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Og(e,t,n){return e.message=e.message.replace(t,n),e}function Fg(e){for(const t of e)if("object"==typeof t&&!Dg(t))return t;return{}}function Pg(e,t){var n;let r;return r=Dg(e[0])?e[0]:Dg(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 ug(this._delegate,e._delegate)}}class Bg extends Vg{data(e){var t=this._delegate.data(e);return this._delegate._converter||void 0!==t||Br(),t}}class qg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Ng(e)}where(e,t,n){try{return new qg(this.firestore,zf(this._delegate,(r=n,i=t,s=qf("where",e),Kf._create(s,i,r))))}catch(e){throw Og(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new qg(this.firestore,zf(this._delegate,([n,r="asc"]=[e,t],i=r,s=qf("orderBy",n),Qf._create(s,i))))}catch(e){throw Og(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new qg(this.firestore,zf(this._delegate,(Ld("limit",t=e),Wf._create("limit",t,"F"))))}catch(e){throw Og(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new qg(this.firestore,zf(this._delegate,(Ld("limitToLast",t=e),Wf._create("limitToLast",t,"L"))))}catch(e){throw Og(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new qg(this.firestore,zf(this._delegate,function(...e){return Hf._create("startAt",e,!0)}(...e)))}catch(e){throw Og(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new qg(this.firestore,zf(this._delegate,function(...e){return Hf._create("startAfter",e,!1)}(...e)))}catch(e){throw Og(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new qg(this.firestore,zf(this._delegate,function(...e){return Yf._create("endBefore",e,!1)}(...e)))}catch(e){throw Og(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new qg(this.firestore,zf(this._delegate,function(...e){return Yf._create("endAt",e,!0)}(...e)))}catch(e){throw Og(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)?lg:"server"===(null==e?void 0:e.source)?function(t){t=Rd(t,Pd);const n=Rd(t.firestore,Jd),e=Zd(n),r=new cg(n);return Ed(e,t._query,{source:"server"}).then(e=>new og(n,r,t,e))}:function(t){t=Rd(t,Pd);const n=Rd(t.firestore,Jd),e=Zd(n),r=new cg(n);return Uf(t._query),Ed(e,t._query).then(e=>new og(n,r,t,e))})(this._delegate),t.then(e=>new jg(this.firestore,new og(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Fg(e),n=Pg(e,e=>new jg(this.firestore,new og(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return gg(this._delegate,t,n)}withConverter(e){return new qg(this.firestore,e?this._delegate.withConverter(Lg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Ug{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Bg(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class jg{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new qg(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 Bg(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Ug(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Bg(this._firestore,e))})}isEqual(e){return ug(this._delegate,e._delegate)}}class Gg extends qg{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 Og(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Rd(e.firestore,Jd),r=Ud(e),i=ng(e.converter,t);return pg(n,[wf(vf(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,go.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 Gg(this.firestore,e?this._delegate.withConverter(Lg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function zg(e){return Rd(e,Vd)}const Kg={Firestore:Ag,GeoPoint:lf,Timestamp:ni,Blob:xg,Transaction:kg,WriteBatch:Rg,DocumentReference:Mg,DocumentSnapshot:Vg,Query:qg,QueryDocumentSnapshot:Bg,QuerySnapshot:jg,CollectionReference:Gg,FieldPath:class $g{constructor(...e){this._delegate=new cf(...e)}static documentId(){return new $g(oi.keyField().canonicalString())}isEqual(e){return(e=y(e))instanceof cf&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Qg{constructor(e){this._delegate=e}static serverTimestamp(){const e=new If("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Qg(e)}static delete(){const e=new _f("deleteField");return e._methodName="FieldValue.delete",new Qg(e)}static arrayUnion(...e){const t=function(...e){return new Ef("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Qg(t)}static arrayRemove(...e){const t=function(...e){return new Tf("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Qg(t)}static increment(e){const t=new Sf("increment",e);return t._methodName="FieldValue.increment",new Qg(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,Lr.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Yd=t.default,Xd=(e,t)=>new Ag(e,t,new Cg),Yd.INTERNAL.registerComponent(new v("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Xd(t,n)},"PUBLIC").setServiceProps(Object.assign({},Kg))),Yd.registerVersion("@firebase/firestore-compat","0.3.25")}).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