!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).firebase,t.firebase.INTERNAL.modularAPIs)}(this,function(ff,gf){"use strict";try{!function(){function t(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var e=t(ff),r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};var o=function(){return(o=Object.assign||function(t){for(var e,n=1,r=arguments.length;n>6|192:(55296==(64512&s)&&r+1>18|240,e[n++]=s>>12&63|128):e[n++]=s>>12|224,e[n++]=s>>6&63|128),e[n++]=63&s|128)}return e}var s={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:function(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[],s=0;s>6,u=63&u;h||(u=64,o||(c=64)),r.push(n[i>>2],n[(3&i)<<4|a>>4],n[c],n[u])}return r.join("")},encodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(n(t),e)},decodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){for(var e=[],n=0,r=0;n>10)),e[r++]=String.fromCharCode(56320+(1023&s))):(i=t[n++],o=t[n++],e[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&o))}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray:function(t,e){this.init_();for(var n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],s=0;s>4),64!==a&&(r.push(o<<4&240|a>>2),64!==h&&r.push(a<<6&192|h))}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},h=function(t){return function(t){t=n(t);return s.encodeByteArray(t,!0)}(t).replace(/\./g,"")};function d(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function i(){return!function(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(t){return}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}var u,c="FirebaseError",l=(function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(f,u=Error),f);function f(t,e,n){e=u.call(this,e)||this;return e.code=t,e.customData=n,e.name=c,Object.setPrototypeOf(e,f.prototype),Error.captureStackTrace&&Error.captureStackTrace(e,g.prototype.create),e}var g=(m.prototype.create=function(t){for(var e=[],n=1;n"})):"Error",t=this.serviceName+": "+t+" ("+i+").";return new l(i,t,s)},m);function m(t,e,n){this.service=t,this.serviceName=e,this.errors=n}var p=/\{\$([^}]+)}/g;function y(t){return t&&t._delegate?t._delegate:t}var w,v=(b.prototype.setInstantiationMode=function(t){return this.instantiationMode=t,this},b.prototype.setMultipleInstances=function(t){return this.multipleInstances=t,this},b.prototype.setServiceProps=function(t){return this.serviceProps=t,this},b.prototype.setInstanceCreatedCallback=function(t){return this.onInstanceCreated=t,this},b);function b(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}(C=w=w||{})[C.DEBUG=0]="DEBUG",C[C.VERBOSE=1]="VERBOSE",C[C.INFO=2]="INFO",C[C.WARN=3]="WARN",C[C.ERROR=4]="ERROR",C[C.SILENT=5]="SILENT";function T(t,e){for(var n=[],r=2;r=t.length?void 0:t)&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}var C,x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},k={},R=x||self;function L(){}function O(t){var e=typeof t;return"array"==(e="object"!=e?e:t?Array.isArray(t)?"array":e:"null")||"object"==e&&"number"==typeof t.length}function M(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var P="closure_uid_"+(1e9*Math.random()>>>0),F=0;function V(t,e,n){return t.call.apply(t.bind,arguments)}function U(e,n,t){if(!e)throw Error();if(2parseFloat(gt)){ot=String(mt);break t}}ot=gt}var pt={};function yt(){return t=function(){for(var t=0,e=J(String(ot)).split("."),n=J("9").split("."),r=Math.max(e.length,n.length),s=0;0==t&&s>>0);function Ut(e){return"function"==typeof e?e:(e[Vt]||(e[Vt]=function(t){return e.handleEvent(t)}),e[Vt])}function qt(){K.call(this),this.i=new At(this),(this.P=this).I=null}function Bt(t,e){var n,r=t.I;if(r)for(n=[];r;r=r.I)n.push(r);if(t=t.P,r=e.type||e,"string"==typeof e?e=new bt(e,t):e instanceof bt?e.target=e.target||t:(o=e,st(e=new bt(r,t),o)),o=!0,n)for(var s=n.length-1;0<=s;s--)var i=e.g=n[s],o=jt(i,r,!0,e)&&o;if(o=jt(i=e.g=t,r,!0,e)&&o,o=jt(i,r,!1,e)&&o,n)for(s=0;si.length?Oe:(i=i.substr(a,o),s.C=a+o,i)))==Oe){4==e&&(t.o=4,ve(14),h=!1),de(t.j,t.m,null,"[Incomplete Response]");break}if(r==Le){t.o=4,ve(15),de(t.j,t.m,n,"[Invalid Chunk]"),h=!1;break}de(t.j,t.m,r,null),$e(t,r)}Fe(t)&&r!=Oe&&r!=Le&&(t.h.g="",t.C=0),4!=e||0!=n.length||t.h.h||(t.o=1,ve(16),h=!1),t.i=t.i&&h,h?0>4&15).toString(16)+(15&t).toString(16)}Ye.prototype.toString=function(){var t=[],e=this.j;e&&t.push(on(e,hn,!0),":");var n=this.i;return!n&&"file"!=e||(t.push("//"),(e=this.s)&&t.push(on(e,hn,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&t.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&t.push("/"),t.push(on(n,"/"==n.charAt(0)?cn:un,!0))),(n=this.h.toString())&&t.push("?",n),(n=this.o)&&t.push("#",on(n,dn)),t.join("")};var hn=/[#\/\?@]/g,un=/[#\?:]/g,cn=/[#\?]/g,ln=/[#\?@]/g,dn=/#/g;function fn(t,e){this.h=this.g=null,this.i=t||null,this.j=!!e}function gn(n){n.g||(n.g=new ze,n.h=0,n.i&&function(t,e){if(t){t=t.split("&");for(var n=0;n2*t.i&&He(t)))}function pn(t,e){return gn(t),e=wn(t,e),Qe(t.g.h,e)}function yn(t,e,n){mn(t,e),0=t.j}function _n(t){return t.h?1:t.g?t.g.size:0}function Sn(t,e){return t.h?t.h==e:t.g&&t.g.has(e)}function Nn(t,e){t.g?t.g.add(e):t.h=e}function An(t,e){t.h&&t.h==e?t.h=null:t.g&&t.g.has(e)&&t.g.delete(e)}function Dn(t){var e,n;if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Q(t.i);var r=t.i;try{for(var s=D(t.g.values()),i=s.next();!i.done;i=s.next())var o=i.value,r=r.concat(o.D)}catch(t){e={error:t}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(e)throw e.error}}return r}function Cn(){}function xn(){this.g=new Cn}function kn(t,e,n,r,s){try{e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,s(r)}catch(t){}}function Rn(t){this.l=t.$b||null,this.j=t.ib||!1}function Ln(t,e){qt.call(this),this.D=t,this.u=e,this.m=void 0,this.readyState=On,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}bn.prototype.cancel=function(){var e,t;if(this.i=Dn(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){try{for(var n=D(this.g.values()),r=n.next();!r.done;r=n.next())r.value.cancel()}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}this.g.clear()}},Cn.prototype.stringify=function(t){return R.JSON.stringify(t,void 0)},Cn.prototype.parse=function(t){return R.JSON.parse(t,void 0)},j(Rn,Ie),Rn.prototype.g=function(){return new Ln(this.l,this.j)},Rn.prototype.i=(Tn={},function(){return Tn}),j(Ln,qt);var On=0;function Mn(t){t.j.read().then(t.Sa.bind(t)).catch(t.ha.bind(t))}function Pn(t){t.readyState=4,t.l=null,t.j=null,t.A=null,Fn(t)}function Fn(t){t.onreadystatechange&&t.onreadystatechange.call(t)}(C=Ln.prototype).open=function(t,e){if(this.readyState!=On)throw this.abort(),Error("Error reopening a connection");this.C=t,this.B=e,this.readyState=1,Fn(this)},C.send=function(t){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;var e={headers:this.v,method:this.C,credentials:this.m,cache:void 0};t&&(e.body=t),(this.D||R).fetch(new Request(this.B,e)).then(this.Va.bind(this),this.ha.bind(this))},C.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Pn(this)),this.readyState=On},C.Va=function(t){if(this.g&&(this.l=t,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=t.headers,this.readyState=2,Fn(this)),this.g&&(this.readyState=3,Fn(this),this.g)))if("arraybuffer"===this.responseType)t.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==R.ReadableStream&&"body"in t){if(this.j=t.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;Mn(this)}else t.text().then(this.Ua.bind(this),this.ha.bind(this))},C.Sa=function(t){var e;this.g&&(this.u&&t.value?this.response.push(t.value):this.u||(e=t.value||new Uint8Array(0),(e=this.A.decode(e,{stream:!t.done}))&&(this.response=this.responseText+=e)),(t.done?Pn:Fn)(this),3==this.readyState&&Mn(this))},C.Ua=function(t){this.g&&(this.response=this.responseText=t,Pn(this))},C.Ta=function(t){this.g&&(this.response=t,Pn(this))},C.ha=function(){this.g&&Pn(this)},C.setRequestHeader=function(t,e){this.v.append(t,e)},C.getResponseHeader=function(t){return this.h&&this.h.get(t.toLowerCase())||""},C.getAllResponseHeaders=function(){if(!this.h)return"";for(var t=[],e=this.h.entries(),n=e.next();!n.done;)n=n.value,t.push(n[0]+": "+n[1]),n=e.next();return t.join("\r\n")},Object.defineProperty(Ln.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(t){this.m=t?"include":"same-origin"}});var Vn=R.JSON.parse;function Un(t){qt.call(this),this.headers=new ze,this.u=t||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=qn,this.K=this.L=!1}j(Un,qt);var qn="",Bn=/^https?$/i,jn=["POST","PUT"];function Kn(t){return"content-type"==t.toLowerCase()}function $n(t,e){t.h=!1,t.g&&(t.l=!0,t.g.abort(),t.l=!1),t.j=e,t.m=5,Gn(t),Hn(t)}function Gn(t){t.D||(t.D=!0,Bt(t,"complete"),Bt(t,"error"))}function zn(t){if(t.h&&void 0!==k&&(!t.C[1]||4!=Wn(t)||2!=t.ba()))if(t.v&&4==Wn(t))re(t.Fa,0,t);else if(Bt(t,"readystatechange"),4==Wn(t)){t.h=!1;try{var e,n,r,s,i=t.ba();t:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break t;default:o=!1}if((e=o)||((n=0===i)&&(!(s=String(t.H).match(We)[1]||null)&&R.self&&R.self.location&&(s=(r=R.self.location.protocol).substr(0,r.length-1)),n=!Bn.test(s?s.toLowerCase():"")),e=n),e)Bt(t,"complete"),Bt(t,"success");else{t.m=6;try{var a=2=r.i.j-(r.m?1:0)||(r.m?(r.l=s.D.concat(r.l),0):1==r.G||2==r.G||r.C>=(r.Xa?0:r.Ya)||(r.m=Te(q(r.Ha,r,s),gr(r,r.C)),r.C++,0))))&&(2!=o||!ur(t)))switch(i&&0`${this.name}: [code=${this.code}]: ${this.message}`}}class Hr{constructor(){this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}}class Qr{constructor(t,e){this.user=e,this.type="OAuth",this.authHeaders={},this.authHeaders.Authorization=`Bearer ${t}`}}class Wr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(t,e){t.enqueueRetryable(()=>e(Mr.UNAUTHENTICATED))}shutdown(){}}class Yr{constructor(t){this.token=t,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(t,e){this.changeListener=e,t.enqueueRetryable(()=>e(this.token.user))}shutdown(){this.changeListener=null}}class Jr{constructor(t){this.t=t,this.currentUser=Mr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,n){let r=this.i;const s=t=>this.i!==r?(r=this.i,n(t)):Promise.resolve();let i=new Hr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Hr,e.enqueueRetryable(()=>s(this.currentUser))};const o=t=>{e.enqueueRetryable(async()=>{Ur("FirebaseCredentialsProvider","Auth detected"),this.auth=t,this.auth.addAuthTokenListener(this.o),await i.promise,await s(this.currentUser)})};this.t.onInit(t=>o(t)),setTimeout(()=>{var t;this.auth||((t=this.t.getImmediate({optional:!0}))?o(t):(Ur("FirebaseCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Hr))},0),e.enqueueRetryable(async()=>{0===this.i&&(await i.promise,await s(this.currentUser))})}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(Ur("FirebaseCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?($r("string"==typeof t.accessToken),new Qr(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var t=this.auth&&this.auth.getUid();return $r(null===t||"string"==typeof t),new Mr(t)}}class Xr{constructor(t,e,n){this.h=t,this.l=e,this.m=n,this.type="FirstParty",this.user=Mr.FIRST_PARTY}get authHeaders(){const t={"X-Goog-AuthUser":this.l},e=this.h.auth.getAuthHeaderValueForFirstParty([]);return e&&(t.Authorization=e),this.m&&(t["X-Goog-Iam-Authorization-Token"]=this.m),t}}class Zr{constructor(t,e,n){this.h=t,this.l=e,this.m=n}getToken(){return Promise.resolve(new Xr(this.h,this.l,this.m))}start(t,e){t.enqueueRetryable(()=>e(Mr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class ts{constructor(t,e){this.previousValue=t,e&&(e.sequenceNumberHandler=t=>this.g(t),this.p=t=>e.writeSequenceNumber(t))}g(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){var t=++this.previousValue;return this.p&&this.p(t),t}}ts.T=-1;class es{static I(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/e.length)*e.length;let r="";for(;r.length<20;){var s=function(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;tr(t,n[e]))}function ss(t){return t+"\0"}class is{constructor(t,e){if(this.seconds=t,(this.nanoseconds=e)<0)throw new zr(Gr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(1e9<=e)throw new zr(Gr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new zr(Gr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(253402300800<=t)throw new zr(Gr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}static now(){return is.fromMillis(Date.now())}static fromDate(t){return is.fromMillis(t.getTime())}static fromMillis(t){var e=Math.floor(t/1e3),t=Math.floor(1e6*(t-1e3*e));return new is(e,t)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(t){return this.seconds===t.seconds?ns(this.nanoseconds,t.nanoseconds):ns(this.seconds,t.seconds)}isEqual(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var t=this.seconds- -62135596800;return String(t).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class os{constructor(t){this.timestamp=t}static fromTimestamp(t){return new os(t)}static min(){return new os(new is(0,0))}compareTo(t){return this.timestamp._compareTo(t.timestamp)}isEqual(t){return this.timestamp.isEqual(t.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function as(t){let e=0;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function hs(t,e){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])}function us(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}class cs{constructor(t,e,n){void 0===e?e=0:e>t.length&&Kr(),void 0===n?n=t.length-e:n>t.length-e&&Kr(),this.segments=t,this.offset=e,this.len=n}get length(){return this.len}isEqual(t){return 0===cs.comparator(this,t)}child(t){const e=this.segments.slice(this.offset,this.limit());return t instanceof cs?t.forEach(t=>{e.push(t)}):e.push(t),this.construct(e)}limit(){return this.offset+this.length}popFirst(t){return this.construct(this.segments,this.offset+(t=void 0===t?1:t),this.length-t)}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(t){return this.segments[this.offset+t]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.lengths)return 1}return e.lengthn.length?1:0}}class ls extends cs{construct(t,e,n){return new ls(t,e,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...t){const e=[];for(const n of t){if(0<=n.indexOf("//"))throw new zr(Gr.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);e.push(...n.split("/").filter(t=>0(t=t.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),t=!fs.isValidIdentifier(t)?"`"+t+"`":t)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new fs(["__name__"])}static fromServerFormat(t){const e=[];let n="",r=0;var s=()=>{if(0===n.length)throw new zr(Gr.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(n),n=""};let i=!1;for(;rt.isEqual(e))}}class ms{constructor(t){this.binaryString=t}static fromBase64String(t){t=atob(t);return new ms(t)}static fromUint8Array(t){t=function(e){let n="";for(let t=0;t=Number.MIN_SAFE_INTEGER}class Ss{constructor(t){this.path=t}static fromPath(t){return new Ss(ls.fromString(t))}static fromName(t){return new Ss(ls.fromString(t).popFirst(5))}hasCollectionId(t){return 2<=this.path.length&&this.path.get(this.path.length-2)===t}isEqual(t){return null!==t&&0===ls.comparator(this.path,t.path)}toString(){return this.path.toString()}static comparator(t,e){return ls.comparator(t.path,e.path)}static isDocumentKey(t){return t.length%2==0}static fromSegments(t){return new Ss(new ls(t.slice()))}}function Ns(t){return"nullValue"in t?0:"booleanValue"in t?1:"integerValue"in t||"doubleValue"in t?2:"timestampValue"in t?3:"stringValue"in t?5:"bytesValue"in t?6:"referenceValue"in t?7:"geoPointValue"in t?8:"arrayValue"in t?9:"mapValue"in t?bs(t)?4:10:Kr()}function As(n,r){var t,e,s=Ns(n);if(s!==Ns(r))return!1;switch(s){case 0:return!0;case 1:return n.booleanValue===r.booleanValue;case 4:return Ts(n).isEqual(Ts(r));case 3:return function(t){if("string"==typeof n.timestampValue&&"string"==typeof t.timestampValue&&n.timestampValue.length===t.timestampValue.length)return n.timestampValue===t.timestampValue;var e=ys(n.timestampValue),t=ys(t.timestampValue);return e.seconds===t.seconds&&e.nanos===t.nanos}(r);case 5:return n.stringValue===r.stringValue;case 6:return e=r,vs(n.bytesValue).isEqual(vs(e.bytesValue));case 7:return n.referenceValue===r.referenceValue;case 8:return t=r,ws((e=n).geoPointValue.latitude)===ws(t.geoPointValue.latitude)&&ws(e.geoPointValue.longitude)===ws(t.geoPointValue.longitude);case 2:return function(t,e){if("integerValue"in t&&"integerValue"in e)return ws(t.integerValue)===ws(e.integerValue);if("doubleValue"in t&&"doubleValue"in e){t=ws(t.doubleValue),e=ws(e.doubleValue);return t===e?Is(t)===Is(e):isNaN(t)&&isNaN(e)}return!1}(n,r);case 9:return rs(n.arrayValue.values||[],r.arrayValue.values||[],As);case 10:return function(t){const e=t.mapValue.fields||{},n=r.mapValue.fields||{};if(as(e)!==as(n))return!1;for(const t in e)if(e.hasOwnProperty(t)&&(void 0===n[t]||!As(e[t],n[t])))return!1;return!0}(n);default:return Kr()}}function Ds(t,e){return void 0!==(t.values||[]).find(t=>As(t,e))}function Cs(t,e){var n,r,s,i=Ns(t),o=Ns(e);if(i!==o)return ns(i,o);switch(i){case 0:return 0;case 1:return ns(t.booleanValue,e.booleanValue);case 2:return r=e,s=ws(t.integerValue||t.doubleValue),r=ws(r.integerValue||r.doubleValue),sn.mapValue.fields[t]=Vs(e)),n}if(e.arrayValue){const r={arrayValue:{values:[]}};for(let t=0;t<(e.arrayValue.values||[]).length;++t)r.arrayValue.values[t]=Vs(e.arrayValue.values[t]);return r}return Object.assign({},e)}class Us{constructor(t){this.value=t}static empty(){return new Us({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t{if(!n.isImmediateParentOf(e)){const t=this.getFieldsMap(n);this.applyChanges(t,r,s),r={},s=[],n=e.popLast()}t?r[e.lastSegment()]=Vs(t):s.push(e.lastSegment())});t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(t){const e=this.field(t.popLast());Fs(e)&&e.mapValue.fields&&delete e.mapValue.fields[t.lastSegment()]}isEqual(t){return As(this.value,t.value)}getFieldsMap(n){let r=this.value;r.mapValue.fields||(r.mapValue={fields:{}});for(let e=0;en[t]=e);for(const t of e)delete n[t]}clone(){return new Us(Vs(this.value))}}class qs{constructor(t,e,n,r,s){this.key=t,this.documentType=e,this.version=n,this.data=r,this.documentState=s}static newInvalidDocument(t){return new qs(t,0,os.min(),Us.empty(),0)}static newFoundDocument(t,e,n){return new qs(t,1,e,n,0)}static newNoDocument(t,e){return new qs(t,2,e,Us.empty(),0)}static newUnknownDocument(t,e){return new qs(t,3,e,Us.empty(),2)}convertToFoundDocument(t,e){return this.version=t,this.documentType=1,this.data=e,this.documentState=0,this}convertToNoDocument(t){return this.version=t,this.documentType=2,this.data=Us.empty(),this.documentState=0,this}convertToUnknownDocument(t){return this.version=t,this.documentType=3,this.data=Us.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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(t){return t instanceof qs&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}clone(){return new qs(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Bs{constructor(t,e=null,n=[],r=[],s=null,i=null,o=null){this.path=t,this.collectionGroup=e,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=o,this.A=null}}function js(t,e=null,n=[],r=[],s=null,i=null,o=null){return new Bs(t,e,n,r,s,i,o)}function Ks(t){const e=t;if(null===e.A){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(t=>function(t){return t.field.canonicalString()+t.op.toString()+ks(t.value)}(t)).join(","),t+="|ob:",t+=e.orderBy.map(t=>function(t){return t.field.canonicalString()+t.dir}(t)).join(","),Es(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=ni(e.startAt)),e.endAt&&(t+="|ub:",t+=ni(e.endAt)),e.A=t}return e.A}function $s(e,n){if(e.limit!==n.limit)return!1;if(e.orderBy.length!==n.orderBy.length)return!1;for(let t=0;t":return 0=":return 0<=t;default:return Kr()}}v(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class Hs extends zs{constructor(t,e,n){super(t,e,n),this.key=Ss.fromName(n.referenceValue)}matches(t){t=Ss.comparator(t.key,this.key);return this.P(t)}}class Qs extends zs{constructor(t,e){super(t,"in",e),this.keys=Ys(0,e)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class Ws extends zs{constructor(t,e){super(t,"not-in",e),this.keys=Ys(0,e)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function Ys(t,e){return((null===(e=e.arrayValue)||void 0===e?void 0:e.values)||[]).map(t=>Ss.fromName(t.referenceValue))}class Js extends zs{constructor(t,e){super(t,"array-contains",e)}matches(t){t=t.data.field(this.field);return Os(t)&&Ds(t.arrayValue,this.value)}}class Xs extends zs{constructor(t,e){super(t,"in",e)}matches(t){t=t.data.field(this.field);return null!==t&&Ds(this.value.arrayValue,t)}}class Zs extends zs{constructor(t,e){super(t,"not-in",e)}matches(t){if(Ds(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;t=t.data.field(this.field);return null!==t&&!Ds(this.value.arrayValue,t)}}class ti extends zs{constructor(t,e){super(t,"array-contains-any",e)}matches(t){const e=t.data.field(this.field);return!(!Os(e)||!e.arrayValue.values)&&e.arrayValue.values.some(t=>Ds(this.value.arrayValue,t))}}class ei{constructor(t,e){this.position=t,this.before=e}}function ni(t){return`${t.before?"b":"a"}:${t.position.map(t=>ks(t)).join(",")}`}class ri{constructor(t,e="asc"){this.field=t,this.dir=e}}function si(e,n,r){let s=0;for(let t=0;tfunction(t){return`${t.field.canonicalString()} (${t.dir})`}(t)).join(", ")}]`),t.startAt&&(e+=", startAt: "+ni(t.startAt)),t.endAt&&(e+=", endAt: "+ni(t.endAt)),`Target(${e})`}(mi(t))}; limitType=${t.limitType})`}function bi(n,t){return t.isFoundDocument()&&(e=n,r=t.key.path,null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(r):Ss.isDocumentKey(e.path)?e.path.isEqual(r):e.path.isImmediateParentOf(r))&&function(t){for(const e of n.explicitOrderBy)if(!e.field.isKeyField()&&null===t.data.field(e.field))return;return 1}(t)&&function(t){for(const e of n.filters)if(!e.matches(t))return;return 1}(t)&&(r=t,(!(t=n).startAt||si(t.startAt,gi(t),r))&&(!t.endAt||!si(t.endAt,gi(t),r)));var e,r}function Ti(s){return(t,e)=>{let n=!1;for(const r of gi(s)){const s=function(t,r,e){var n=t.field.isKeyField()?Ss.comparator(r.key,e.key):function(t,e){var n=r.data.field(t),t=e.data.field(t);return null!==n&&null!==t?Cs(n,t):Kr()}(t.field,e);switch(t.dir){case"asc":return n;case"desc":return-1*n;default:return Kr()}}(r,t,e);if(0!==s)return s;n=n||r.field.isKeyField()}return 0}}function Ei(t,e){if(t.D){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Is(e)?"-0":e}}function Ii(t){return{integerValue:""+t}}function _i(t,e){return _s(e)?Ii(e):Ei(t,e)}class Si{constructor(){this._=void 0}}function Ni(t,e){return t instanceof Ri?Ls(t=e)||t&&"doubleValue"in t?e:{integerValue:0}:null}class Ai extends Si{}class Di extends Si{constructor(t){super(),this.elements=t}}function Ci(t,e){const n=Oi(e);for(const e of t.elements)n.some(t=>As(t,e))||n.push(e);return{arrayValue:{values:n}}}class xi extends Si{constructor(t){super(),this.elements=t}}function ki(t,e){let n=Oi(e);for(const e of t.elements)n=n.filter(t=>!As(t,e));return{arrayValue:{values:n}}}class Ri extends Si{constructor(t,e){super(),this.N=t,this.C=e}}function Li(t){return ws(t.integerValue||t.doubleValue)}function Oi(t){return Os(t)&&t.arrayValue.values?t.arrayValue.values.slice():[]}class Mi{constructor(t,e){this.field=t,this.transform=e}}class Pi{constructor(t,e){this.version=t,this.transformResults=e}}class Fi{constructor(t,e){this.updateTime=t,this.exists=e}static none(){return new Fi}static exists(t){return new Fi(void 0,t)}static updateTime(t){return new Fi(t)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(t){return this.exists===t.exists&&(this.updateTime?!!t.updateTime&&this.updateTime.isEqual(t.updateTime):!t.updateTime)}}function Vi(t,e){return void 0!==t.updateTime?e.isFoundDocument()&&e.version.isEqual(t.updateTime):void 0===t.exists||t.exists===e.isFoundDocument()}class Ui{}function qi(t,e,n){t instanceof $i?function(t,e,n){const r=t.value.clone(),s=Hi(t.fieldTransforms,e,n.transformResults);r.setAll(s),e.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(t,e,n):t instanceof Gi?function(t,e,n){if(!Vi(t.precondition,e))return e.convertToUnknownDocument(n.version);const r=Hi(t.fieldTransforms,e,n.transformResults),s=e.data;s.setAll(zi(t)),s.setAll(r),e.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(t,e,n):e.convertToNoDocument(n.version).setHasCommittedMutations()}function Bi(t,e,n){t instanceof $i?function(t,e,n){if(Vi(t.precondition,e)){const r=t.value.clone(),s=Qi(t.fieldTransforms,n,e);r.setAll(s),e.convertToFoundDocument(Ki(e),r).setHasLocalMutations()}}(t,e,n):t instanceof Gi?function(t,e,n){if(Vi(t.precondition,e)){const r=Qi(t.fieldTransforms,n,e),s=e.data;s.setAll(zi(t)),s.setAll(r),e.convertToFoundDocument(Ki(e),s).setHasLocalMutations()}}(t,e,n):(e=e,Vi(t.precondition,e)&&e.convertToNoDocument(os.min()))}function ji(t,e){return t.type===e.type&&!!t.key.isEqual(e.key)&&!!t.precondition.isEqual(e.precondition)&&(n=t.fieldTransforms,r=e.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&rs(n,r,(t,e)=>function(t,e){return t.field.isEqual(e.field)&&(t=t.transform,e=e.transform,t instanceof Di&&e instanceof Di||t instanceof xi&&e instanceof xi?rs(t.elements,e.elements,As):t instanceof Ri&&e instanceof Ri?As(t.C,e.C):t instanceof Ai&&e instanceof Ai)}(t,e)))&&(0===t.type?t.value.isEqual(e.value):1!==t.type||t.data.isEqual(e.data)&&t.fieldMask.isEqual(e.fieldMask)));var n,r}function Ki(t){return t.isFoundDocument()?t.version:os.min()}class $i extends Ui{constructor(t,e,n,r=[]){super(),this.key=t,this.value=e,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Gi extends Ui{constructor(t,e,n,r,s=[]){super(),this.key=t,this.data=e,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}}function zi(n){const r=new Map;return n.fieldMask.fields.forEach(t=>{var e;t.isEmpty()||(e=n.data.field(t),r.set(t,e))}),r}function Hi(e,n,r){const s=new Map;$r(e.length===r.length);for(let t=0;t(n(t,e),!1))}toString(){const n=[];return this.inorderTraversal((t,e)=>(n.push(`${t}:${e}`),!1)),`{${n.join(", ")}}`}reverseTraversal(t){return this.root.reverseTraversal(t)}getIterator(){return new eo(this.root,null,this.comparator,!1)}getIteratorFrom(t){return new eo(this.root,t,this.comparator,!1)}getReverseIterator(){return new eo(this.root,null,this.comparator,!0)}getReverseIteratorFrom(t){return new eo(this.root,t,this.comparator,!0)}}class eo{constructor(t,e,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!t.isEmpty();)if(s=e?n(t.key,e):1,r&&(s*=-1),s<0)t=this.isReverse?t.left:t.right;else{if(0===s){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}getNext(){let t=this.nodeStack.pop();var e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e}hasNext(){return 0(n(t),!1))}forEachInRange(t,e){const n=this.data.getIteratorFrom(t[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,t[1]))return;e(r.key)}}forEachWhile(t,e){let n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return}firstAfterOrEqual(t){const e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null}getIterator(){return new so(this.data.getIterator())}getIteratorFrom(t){return new so(this.data.getIteratorFrom(t))}add(t){return this.copy(this.data.remove(t).insert(t,!0))}delete(t){return this.has(t)?this.copy(this.data.remove(t)):this}isEmpty(){return this.data.isEmpty()}unionWith(t){let e=this;return e.size{e=e.add(t)}),e}isEqual(t){if(!(t instanceof ro))return!1;if(this.size!==t.size)return!1;const e=this.data.getIterator(),n=t.data.getIterator();for(;e.hasNext();){const t=e.getNext().key,r=n.getNext().key;if(0!==this.comparator(t,r))return!1}return!0}toArray(){const e=[];return this.forEach(t=>{e.push(t)}),e}toString(){const e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(t){const e=new ro(this.comparator);return e.data=t,e}}class so{constructor(t){this.iter=t}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const io=new to(Ss.comparator);const oo=new to(Ss.comparator);const ao=new to(Ss.comparator);const ho=new ro(Ss.comparator);function uo(...t){let e=ho;for(const n of t)e=e.add(n);return e}const co=new ro(ns);class lo{constructor(t,e,n,r,s){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(t,e){const n=new Map;return n.set(t,fo.createSynthesizedTargetChangeForCurrentChange(t,e)),new lo(os.min(),n,co,io,uo())}}class fo{constructor(t,e,n,r,s){this.resumeToken=t,this.current=e,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(t,e){return new fo(ms.EMPTY_BYTE_STRING,e,uo(),uo(),uo())}}class go{constructor(t,e,n,r){this.k=t,this.removedTargetIds=e,this.key=n,this.$=r}}class mo{constructor(t,e){this.targetId=t,this.O=e}}class po{constructor(t,e,n=ms.EMPTY_BYTE_STRING,r=null){this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}}class yo{constructor(){this.F=0,this.M=bo(),this.L=ms.EMPTY_BYTE_STRING,this.B=!1,this.U=!0}get current(){return this.B}get resumeToken(){return this.L}get q(){return 0!==this.F}get K(){return this.U}j(t){0{switch(e){case 0:n=n.add(t);break;case 2:r=r.add(t);break;case 1:s=s.add(t);break;default:Kr()}}),new fo(this.L,this.B,n,r,s)}G(){this.U=!1,this.M=bo()}H(t,e){this.U=!0,this.M=this.M.insert(t,e)}J(t){this.U=!0,this.M=this.M.remove(t)}Y(){this.F+=1}X(){--this.F}Z(){this.U=!0,this.B=!0}}class wo{constructor(t){this.tt=t,this.et=new Map,this.nt=io,this.st=vo(),this.it=new ro(ns)}rt(t){for(const e of t.k)t.$&&t.$.isFoundDocument()?this.ot(e,t.$):this.at(e,t.key,t.$);for(const n of t.removedTargetIds)this.at(n,t.key,t.$)}ct(n){this.forEachTarget(n,t=>{const e=this.ut(t);switch(n.state){case 0:this.ht(t)&&e.j(n.resumeToken);break;case 1:e.X(),e.q||e.G(),e.j(n.resumeToken);break;case 2:e.X(),e.q||this.removeTarget(t);break;case 3:this.ht(t)&&(e.Z(),e.j(n.resumeToken));break;case 4:this.ht(t)&&(this.lt(t),e.j(n.resumeToken));break;default:Kr()}})}forEachTarget(t,n){0{this.ht(e)&&n(e)})}ft(t){const e=t.targetId,n=t.O.count,r=this.dt(e);if(r){const t=r.target;if(Gs(t))if(0===n){const n=new Ss(t.path);this.at(e,n,qs.newNoDocument(n,os.min()))}else $r(1===n);else this.wt(e)!==n&&(this.lt(e),this.it=this.it.add(e))}}_t(r){const s=new Map;this.et.forEach((t,e)=>{var n=this.dt(e);if(n){if(t.current&&Gs(n.target)){const s=new Ss(n.target.path);null!==this.nt.get(s)||this.gt(e,s)||this.at(e,s,qs.newNoDocument(s,r))}t.K&&(s.set(e,t.W()),t.G())}});let i=uo();this.st.forEach((t,e)=>{let n=!0;e.forEachWhile(t=>{t=this.dt(t);return!t||2===t.purpose||(n=!1)}),n&&(i=i.add(t))});var t=new lo(r,s,this.it,this.nt,i);return this.nt=io,this.st=vo(),this.it=new ro(ns),t}ot(t,e){var n;this.ht(t)&&(n=this.gt(t,e.key)?2:0,this.ut(t).H(e.key,n),this.nt=this.nt.insert(e.key,e),this.st=this.st.insert(e.key,this.yt(e.key).add(t)))}at(t,e,n){if(this.ht(t)){const r=this.ut(t);this.gt(t,e)?r.H(e,1):r.J(e),this.st=this.st.insert(e,this.yt(e).delete(t)),n&&(this.nt=this.nt.insert(e,n))}}removeTarget(t){this.et.delete(t)}wt(t){var e=this.ut(t).W();return this.tt.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size}Y(t){this.ut(t).Y()}ut(t){let e=this.et.get(t);return e||(e=new yo,this.et.set(t,e)),e}yt(t){let e=this.st.get(t);return e||(e=new ro(ns),this.st=this.st.insert(t,e)),e}ht(t){var e=null!==this.dt(t);return e||Ur("WatchChangeAggregator","Detected inactive target",t),e}dt(t){var e=this.et.get(t);return e&&e.q?null:this.tt.Et(t)}lt(e){this.et.set(e,new yo),this.tt.getRemoteKeysForTarget(e).forEach(t=>{this.at(e,t,null)})}gt(t,e){return this.tt.getRemoteKeysForTarget(t).has(e)}}function vo(){return new to(Ss.comparator)}function bo(){return new to(Ss.comparator)}const To={asc:"ASCENDING",desc:"DESCENDING"},Eo={"<":"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"};class Io{constructor(t,e){this.databaseId=t,this.D=e}}function _o(t,e){return t.D?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function So(t,e){return t.D?e.toBase64():e.toUint8Array()}function No(t){return $r(!!t),os.fromTimestamp((t=ys(t),new is(t.seconds,t.nanos)))}function Ao(t,e){return t=t,new ls(["projects",t.projectId,"databases",t.database]).child("documents").child(e).canonicalString()}function Do(t){t=ls.fromString(t);return $r(Qo(t)),t}function Co(t,e){return Ao(t.databaseId,e.path)}function xo(t,e){const n=Do(e);if(n.get(1)!==t.databaseId.projectId)throw new zr(Gr.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+t.databaseId.projectId);if(n.get(3)!==t.databaseId.database)throw new zr(Gr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+t.databaseId.database);return new Ss(Oo(n))}function ko(t,e){return Ao(t.databaseId,e)}function Ro(t){t=Do(t);return 4===t.length?ls.emptyPath():Oo(t)}function Lo(t){return new ls(["projects",t.databaseId.projectId,"databases",t.databaseId.database]).canonicalString()}function Oo(t){return $r(4e.push(t.canonicalString())),{fieldPaths:e}}(e.fieldMask)};else{if(!(e instanceof Yi))return Kr();n={verify:Co(t,e.key)}}return 0function(t){var e=t.transform;if(e instanceof Ai)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(e instanceof Di)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:e.elements}};if(e instanceof xi)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:e.elements}};if(e instanceof Ri)return{fieldPath:t.field.canonicalString(),increment:e.C};throw Kr()}(t))),e.precondition.isNone||(n.currentDocument=void 0!==(e=e.precondition).updateTime?{updateTime:_o(t,e.updateTime.toTimestamp())}:void 0!==e.exists?{exists:e.exists}:Kr()),n}function Vo(e,n){const t=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?Fi.updateTime(No(i.updateTime)):void 0!==i.exists?Fi.exists(i.exists):Fi.none():Fi.none(),r=n.updateTransforms?n.updateTransforms.map(t=>function(t,e){let n=null;if("setToServerValue"in e)$r("REQUEST_TIME"===e.setToServerValue),n=new Ai;else if("appendMissingElements"in e){const t=e.appendMissingElements.values||[];n=new Di(t)}else if("removeAllFromArray"in e){const t=e.removeAllFromArray.values||[];n=new xi(t)}else"increment"in e?n=new Ri(t,e.increment):Kr();e=fs.fromServerFormat(e.fieldPath);return new Mi(e,n)}(e,t)):[];if(n.update){n.update.name;var s=xo(e,n.update.name),i=new Us({mapValue:{fields:n.update.fields}});if(n.updateMask){const e=function(){const t=n.updateMask.fieldPaths||[];return new gs(t.map(t=>fs.fromServerFormat(t)))}();return new Gi(s,i,e,t,r)}return new $i(s,i,t,r)}if(n.delete){const r=xo(e,n.delete);return new Wi(r,t)}if(n.verify){const r=xo(e,n.verify);return new Yi(r,t)}return Kr()}function Uo(t,e){return{documents:[ko(t,e.path)]}}function qo(t,e){const n={structuredQuery:{}},r=e.path;null!==e.collectionGroup?(n.parent=ko(t,r),n.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(n.parent=ko(t,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var s=function(t){if(0!==t.length){t=t.map(t=>function(t){if("=="===t.op){if(Ps(t.value))return{unaryFilter:{field:$o(t.field),op:"IS_NAN"}};if(Ms(t.value))return{unaryFilter:{field:$o(t.field),op:"IS_NULL"}}}else if("!="===t.op){if(Ps(t.value))return{unaryFilter:{field:$o(t.field),op:"IS_NOT_NAN"}};if(Ms(t.value))return{unaryFilter:{field:$o(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:$o(t.field),op:(e=t.op,Eo[e]),value:t.value}};var e}(t));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(e.filters);s&&(n.structuredQuery.where=s);s=function(t){if(0!==t.length)return t.map(t=>function(t){return{field:$o(t.field),direction:(t=t.dir,To[t])}}(t))}(e.orderBy);s&&(n.structuredQuery.orderBy=s);s=e.limit,s=t.D||Es(s)?s:{value:s};return null!==s&&(n.structuredQuery.limit=s),e.startAt&&(n.structuredQuery.startAt=jo(e.startAt)),e.endAt&&(n.structuredQuery.endAt=jo(e.endAt)),n}function Bo(t){let e=Ro(t.parent);const n=t.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0e(t)).reduce((t,e)=>t.concat(e)):Kr():[]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(t=>function(t){return new ri(Go(t.field),function(){switch(t.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(t)));let a=null;n.limit&&(a=function(t){t="object"==typeof t?t.value:t;return Es(t)?null:t}(n.limit));let h=null;n.startAt&&(h=Ko(n.startAt));let u=null;return n.endAt&&(u=Ko(n.endAt)),ai(e,s,o,i,a,"F",h,u)}function jo(t){return{before:t.before,values:t.position}}function Ko(t){var e=!!t.before,t=t.values||[];return new ei(t,e)}function $o(t){return{fieldPath:t.canonicalString()}}function Go(t){return fs.fromServerFormat(t.fieldPath)}function zo(t){return zs.create(Go(t.fieldFilter.field),function(){switch(t.fieldFilter.op){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":default:return Kr()}}(),t.fieldFilter.value)}function Ho(t){switch(t.unaryFilter.op){case"IS_NAN":var e=Go(t.unaryFilter.field);return zs.create(e,"==",{doubleValue:NaN});case"IS_NULL":e=Go(t.unaryFilter.field);return zs.create(e,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=Go(t.unaryFilter.field);return zs.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=Go(t.unaryFilter.field);return zs.create(n,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":default:return Kr()}}function Qo(t){return 4<=t.length&&"projects"===t.get(0)&&"databases"===t.get(2)}function Wo(e){let n="";for(let t=0;ts)&&Kr(),n.charAt(r+1)){case"":const s=n.substring(e,r);let t;0===o.length?t=s:(o+=s,t=o,o=""),i.push(t);break;case"":o+=n.substring(e,r),o+="\0";break;case"":o+=n.substring(e,r+1);break;default:Kr()}e=r+2}return new ls(i)}class Xo{constructor(t,e){this.seconds=t,this.nanoseconds=e}}class Zo{constructor(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}}Zo.store="owner",Zo.key="owner";class ta{constructor(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}}ta.store="mutationQueues",ta.keyPath="userId";class ea{constructor(t,e,n,r,s){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=s}}ea.store="mutations",ea.keyPath="batchId",ea.userMutationsIndex="userMutationsIndex",ea.userMutationsKeyPath=["userId","batchId"];class na{constructor(){}static prefixForUser(t){return[t]}static prefixForPath(t,e){return[t,Wo(e)]}static key(t,e,n){return[t,Wo(e),n]}}na.store="documentMutations",na.PLACEHOLDER=new na;class ra{constructor(t,e){this.path=t,this.readTime=e}}class sa{constructor(t,e){this.path=t,this.version=e}}class ia{constructor(t,e,n,r,s,i){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r,this.readTime=s,this.parentPath=i}}ia.store="remoteDocuments",ia.readTimeIndex="readTimeIndex",ia.readTimeIndexPath="readTime",ia.collectionReadTimeIndex="collectionReadTimeIndex",ia.collectionReadTimeIndexPath=["parentPath","readTime"];class oa{constructor(t){this.byteSize=t}}oa.store="remoteDocumentGlobal",oa.key="remoteDocumentGlobalKey";class aa{constructor(t,e,n,r,s,i,o){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=s,this.lastLimboFreeSnapshotVersion=i,this.query=o}}aa.store="targets",aa.keyPath="targetId",aa.queryTargetsIndexName="queryTargetsIndex",aa.queryTargetsKeyPath=["canonicalId","targetId"];class ha{constructor(t,e,n){this.targetId=t,this.path=e,this.sequenceNumber=n}}ha.store="targetDocuments",ha.keyPath=["targetId","path"],ha.documentTargetsIndex="documentTargetsIndex",ha.documentTargetsKeyPath=["path","targetId"];class ua{constructor(t,e,n,r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r}}ua.key="targetGlobalKey",ua.store="targetGlobal";class ca{constructor(t,e){this.collectionId=t,this.parent=e}}ca.store="collectionParents",ca.keyPath=["collectionId","parent"];class la{constructor(t,e,n,r){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r}}la.store="clientMetadata",la.keyPath="clientId";class da{constructor(t,e,n){this.bundleId=t,this.createTime=e,this.version=n}}da.store="bundles",da.keyPath="bundleId";class fa{constructor(t,e,n){this.name=t,this.readTime=e,this.bundledQuery=n}}fa.store="namedQueries",fa.keyPath="name";const ga=[ta.store,ea.store,na.store,ia.store,aa.store,Zo.store,ua.store,ha.store,la.store,oa.store,ca.store,da.store,fa.store],ma="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class pa{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(t){this.onCommittedListeners.push(t)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(t=>t())}}class ya{constructor(t){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t(t=>{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)},t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)})}catch(t){return this.next(void 0,t)}next(r,s){return this.callbackAttached&&Kr(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(s,this.error):this.wrapSuccess(r,this.result):new ya((e,n)=>{this.nextCallback=t=>{this.wrapSuccess(r,t).next(e,n)},this.catchCallback=t=>{this.wrapFailure(s,t).next(e,n)}})}toPromise(){return new Promise((t,e)=>{this.next(t,e)})}wrapUserFunction(t){try{var e=t();return e instanceof ya?e:ya.resolve(e)}catch(t){return ya.reject(t)}}wrapSuccess(t,e){return t?this.wrapUserFunction(()=>t(e)):ya.resolve(e)}wrapFailure(t,e){return t?this.wrapUserFunction(()=>t(e)):ya.reject(e)}static resolve(n){return new ya((t,e)=>{t(n)})}static reject(n){return new ya((t,e)=>{e(n)})}static waitFor(t){return new ya((e,n)=>{let r=0,s=0,i=!1;t.forEach(t=>{++r,t.next(()=>{++s,i&&s===r&&e()},t=>n(t))}),i=!0,s===r&&e()})}static or(t){let e=ya.resolve(!1);for(const n of t)e=e.next(t=>t?ya.resolve(t):n());return e}static forEach(t,n){const r=[];return t.forEach((t,e)=>{r.push(n.call(this,t,e))}),this.waitFor(r)}}class wa{constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.Tt=new Hr,this.transaction.oncomplete=()=>{this.Tt.resolve()},this.transaction.onabort=()=>{t.error?this.Tt.reject(new Ta(e,t.error)):this.Tt.resolve()},this.transaction.onerror=t=>{t=Na(t.target.error);this.Tt.reject(new Ta(e,t))}}static open(t,e,n,r){try{return new wa(e,t.transaction(r,n))}catch(t){throw new Ta(e,t)}}get It(){return this.Tt.promise}abort(t){t&&this.Tt.reject(t),this.aborted||(Ur("SimpleDb","Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}store(t){t=this.transaction.objectStore(t);return new Ia(t)}}class va{constructor(t,e,n){this.name=t,this.version=e,this.At=n,12.2===va.Rt(d())&&qr("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(t){return Ur("SimpleDb","Removing database:",t),_a(window.indexedDB.deleteDatabase(t)).toPromise()}static Pt(){if("undefined"==typeof indexedDB)return!1;if(va.bt())return!0;const t=d(),e=va.Rt(t),n=0{const r=indexedDB.open(this.name,this.version);r.onsuccess=t=>{t=t.target.result;e(t)},r.onblocked=()=>{n(new Ta(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{t=t.target.error;"VersionError"===t.name?n(new zr(Gr.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.")):n(new Ta(s,t))},r.onupgradeneeded=t=>{Ur("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',t.oldVersion);var e=t.target.result;this.At.Ct(e,r.transaction,t.oldVersion,this.version).next(()=>{Ur("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Nt&&(this.db.onversionchange=t=>this.Nt(t)),this.db}xt(e){this.Nt=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(t,e,n,r){var s="readonly"===e;let i=0;for(;;){++i;try{this.db=await this.Dt(t);const e=wa.open(this.db,t,s?"readonly":"readwrite",n),i=r(e).catch(t=>(e.abort(t),ya.reject(t))).toPromise();return i.catch(()=>{}),await e.It,i}catch(t){const e="FirebaseError"!==t.name&&i<3;if(Ur("SimpleDb","Transaction failed with error:",t.message,"Retrying:",e),this.close(),!e)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class ba{constructor(t){this.kt=t,this.$t=!1,this.Ot=null}get isDone(){return this.$t}get Ft(){return this.Ot}set cursor(t){this.kt=t}done(){this.$t=!0}Mt(t){this.Ot=t}delete(){return _a(this.kt.delete())}}class Ta extends zr{constructor(t,e){super(Gr.UNAVAILABLE,`IndexedDB transaction '${t}' failed: ${e}`),this.name="IndexedDbTransactionError"}}function Ea(t){return"IndexedDbTransactionError"===t.name}class Ia{constructor(t){this.store=t}put(t,e){let n;return n=void 0!==e?(Ur("SimpleDb","PUT",this.store.name,t,e),this.store.put(e,t)):(Ur("SimpleDb","PUT",this.store.name,"",t),this.store.put(t)),_a(n)}add(t){return Ur("SimpleDb","ADD",this.store.name,t,t),_a(this.store.add(t))}get(e){return _a(this.store.get(e)).next(t=>(Ur("SimpleDb","GET",this.store.name,e,t=void 0===t?null:t),t))}delete(t){return Ur("SimpleDb","DELETE",this.store.name,t),_a(this.store.delete(t))}count(){return Ur("SimpleDb","COUNT",this.store.name),_a(this.store.count())}Lt(t,e){const n=this.cursor(this.options(t,e)),r=[];return this.Bt(n,(t,e)=>{r.push(e)}).next(()=>r)}Ut(t,e){Ur("SimpleDb","DELETE ALL",this.store.name);const n=this.options(t,e);n.qt=!1;e=this.cursor(n);return this.Bt(e,(t,e,n)=>n.delete())}Kt(t,e){let n;e?n=t:(n={},e=t);t=this.cursor(n);return this.Bt(t,e)}jt(r){const t=this.cursor({});return new ya((n,e)=>{t.onerror=t=>{t=Na(t.target.error);e(t)},t.onsuccess=t=>{const e=t.target.result;e?r(e.primaryKey,e.value).next(t=>{t?e.continue():n()}):n()}})}Bt(t,i){const o=[];return new ya((s,e)=>{t.onerror=t=>{e(t.target.error)},t.onsuccess=t=>{const e=t.target.result;if(e){const n=new ba(e),r=i(e.primaryKey,e.value,n);if(r instanceof ya){const t=r.catch(t=>(n.done(),ya.reject(t)));o.push(t)}n.isDone?s():null===n.Ft?e.continue():e.continue(n.Ft)}else s()}}).next(()=>ya.waitFor(o))}options(t,e){let n;return void 0!==t&&("string"==typeof t?n=t:e=t),{index:n,range:e}}cursor(t){let e="next";if(t.reverse&&(e="prev"),t.index){const n=this.store.index(t.index);return t.qt?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)}}function _a(t){return new ya((e,n)=>{t.onsuccess=t=>{t=t.target.result;e(t)},t.onerror=t=>{t=Na(t.target.error);n(t)}})}let Sa=!1;function Na(t){const e=va.Rt(d());if(12.2<=e&&e<13){const e="An internal error was encountered in the Indexed Database server";if(0<=t.message.indexOf(e)){const t=new zr("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Sa||(Sa=!0,setTimeout(()=>{throw t},0)),t}}return t}class Aa extends pa{constructor(t,e){super(),this.Qt=t,this.currentSequenceNumber=e}}function Da(t,e){return va.St(t.Qt,e)}class Ca{constructor(t,e,n,r){this.batchId=t,this.localWriteTime=e,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let t=0;t{const e=r.get(t.key),n=e;this.applyToLocalView(n),e.isValidDocument()||n.convertToNoDocument(os.min())})}keys(){return this.mutations.reduce((t,e)=>t.add(e.key),uo())}isEqual(t){return this.batchId===t.batchId&&rs(this.mutations,t.mutations,(t,e)=>ji(t,e))&&rs(this.baseMutations,t.baseMutations,(t,e)=>ji(t,e))}}class xa{constructor(t,e,n,r){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.docVersions=r}static from(t,e,n){$r(t.mutations.length===n.length);let r=ao;var s=t.mutations;for(let t=0;tVo(e.Wt,t));for(let t=0;tVo(e.Wt,t)),t=is.fromMillis(n.localWriteTimeMs);return new Ca(n.batchId,t,r,s)}function qa(t){var e,n=Va(t.readTime),r=void 0!==t.lastLimboFreeSnapshotVersion?Va(t.lastLimboFreeSnapshotVersion):os.min();let s;return s=void 0!==t.query.documents?($r(1===(e=t.query).documents.length),mi(hi(Ro(e.documents[0])))):mi(Bo(t.query)),new ka(s,t.targetId,0,t.lastListenSequenceNumber,n,r,ms.fromBase64String(t.resumeToken))}function Ba(t,e){var n=Fa(e.snapshotVersion),r=Fa(e.lastLimboFreeSnapshotVersion),s=(Gs(e.target)?Uo:qo)(t.Wt,e.target),t=e.resumeToken.toBase64();return new aa(e.targetId,Ks(e.target),n,t,e.sequenceNumber,r,s)}function ja(t){var e=Bo({parent:t.parent,structuredQuery:t.structuredQuery});return"LAST"===t.limitType?pi(e,e.limit,"L"):e}class Ka{getBundleMetadata(t,e){return $a(t).get(e).next(t=>{if(t)return{id:(t=t).bundleId,createTime:Va(t.createTime),version:t.version}})}saveBundleMetadata(t,e){return $a(t).put({bundleId:(e=e).id,createTime:Fa(No(e.createTime)),version:e.version})}getNamedQuery(t,e){return Ga(t).get(e).next(t=>{if(t)return{name:(t=t).name,query:ja(t.bundledQuery),readTime:Va(t.readTime)}})}saveNamedQuery(t,e){return Ga(t).put({name:(e=e).name,readTime:Fa(No(e.readTime)),bundledQuery:e.bundledQuery})}}function $a(t){return Da(t,da.store)}function Ga(t){return Da(t,fa.store)}class za{constructor(){this.Gt=new Ha}addToCollectionParentIndex(t,e){return this.Gt.add(e),ya.resolve()}getCollectionParents(t,e){return ya.resolve(this.Gt.getEntries(e))}}class Ha{constructor(){this.index={}}add(t){const e=t.lastSegment(),n=t.popLast(),r=this.index[e]||new ro(ls.comparator),s=!r.has(n);return this.index[e]=r.add(n),s}has(t){const e=t.lastSegment(),n=t.popLast(),r=this.index[e];return r&&r.has(n)}getEntries(t){return(this.index[t]||new ro(ls.comparator)).toArray()}}class Qa{constructor(){this.zt=new Ha}addToCollectionParentIndex(t,e){if(this.zt.has(e))return ya.resolve();var n=e.lastSegment(),r=e.popLast();t.addOnCommittedListener(()=>{this.zt.add(e)});r={collectionId:n,parent:Wo(r)};return Wa(t).put(r)}getCollectionParents(t,n){const r=[],e=IDBKeyRange.bound([n,""],[ss(n),""],!1,!0);return Wa(t).Lt(e).next(t=>{for(const e of t){if(e.collectionId!==n)break;r.push(Jo(e.parent))}return r})}}function Wa(t){return Da(t,ca.store)}const Ya={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Ja{constructor(t,e,n){this.cacheSizeCollectionThreshold=t,this.percentileToCollect=e,this.maximumSequenceNumbersToCollect=n}static withCacheSize(t){return new Ja(t,Ja.DEFAULT_COLLECTION_PERCENTILE,Ja.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Xa(t,e,n){const r=t.store(ea.store),s=t.store(na.store),i=[],o=IDBKeyRange.only(n.batchId);let a=0;const h=r.Kt({range:o},(t,e,n)=>(a++,n.delete()));i.push(h.next(()=>{$r(1===a)}));const u=[];for(const t of n.mutations){const r=na.key(e,t.key.path,n.batchId);i.push(s.delete(r)),u.push(t.key)}return ya.waitFor(i).next(()=>u)}function Za(t){if(!t)return 0;let e;if(t.document)e=t.document;else if(t.unknownDocument)e=t.unknownDocument;else{if(!t.noDocument)throw Kr();e=t.noDocument}return JSON.stringify(e).length}Ja.DEFAULT_COLLECTION_PERCENTILE=10,Ja.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ja.DEFAULT=new Ja(41943040,Ja.DEFAULT_COLLECTION_PERCENTILE,Ja.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ja.DISABLED=new Ja(-1,0,0);class th{constructor(t,e,n,r){this.userId=t,this.N=e,this.Ht=n,this.referenceDelegate=r,this.Jt={}}static Yt(t,e,n,r){$r(""!==t.uid);t=t.isAuthenticated()?t.uid:"";return new th(t,e,n,r)}checkEmpty(t){let r=!0;var e=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return nh(t).Kt({index:ea.userMutationsIndex,range:e},(t,e,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(c,l,d,f){const g=rh(c),m=nh(c);return m.add({}).next(t=>{$r("number"==typeof t);const e=new Ca(t,l,d,f),n=(s=this.N,i=this.userId,o=e,a=o.baseMutations.map(t=>Fo(s.Wt,t)),h=o.mutations.map(t=>Fo(s.Wt,t)),new ea(i,o.batchId,o.localWriteTime.toMillis(),a,h)),r=[];var s,i,o,a,h;let u=new ro((t,e)=>ns(t.canonicalString(),e.canonicalString()));for(const c of f){const l=na.key(this.userId,c.key.path,t);u=u.add(c.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,na.PLACEHOLDER))}return u.forEach(t=>{r.push(this.Ht.addToCollectionParentIndex(c,t))}),c.addOnCommittedListener(()=>{this.Jt[t]=e.keys()}),ya.waitFor(r).next(()=>e)})}lookupMutationBatch(t,e){return nh(t).get(e).next(t=>t?($r(t.userId===this.userId),Ua(this.N,t)):null)}Xt(t,e){return this.Jt[e]?ya.resolve(this.Jt[e]):this.lookupMutationBatch(t,e).next(t=>{if(t){t=t.keys();return this.Jt[e]=t}return null})}getNextMutationBatchAfterBatchId(t,e){const r=e+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return nh(t).Kt({index:ea.userMutationsIndex,range:n},(t,e,n)=>{e.userId===this.userId&&($r(e.batchId>=r),s=Ua(this.N,e)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return nh(t).Kt({index:ea.userMutationsIndex,range:e,reverse:!0},(t,e,n)=>{r=e.batchId,n.done()}).next(()=>r)}getAllMutationBatches(t){var e=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return nh(t).Lt(ea.userMutationsIndex,e).next(t=>t.map(t=>Ua(this.N,t)))}getAllMutationBatchesAffectingDocumentKey(i,o){const t=na.prefixForPath(this.userId,o.path),e=IDBKeyRange.lowerBound(t),a=[];return rh(i).Kt({range:e},(t,e,n)=>{var[r,s,t]=t,s=Jo(s);if(r===this.userId&&o.path.isEqual(s))return nh(i).get(t).next(t=>{if(!t)throw Kr();$r(t.userId===this.userId),a.push(Ua(this.N,t))});n.done()}).next(()=>a)}getAllMutationBatchesAffectingDocumentKeys(e,t){let o=new ro(ns);const n=[];return t.forEach(i=>{var t=na.prefixForPath(this.userId,i.path),t=IDBKeyRange.lowerBound(t),t=rh(e).Kt({range:t},(t,e,n)=>{var[r,s,t]=t,s=Jo(s);r===this.userId&&i.path.isEqual(s)?o=o.add(t):n.done()});n.push(t)}),ya.waitFor(n).next(()=>this.Zt(e,o))}getAllMutationBatchesAffectingQuery(t,e){const i=e.path,o=i.length+1,n=na.prefixForPath(this.userId,i),r=IDBKeyRange.lowerBound(n);let a=new ro(ns);return rh(t).Kt({range:r},(t,e,n)=>{var[r,s,t]=t,s=Jo(s);r===this.userId&&i.isPrefixOf(s)?s.length===o&&(a=a.add(t)):n.done()}).next(()=>this.Zt(t,a))}Zt(e,t){const n=[],r=[];return t.forEach(t=>{r.push(nh(e).get(t).next(t=>{if(null===t)throw Kr();$r(t.userId===this.userId),n.push(Ua(this.N,t))}))}),ya.waitFor(r).next(()=>n)}removeMutationBatch(e,n){return Xa(e.Qt,this.userId,n).next(t=>(e.addOnCommittedListener(()=>{this.te(n.batchId)}),ya.forEach(t,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}te(t){delete this.Jt[t]}performConsistencyCheck(n){return this.checkEmpty(n).next(t=>{if(!t)return ya.resolve();const e=IDBKeyRange.lowerBound(na.prefixForUser(this.userId)),r=[];return rh(n).Kt({range:e},(t,e,n)=>{if(t[0]===this.userId){const e=Jo(t[1]);r.push(e)}else n.done()}).next(()=>{$r(0===r.length)})})}containsKey(t,e){return eh(t,this.userId,e)}ee(t){return sh(t).get(this.userId).next(t=>t||new ta(this.userId,-1,""))}}function eh(t,s,e){const n=na.prefixForPath(s,e.path),i=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return rh(t).Kt({range:r,qt:!0},(t,e,n)=>{var[r,t]=t;r===s&&t===i&&(o=!0),n.done()}).next(()=>o)}function nh(t){return Da(t,ea.store)}function rh(t){return Da(t,na.store)}function sh(t){return Da(t,ta.store)}class ih{constructor(t){this.ne=t}next(){return this.ne+=2,this.ne}static se(){return new ih(0)}static ie(){return new ih(-1)}}class oh{constructor(t,e){this.referenceDelegate=t,this.N=e}allocateTargetId(n){return this.re(n).next(t=>{const e=new ih(t.highestTargetId);return t.highestTargetId=e.next(),this.oe(n,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(t){return this.re(t).next(t=>os.fromTimestamp(new is(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(t){return this.re(t).next(t=>t.highestListenSequenceNumber)}setTargetsMetadata(e,n,r){return this.re(e).next(t=>(t.highestListenSequenceNumber=n,r&&(t.lastRemoteSnapshotVersion=r.toTimestamp()),n>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=n),this.oe(e,t)))}addTargetData(e,n){return this.ae(e,n).next(()=>this.re(e).next(t=>(t.targetCount+=1,this.ce(n,t),this.oe(e,t))))}updateTargetData(t,e){return this.ae(t,e)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>ah(e).delete(t.targetId)).next(()=>this.re(e)).next(t=>($r(0{e=qa(e);e.sequenceNumber<=r&&null===s.get(e.targetId)&&(i++,o.push(this.removeTargetData(n,e)))}).next(()=>ya.waitFor(o)).next(()=>i)}forEachTarget(t,n){return ah(t).Kt((t,e)=>{e=qa(e);n(e)})}re(t){return hh(t).get(ua.key).next(t=>($r(null!==t),t))}oe(t,e){return hh(t).put(ua.key,e)}ae(t,e){return ah(t).put(Ba(this.N,e))}ce(t,e){let n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n}getTargetCount(t){return this.re(t).next(t=>t.targetCount)}getTargetData(t,r){var e=Ks(r),e=IDBKeyRange.bound([e,Number.NEGATIVE_INFINITY],[e,Number.POSITIVE_INFINITY]);let s=null;return ah(t).Kt({range:e,index:aa.queryTargetsIndexName},(t,e,n)=>{e=qa(e);$s(r,e.target)&&(s=e,n.done())}).next(()=>s)}addMatchingKeys(n,t,r){const s=[],i=uh(n);return t.forEach(t=>{var e=Wo(t.path);s.push(i.put(new ha(r,e))),s.push(this.referenceDelegate.addReference(n,r,t))}),ya.waitFor(s)}removeMatchingKeys(n,t,r){const s=uh(n);return ya.forEach(t,t=>{var e=Wo(t.path);return ya.waitFor([s.delete([r,e]),this.referenceDelegate.removeReference(n,r,t)])})}removeMatchingKeysForTargetId(t,e){const n=uh(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(t,e){const n=IDBKeyRange.bound([e],[e+1],!1,!0),r=uh(t);let s=uo();return r.Kt({range:n,qt:!0},(t,e,n)=>{t=Jo(t[1]),t=new Ss(t);s=s.add(t)}).next(()=>s)}containsKey(t,e){e=Wo(e.path),e=IDBKeyRange.bound([e],[ss(e)],!1,!0);let r=0;return uh(t).Kt({index:ha.documentTargetsIndex,qt:!0,range:e},([t],e,n)=>{0!==t&&(r++,n.done())}).next(()=>0t?qa(t):null)}}function ah(t){return Da(t,aa.store)}function hh(t){return Da(t,ua.store)}function uh(t){return Da(t,ha.store)}async function ch(t){if(t.code!==Gr.FAILED_PRECONDITION||t.message!==ma)throw t;Ur("LocalStore","Unexpectedly lost primary lease")}function lh([t,e],[n,r]){n=ns(t,n);return 0===n?ns(e,r):n}class dh{constructor(t){this.ue=t,this.buffer=new ro(lh),this.he=0}le(){return++this.he}fe(t){t=[t,this.le()];if(this.buffer.size{this.we=null,this.de=!0;try{await t.collectGarbage(this.garbageCollector)}catch(t){Ea(t)?Ur("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",t):await ch(t)}await this._e(t)})}}class gh{constructor(t,e){this.me=t,this.params=e}calculateTargetCount(t,e){return this.me.ge(t).next(t=>Math.floor(e/100*t))}nthSequenceNumber(t,e){if(0===e)return ya.resolve(ts.T);const n=new dh(e);return this.me.forEachTarget(t,t=>n.fe(t.sequenceNumber)).next(()=>this.me.ye(t,t=>n.fe(t))).next(()=>n.maxValue)}removeTargets(t,e,n){return this.me.removeTargets(t,e,n)}removeOrphanedDocuments(t,e){return this.me.removeOrphanedDocuments(t,e)}collect(e,n){return-1===this.params.cacheSizeCollectionThreshold?(Ur("LruGarbageCollector","Garbage collection skipped; disabled"),ya.resolve(Ya)):this.getCacheSize(e).next(t=>t(s=t>this.params.maximumSequenceNumbersToCollect?(Ur("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),this.params.maximumSequenceNumbersToCollect):t,o=Date.now(),this.nthSequenceNumber(e,s))).next(t=>(r=t,a=Date.now(),this.removeTargets(e,r,n))).next(t=>(i=t,h=Date.now(),this.removeOrphanedDocuments(e,r))).next(t=>(u=Date.now(),Vr()<=w.DEBUG&&Ur("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-c}ms\n\tDetermined least recently used ${s} in `+(a-o)+"ms\n"+`\tRemoved ${i} targets in `+(h-a)+"ms\n"+`\tRemoved ${t} documents in `+(u-h)+"ms\n"+`Total Duration: ${u-c}ms`),ya.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:t})))}}class mh{constructor(t,e){this.db=t,this.garbageCollector=(t=this,e=e,new gh(t,e))}ge(t){const n=this.Ee(t);return this.db.getTargetCache().getTargetCount(t).next(e=>n.next(t=>e+t))}Ee(t){let e=0;return this.ye(t,t=>{e++}).next(()=>e)}forEachTarget(t,e){return this.db.getTargetCache().forEachTarget(t,e)}ye(t,n){return this.Te(t,(t,e)=>n(e))}addReference(t,e,n){return ph(t,n)}removeReference(t,e,n){return ph(t,n)}removeTargets(t,e,n){return this.db.getTargetCache().removeTargets(t,e,n)}markPotentiallyOrphaned(t,e){return ph(t,e)}Ie(e,n){let r=!1;return sh(e).jt(t=>eh(e,t,n).next(t=>(t&&(r=!0),ya.resolve(!t)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let o=0;return this.Te(n,(e,t)=>{if(t<=r){const r=this.Ie(n,e).next(t=>{if(!t)return o++,s.getEntry(n,e).next(()=>(s.removeEntry(e),uh(n).delete([0,Wo(e.path)])))});i.push(r)}}).next(()=>ya.waitFor(i)).next(()=>s.apply(n)).next(()=>o)}removeTarget(t,e){e=e.withSequenceNumber(t.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(t,e)}updateLimboDocument(t,e){return ph(t,e)}Te(t,r){const e=uh(t);let s,i=ts.T;return e.Kt({index:ha.documentTargetsIndex},([t],{path:e,sequenceNumber:n})=>{0===t?(i!==ts.T&&r(new Ss(Jo(s)),i),i=n,s=e):i=ts.T}).next(()=>{i!==ts.T&&r(new Ss(Jo(s)),i)})}getCacheSize(t){return this.db.getRemoteDocumentCache().getSize(t)}}function ph(t,e){return uh(t).put((e=e,t=t.currentSequenceNumber,new ha(0,Wo(e.path),t)))}class yh{constructor(t,e){this.mapKeyFn=t,this.equalsFn=e,this.inner={}}get(t){const e=this.mapKeyFn(t),n=this.inner[e];if(void 0!==n)for(const[e,r]of n)if(this.equalsFn(e,t))return r}has(t){return void 0!==this.get(t)}set(e,n){const t=this.mapKeyFn(e),r=this.inner[t];if(void 0!==r){for(let t=0;t{for(const[t,n]of e)r(t,n)})}isEmpty(){return us(this.inner)}}class wh{constructor(){this.changes=new yh(t=>t.toString(),(t,e)=>t.isEqual(e)),this.changesApplied=!1}getReadTime(t){t=this.changes.get(t);return t?t.readTime:os.min()}addEntry(t,e){this.assertNotApplied(),this.changes.set(t.key,{document:t,readTime:e})}removeEntry(t,e=null){this.assertNotApplied(),this.changes.set(t,{document:qs.newInvalidDocument(t),readTime:e})}getEntry(t,e){this.assertNotApplied();var n=this.changes.get(e);return void 0!==n?ya.resolve(n.document):this.getFromCache(t,e)}getEntries(t,e){return this.getAllFromCache(t,e)}apply(t){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(t)}assertNotApplied(){}}class vh{constructor(t,e){this.N=t,this.Ht=e}addEntry(t,e,n){return Eh(t).put(Ih(e),n)}removeEntry(t,e){const n=Eh(t),r=Ih(e);return n.delete(r)}updateMetadata(e,n){return this.getMetadata(e).next(t=>(t.byteSize+=n,this.Ae(e,t)))}getEntry(t,e){return Eh(t).get(Ih(e)).next(t=>this.Re(e,t))}Pe(t,e){return Eh(t).get(Ih(e)).next(t=>({document:this.Re(e,t),size:Za(t)}))}getEntries(t,e){let n=io;return this.be(t,e,(t,e)=>{e=this.Re(t,e);n=n.insert(t,e)}).next(()=>n)}ve(t,e){let r=io,s=new to(Ss.comparator);return this.be(t,e,(t,e)=>{var n=this.Re(t,e);r=r.insert(t,n),s=s.insert(t,Za(e))}).next(()=>({documents:r,Ve:s}))}be(t,e,s){if(e.isEmpty())return ya.resolve();const n=IDBKeyRange.bound(e.first().path.toArray(),e.last().path.toArray()),i=e.getIterator();let o=i.getNext();return Eh(t).Kt({range:n},(t,e,n)=>{for(var r=Ss.fromSegments(t);o&&Ss.comparator(o,r)<0;)s(o,null),o=i.getNext();o&&o.isEqual(r)&&(s(o,e),o=i.hasNext()?i.getNext():null),o?n.Mt(o.path.toArray()):n.done()}).next(()=>{for(;o;)s(o,null),o=i.hasNext()?i.getNext():null})}getDocumentsMatchingQuery(t,r,e){let s=io;const i=r.path.length+1,n={};if(e.isEqual(os.min())){const t=r.path.toArray();n.range=IDBKeyRange.lowerBound(t)}else{const t=r.path.toArray(),s=Ma(e);n.range=IDBKeyRange.lowerBound([t,s],!0),n.index=ia.collectionReadTimeIndex}return Eh(t).Kt(n,(t,e,n)=>{t.length===i&&(e=La(this.N,e),r.path.isPrefixOf(e.key.path)?bi(r,e)&&(s=s.insert(e.key,e)):n.done())}).next(()=>s)}newChangeBuffer(t){return new bh(this,!!t&&t.trackRemovals)}getSize(t){return this.getMetadata(t).next(t=>t.byteSize)}getMetadata(t){return Th(t).get(oa.key).next(t=>($r(!!t),t))}Ae(t,e){return Th(t).put(oa.key,e)}Re(t,e){if(e){const t=La(this.N,e);if(!t.isNoDocument()||!t.version.isEqual(os.min()))return t}return qs.newInvalidDocument(t)}}class bh extends wh{constructor(t,e){super(),this.Se=t,this.trackRemovals=e,this.De=new yh(t=>t.toString(),(t,e)=>t.isEqual(e))}applyChanges(s){const i=[];let o=0,a=new ro((t,e)=>ns(t.canonicalString(),e.canonicalString()));return this.changes.forEach((t,e)=>{var n=this.De.get(t);if(e.document.isValidDocument()){var r=Oa(this.Se.N,e.document,this.getReadTime(t));a=a.add(t.path.popLast());e=Za(r);o+=e-n,i.push(this.Se.addEntry(s,t,r))}else if(o-=n,this.trackRemovals){const o=Oa(this.Se.N,qs.newNoDocument(t,os.min()),this.getReadTime(t));i.push(this.Se.addEntry(s,t,o))}else i.push(this.Se.removeEntry(s,t))}),a.forEach(t=>{i.push(this.Se.Ht.addToCollectionParentIndex(s,t))}),i.push(this.Se.updateMetadata(s,o)),ya.waitFor(i)}getFromCache(t,e){return this.Se.Pe(t,e).next(t=>(this.De.set(e,t.size),t.document))}getAllFromCache(t,e){return this.Se.ve(t,e).next(({documents:t,Ve:e})=>(e.forEach((t,e)=>{this.De.set(t,e)}),t))}}function Th(t){return Da(t,oa.store)}function Eh(t){return Da(t,ia.store)}function Ih(t){return t.path.toArray()}class _h{constructor(t){this.N=t}Ct(e,n,t,r){$r(tfunction(){const t=s.store(ua.store),e=new ua(0,0,os.min().toTimestamp(),0);return t.put(ua.key,e)}())),t<4&&4<=r&&(0!==t&&(o=o.next(()=>function(r,s){return s.store(ea.store).Lt().next(t=>{r.deleteObjectStore(ea.store),r.createObjectStore(ea.store,{keyPath:ea.keyPath,autoIncrement:!0}).createIndex(ea.userMutationsIndex,ea.userMutationsKeyPath,{unique:!0});const e=s.store(ea.store),n=t.map(t=>e.put(t));return ya.waitFor(n)})}(e,s))),o=o.next(()=>{e.createObjectStore(la.store,{keyPath:la.keyPath})})),t<5&&5<=r&&(o=o.next(()=>this.Ce(s))),t<6&&6<=r&&(o=o.next(()=>(e.createObjectStore(oa.store),this.Ne(s)))),t<7&&7<=r&&(o=o.next(()=>this.xe(s))),t<8&&8<=r&&(o=o.next(()=>this.ke(e,s))),t<9&&9<=r&&(o=o.next(()=>{var t;(t=e).objectStoreNames.contains("remoteDocumentChanges")&&t.deleteObjectStore("remoteDocumentChanges"),function(){const t=n.objectStore(ia.store);t.createIndex(ia.readTimeIndex,ia.readTimeIndexPath,{unique:!1}),t.createIndex(ia.collectionReadTimeIndex,ia.collectionReadTimeIndexPath,{unique:!1})}()})),t<10&&10<=r&&(o=o.next(()=>this.$e(s))),t<11&&11<=r&&(o=o.next(()=>{e.createObjectStore(da.store,{keyPath:da.keyPath}),e.createObjectStore(fa.store,{keyPath:fa.keyPath})})),o}Ne(e){let n=0;return e.store(ia.store).Kt((t,e)=>{n+=Za(e)}).next(()=>{var t=new oa(n);return e.store(oa.store).put(oa.key,t)})}Ce(n){const t=n.store(ta.store),r=n.store(ea.store);return t.Lt().next(t=>ya.forEach(t,e=>{var t=IDBKeyRange.bound([e.userId,-1],[e.userId,e.lastAcknowledgedBatchId]);return r.Lt(ea.userMutationsIndex,t).next(t=>ya.forEach(t,t=>{$r(t.userId===e.userId);t=Ua(this.N,t);return Xa(n,e.userId,t).next(()=>{})}))}))}xe(t){const o=t.store(ha.store),e=t.store(ia.store);return t.store(ua.store).get(ua.key).next(s=>{const i=[];return e.Kt((t,e)=>{const n=new ls(t),r=[0,Wo(n)];i.push(o.get(r).next(t=>t?ya.resolve():(t=>o.put(new ha(0,Wo(t),s.highestListenSequenceNumber)))(n)))}).next(()=>ya.waitFor(i))})}ke(t,e){t.createObjectStore(ca.store,{keyPath:ca.keyPath});const n=e.store(ca.store),r=new Ha,s=t=>{if(r.add(t)){const e=t.lastSegment(),r=t.popLast();return n.put({collectionId:e,parent:Wo(r)})}};return e.store(ia.store).Kt({qt:!0},(t,e)=>{const n=new ls(t);return s(n.popLast())}).next(()=>e.store(na.store).Kt({qt:!0},([,t],e)=>{const n=Jo(t);return s(n.popLast())}))}$e(t){const n=t.store(aa.store);return n.Kt((t,e)=>{e=qa(e),e=Ba(this.N,e);return n.put(e)})}}function Sh(t){t.createObjectStore(ha.store,{keyPath:ha.keyPath}).createIndex(ha.documentTargetsIndex,ha.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(aa.store,{keyPath:aa.keyPath}).createIndex(aa.queryTargetsIndexName,aa.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(ua.store)}const Nh="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class Ah{constructor(t,e,n,r,s,i,o,a,h,u){if(this.allowTabSynchronization=t,this.persistenceKey=e,this.clientId=n,this.Oe=s,this.window=i,this.document=o,this.Fe=h,this.Me=u,this.Le=null,this.Be=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ue=null,this.inForeground=!1,this.qe=null,this.Ke=null,this.je=Number.NEGATIVE_INFINITY,this.Qe=t=>Promise.resolve(),!Ah.Pt())throw new zr(Gr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new mh(this,r),this.We=e+"main",this.N=new Ra(a),this.Ge=new va(this.We,11,new _h(this.N)),this.ze=new oh(this.referenceDelegate,this.N),this.Ht=new Qa,this.He=(e=this.N,a=this.Ht,new vh(e,a)),this.Je=new Ka,this.window&&this.window.localStorage?this.Ye=this.window.localStorage:(this.Ye=null,!1===u&&qr("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.Xe().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new zr(Gr.FAILED_PRECONDITION,Nh);return this.Ze(),this.tn(),this.en(),this.runTransaction("getHighestListenSequenceNumber","readonly",t=>this.ze.getHighestSequenceNumber(t))}).then(t=>{this.Le=new ts(t,this.Fe)}).then(()=>{this.Be=!0}).catch(t=>(this.Ge&&this.Ge.close(),Promise.reject(t)))}nn(e){return this.Qe=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.Ge.xt(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(t){this.networkEnabled!==t&&(this.networkEnabled=t,this.Oe.enqueueAndForget(async()=>{this.started&&await this.Xe()}))}Xe(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>Ch(e).put(new la(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.sn(e).next(t=>{t||(this.isPrimary=!1,this.Oe.enqueueRetryable(()=>this.Qe(!1)))})}).next(()=>this.rn(e)).next(t=>this.isPrimary&&!t?this.on(e).next(()=>!1):!!t&&this.an(e).next(()=>!0))).catch(t=>{if(Ea(t))return Ur("IndexedDbPersistence","Failed to extend owner lease: ",t),this.isPrimary;if(!this.allowTabSynchronization)throw t;return Ur("IndexedDbPersistence","Releasing owner lease after error during lease refresh",t),!1}).then(t=>{this.isPrimary!==t&&this.Oe.enqueueRetryable(()=>this.Qe(t)),this.isPrimary=t})}sn(t){return Dh(t).get(Zo.key).next(t=>ya.resolve(this.cn(t)))}un(t){return Ch(t).delete(this.clientId)}async hn(){if(this.isPrimary&&!this.ln(this.je,18e5)){this.je=Date.now();var t=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",t=>{const r=Da(t,la.store);return r.Lt().next(t=>{const e=this.fn(t,18e5),n=t.filter(t=>-1===e.indexOf(t));return ya.forEach(n,t=>r.delete(t.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Ye)for(const e of t)this.Ye.removeItem(this.dn(e.clientId))}}en(){this.Ke=this.Oe.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Xe().then(()=>this.hn()).then(()=>this.en()))}cn(t){return!!t&&t.ownerId===this.clientId}rn(e){return this.Me?ya.resolve(!0):Dh(e).get(Zo.key).next(t=>{if(null!==t&&this.ln(t.leaseTimestampMs,5e3)&&!this.wn(t.ownerId)){if(this.cn(t)&&this.networkEnabled)return!0;if(!this.cn(t)){if(!t.allowTabSynchronization)throw new zr(Gr.FAILED_PRECONDITION,Nh);return!1}}return!(!this.networkEnabled||!this.inForeground)||Ch(e).Lt().next(t=>void 0===this.fn(t,5e3).find(t=>{if(this.clientId!==t.clientId){var e=!this.networkEnabled&&t.networkEnabled,n=!this.inForeground&&t.inForeground,t=this.networkEnabled===t.networkEnabled;if(e||n&&t)return!0}return!1}))}).next(t=>(this.isPrimary!==t&&Ur("IndexedDbPersistence",`Client ${t?"is":"is not"} eligible for a primary lease.`),t))}async shutdown(){this.Be=!1,this._n(),this.Ke&&(this.Ke.cancel(),this.Ke=null),this.mn(),this.gn(),await this.Ge.runTransaction("shutdown","readwrite",[Zo.store,la.store],t=>{const e=new Aa(t,ts.T);return this.on(e).next(()=>this.un(e))}),this.Ge.close(),this.yn()}fn(t,e){return t.filter(t=>this.ln(t.updateTimeMs,e)&&!this.wn(t.clientId))}pn(){return this.runTransaction("getActiveClients","readonly",t=>Ch(t).Lt().next(t=>this.fn(t,18e5).map(t=>t.clientId)))}get started(){return this.Be}getMutationQueue(t){return th.Yt(t,this.N,this.Ht,this.referenceDelegate)}getTargetCache(){return this.ze}getRemoteDocumentCache(){return this.He}getIndexManager(){return this.Ht}getBundleCache(){return this.Je}runTransaction(e,n,r){Ur("IndexedDbPersistence","Starting transaction:",e);let s;return this.Ge.runTransaction(e,"readonly"===n?"readonly":"readwrite",ga,t=>(s=new Aa(t,this.Le?this.Le.next():ts.T),"readwrite-primary"===n?this.sn(s).next(t=>!!t||this.rn(s)).next(t=>{if(!t)throw qr(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.Oe.enqueueRetryable(()=>this.Qe(!1)),new zr(Gr.FAILED_PRECONDITION,ma);return r(s)}).next(t=>this.an(s).next(()=>t)):this.En(s).next(()=>r(s)))).then(t=>(s.raiseOnCommittedEvent(),t))}En(t){return Dh(t).get(Zo.key).next(t=>{if(null!==t&&this.ln(t.leaseTimestampMs,5e3)&&!this.wn(t.ownerId)&&!this.cn(t)&&!(this.Me||this.allowTabSynchronization&&t.allowTabSynchronization))throw new zr(Gr.FAILED_PRECONDITION,Nh)})}an(t){var e=new Zo(this.clientId,this.allowTabSynchronization,Date.now());return Dh(t).put(Zo.key,e)}static Pt(){return va.Pt()}on(t){const e=Dh(t);return e.get(Zo.key).next(t=>this.cn(t)?(Ur("IndexedDbPersistence","Releasing primary lease."),e.delete(Zo.key)):ya.resolve())}ln(t,e){var n=Date.now();return!(t ${n}`),1))}Ze(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.qe=()=>{this.Oe.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Xe()))},this.document.addEventListener("visibilitychange",this.qe),this.inForeground="visible"===this.document.visibilityState)}mn(){this.qe&&(this.document.removeEventListener("visibilitychange",this.qe),this.qe=null)}tn(){var t;"function"==typeof(null===(t=this.window)||void 0===t?void 0:t.addEventListener)&&(this.Ue=()=>{this._n(),i()&&navigator.appVersion.match("Version/14")&&this.Oe.enterRestrictedMode(!0),this.Oe.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ue))}gn(){this.Ue&&(this.window.removeEventListener("pagehide",this.Ue),this.Ue=null)}wn(t){var e;try{var n=null!==(null===(e=this.Ye)||void 0===e?void 0:e.getItem(this.dn(t)));return Ur("IndexedDbPersistence",`Client '${t}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(t){return qr("IndexedDbPersistence","Failed to get zombied client id.",t),!1}}_n(){if(this.Ye)try{this.Ye.setItem(this.dn(this.clientId),String(Date.now()))}catch(t){qr("Failed to set zombie client id.",t)}}yn(){if(this.Ye)try{this.Ye.removeItem(this.dn(this.clientId))}catch(t){}}dn(t){return`firestore_zombie_${this.persistenceKey}_${t}`}}function Dh(t){return Da(t,Zo.store)}function Ch(t){return Da(t,la.store)}function xh(t,e){let n=t.projectId;return t.isDefaultDatabase||(n+="."+t.database),"firestore/"+e+"/"+n+"/"}class kh{constructor(t,e){this.progress=t,this.Tn=e}}class Rh{constructor(t,e,n){this.He=t,this.In=e,this.Ht=n}An(e,n){return this.In.getAllMutationBatchesAffectingDocumentKey(e,n).next(t=>this.Rn(e,n,t))}Rn(t,e,n){return this.He.getEntry(t,e).next(t=>{for(const e of n)e.applyToLocalView(t);return t})}Pn(t,n){t.forEach((t,e)=>{for(const t of n)t.applyToLocalView(e)})}bn(e,t){return this.He.getEntries(e,t).next(t=>this.vn(e,t).next(()=>t))}vn(t,e){return this.In.getAllMutationBatchesAffectingDocumentKeys(t,e).next(t=>this.Pn(e,t))}getDocumentsMatchingQuery(t,e,n){return r=e,Ss.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.Vn(t,e.path):fi(e)?this.Sn(t,e,n):this.Dn(t,e,n);var r}Vn(t,e){return this.An(t,new Ss(e)).next(t=>{let e=oo;return t.isFoundDocument()&&(e=e.insert(t.key,t)),e})}Sn(n,r,s){const i=r.collectionGroup;let o=oo;return this.Ht.getCollectionParents(n,i).next(t=>ya.forEach(t,t=>{var e,e=(e=r,t=t.child(i),new oi(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt));return this.Dn(n,e,s).next(t=>{t.forEach((t,e)=>{o=o.insert(t,e)})})}).next(()=>o))}Dn(e,n,t){let s,i;return this.He.getDocumentsMatchingQuery(e,n,t).next(t=>(s=t,this.In.getAllMutationBatchesAffectingQuery(e,n))).next(t=>(i=t,this.Cn(e,i,s).next(e=>{s=e;for(const e of i)for(const r of e.mutations){var n=r.key;let t=s.get(n);null==t&&(t=qs.newInvalidDocument(n),s=s.insert(n,t)),Bi(r,t,e.localWriteTime),t.isFoundDocument()||(s=s.remove(n))}}))).next(()=>(s.forEach((t,e)=>{bi(n,e)||(s=s.remove(t))}),s))}Cn(t,e,n){let r=uo();for(const t of e)for(const e of t.mutations)e instanceof Gi&&null===n.get(e.key)&&(r=r.add(e.key));let s=n;return this.He.getEntries(t,r).next(t=>(t.forEach((t,e)=>{e.isFoundDocument()&&(s=s.insert(t,e))}),s))}}class Lh{constructor(t,e,n,r){this.targetId=t,this.fromCache=e,this.Nn=n,this.xn=r}static kn(t,e){let n=uo(),r=uo();for(const t of e.docChanges)switch(t.type){case 0:n=n.add(t.doc.key);break;case 1:r=r.add(t.doc.key)}return new Lh(t,e.fromCache,n,r)}}class Oh{$n(t){this.On=t}getDocumentsMatchingQuery(e,r,s,i){return 0===r.filters.length&&null===r.limit&&null==r.startAt&&null==r.endAt&&(0===r.explicitOrderBy.length||1===r.explicitOrderBy.length&&r.explicitOrderBy[0].field.isKeyField())||s.isEqual(os.min())?this.Fn(e,r):this.On.bn(e,i).next(t=>{const n=this.Mn(r,t);return(ui(r)||ci(r))&&this.Ln(r.limitType,n,i,s)?this.Fn(e,r):(Vr()<=w.DEBUG&&Ur("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),vi(r)),this.On.getDocumentsMatchingQuery(e,r,s).next(e=>(n.forEach(t=>{e=e.insert(t.key,t)}),e)))})}Mn(n,t){let r=new ro(Ti(n));return t.forEach((t,e)=>{bi(n,e)&&(r=r.add(e))}),r}Ln(t,e,n,r){if(n.size!==e.size)return!0;const s="F"===t?e.last():e.first();return!!s&&(s.hasPendingWrites||0Ks(t),$s),this.Kn=os.min(),this.In=t.getMutationQueue(n),this.jn=t.getRemoteDocumentCache(),this.ze=t.getTargetCache(),this.Qn=new Rh(this.jn,this.In,this.persistence.getIndexManager()),this.Je=t.getBundleCache(),this.Bn.$n(this.Qn)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Un))}}function Ph(t,e,n,r){return new Mh(t,e,n,r)}async function Fh(t,e){const n=t;let r=n.In,o=n.Qn;t=await n.persistence.runTransaction("Handle user change","readonly",s=>{let i;return n.In.getAllMutationBatches(s).next(t=>(i=t,r=n.persistence.getMutationQueue(e),o=new Rh(n.jn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(s))).next(t=>{const e=[],n=[];let r=uo();for(const s of i){e.push(s.batchId);for(const t of s.mutations)r=r.add(t.key)}for(const s of t){n.push(s.batchId);for(const t of s.mutations)r=r.add(t.key)}return o.bn(s,r).next(t=>({Wn:t,removedBatchIds:e,addedBatchIds:n}))})});return n.In=r,n.Qn=o,n.Bn.$n(n.Qn),t}function Vh(t){const e=t;return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.ze.getLastRemoteSnapshotVersion(t))}function Uh(t,n){const c=t,l=n.snapshotVersion;let d=c.Un;return c.persistence.runTransaction("Apply remote event","readwrite-primary",h=>{const t=c.jn.newChangeBuffer({trackRemovals:!0});d=c.Un;const u=[];n.targetChanges.forEach((t,e)=>{const n=d.get(e);if(n){u.push(c.ze.removeMatchingKeys(h,t.removedDocuments,e).next(()=>c.ze.addMatchingKeys(h,t.addedDocuments,e)));const a=t.resumeToken;var r,s,i,o;0{n.resolvedLimboDocuments.has(t)&&u.push(c.persistence.referenceDelegate.updateLimboDocument(h,t))}),u.push(qh(h,t,n.documentUpdates,l,void 0).next(t=>{e=t})),!l.isEqual(os.min())){const n=c.ze.getLastRemoteSnapshotVersion(h).next(t=>c.ze.setTargetsMetadata(h,h.currentSequenceNumber,l));u.push(n)}return ya.waitFor(u).next(()=>t.apply(h)).next(()=>c.Qn.vn(h,e)).next(()=>e)}).then(t=>(c.Un=d,t))}function qh(t,o,e,a,h){let n=uo();return e.forEach(t=>n=n.add(t)),o.getEntries(t,n).next(s=>{let i=io;return e.forEach((t,e)=>{const n=s.get(t),r=(null==h?void 0:h.get(t))||a;e.isNoDocument()&&e.version.isEqual(os.min())?(o.removeEntry(t,r),i=i.insert(t,e)):!n.isValidDocument()||0{let n;return s.ze.getTargetData(e,r).next(t=>t?(n=t,ya.resolve(n)):s.ze.allocateTargetId(e).next(t=>(n=new ka(r,t,0,e.currentSequenceNumber),s.ze.addTargetData(e,n).next(()=>n))))}).then(t=>{var e=s.Un.get(t.targetId);return(null===e||0r.persistence.referenceDelegate.removeTarget(t,s))}catch(t){if(!Ea(t))throw t;Ur("LocalStore",`Failed to update sequence numbers for target ${e}: ${t}`)}r.Un=r.Un.remove(e),r.qn.delete(s.target)}function Kh(t,n,r){const s=t;let i=os.min(),o=uo();return s.persistence.runTransaction("Execute query","readonly",e=>function(t,e,n){const r=t,s=r.qn.get(n);return void 0!==s?ya.resolve(r.Un.get(s)):r.ze.getTargetData(e,n)}(s,e,mi(n)).next(t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,s.ze.getMatchingKeysForTargetId(e,t.targetId).next(t=>{o=t})}).next(()=>s.Bn.getDocumentsMatchingQuery(e,n,r?i:os.min(),r?o:uo())).next(t=>({documents:t,Gn:o})))}function $h(t,e){const n=t,r=n.ze,s=n.Un.get(e);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",t=>r.Et(t,e).next(t=>t?t.target:null))}function Gh(t){const n=t;return n.persistence.runTransaction("Get new document changes","readonly",t=>function(t,e,n){const r=t;let s=io,i=Ma(n);const o=Eh(e),a=IDBKeyRange.lowerBound(i,!0);return o.Kt({index:ia.readTimeIndex,range:a},(t,e)=>{var n=La(r.N,e);s=s.insert(n.key,n),i=e.readTime}).next(()=>({Tn:s,readTime:Pa(i)}))}(n.jn,t,n.Kn)).then(({Tn:t,readTime:e})=>(n.Kn=e,t))}class zh{constructor(t){this.N=t,this.Yn=new Map,this.Xn=new Map}getBundleMetadata(t,e){return ya.resolve(this.Yn.get(e))}saveBundleMetadata(t,e){return this.Yn.set(e.id,{id:e.id,version:e.version,createTime:No(e.createTime)}),ya.resolve()}getNamedQuery(t,e){return ya.resolve(this.Xn.get(e))}saveNamedQuery(t,e){return this.Xn.set(e.name,{name:(e=e).name,query:ja(e.bundledQuery),readTime:No(e.readTime)}),ya.resolve()}}class Hh{constructor(){this.Zn=new ro(Qh.ts),this.es=new ro(Qh.ns)}isEmpty(){return this.Zn.isEmpty()}addReference(t,e){e=new Qh(t,e);this.Zn=this.Zn.add(e),this.es=this.es.add(e)}ss(t,e){t.forEach(t=>this.addReference(t,e))}removeReference(t,e){this.rs(new Qh(t,e))}os(t,e){t.forEach(t=>this.removeReference(t,e))}cs(t){const e=new Ss(new ls([])),n=new Qh(e,t),r=new Qh(e,t+1),s=[];return this.es.forEachInRange([n,r],t=>{this.rs(t),s.push(t.key)}),s}us(){this.Zn.forEach(t=>this.rs(t))}rs(t){this.Zn=this.Zn.delete(t),this.es=this.es.delete(t)}hs(t){var e=new Ss(new ls([])),n=new Qh(e,t),t=new Qh(e,t+1);let r=uo();return this.es.forEachInRange([n,t],t=>{r=r.add(t.key)}),r}containsKey(t){var e=new Qh(t,0),e=this.Zn.firstAfterOrEqual(e);return null!==e&&t.isEqual(e.key)}}class Qh{constructor(t,e){this.key=t,this.ls=e}static ts(t,e){return Ss.comparator(t.key,e.key)||ns(t.ls,e.ls)}static ns(t,e){return ns(t.ls,e.ls)||Ss.comparator(t.key,e.key)}}class Wh{constructor(t,e){this.Ht=t,this.referenceDelegate=e,this.In=[],this.fs=1,this.ds=new ro(Qh.ts)}checkEmpty(t){return ya.resolve(0===this.In.length)}addMutationBatch(t,e,n,r){var s=this.fs;this.fs++,0e?this.In[e]:null)}getHighestUnacknowledgedBatchId(){return ya.resolve(0===this.In.length?-1:this.fs-1)}getAllMutationBatches(t){return ya.resolve(this.In.slice())}getAllMutationBatchesAffectingDocumentKey(t,e){const n=new Qh(e,0),r=new Qh(e,Number.POSITIVE_INFINITY),s=[];return this.ds.forEachInRange([n,r],t=>{t=this.ws(t.ls);s.push(t)}),ya.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(t,e){let n=new ro(ns);return e.forEach(t=>{var e=new Qh(t,0),t=new Qh(t,Number.POSITIVE_INFINITY);this.ds.forEachInRange([e,t],t=>{n=n.add(t.ls)})}),ya.resolve(this.gs(n))}getAllMutationBatchesAffectingQuery(t,e){const n=e.path,r=n.length+1;let s=n;Ss.isDocumentKey(s)||(s=s.child(""));e=new Qh(new Ss(s),0);let i=new ro(ns);return this.ds.forEachWhile(t=>{var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(i=i.add(t.ls)),!0)},e),ya.resolve(this.gs(i))}gs(t){const e=[];return t.forEach(t=>{t=this.ws(t);null!==t&&e.push(t)}),e}removeMutationBatch(n,r){$r(0===this.ys(r.batchId,"removed")),this.In.shift();let s=this.ds;return ya.forEach(r.mutations,t=>{var e=new Qh(t.key,r.batchId);return s=s.delete(e),this.referenceDelegate.markPotentiallyOrphaned(n,t.key)}).next(()=>{this.ds=s})}te(t){}containsKey(t,e){var n=new Qh(e,0),n=this.ds.firstAfterOrEqual(n);return ya.resolve(e.isEqual(n&&n.key))}performConsistencyCheck(t){return this.In.length,ya.resolve()}ys(t,e){return this._s(t)}_s(t){return 0===this.In.length?0:t-this.In[0].batchId}ws(t){t=this._s(t);return t<0||t>=this.In.length?null:this.In[t]}}class Yh{constructor(t,e){this.Ht=t,this.ps=e,this.docs=new to(Ss.comparator),this.size=0}addEntry(t,e,n){const r=e.key,s=this.docs.get(r),i=s?s.size:0,o=this.ps(e);return this.docs=this.docs.insert(r,{document:e.clone(),size:o,readTime:n}),this.size+=o-i,this.Ht.addToCollectionParentIndex(t,r.path.popLast())}removeEntry(t){var e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)}getEntry(t,e){const n=this.docs.get(e);return ya.resolve(n?n.document.clone():qs.newInvalidDocument(e))}getEntries(t,e){let n=io;return e.forEach(t=>{const e=this.docs.get(t);n=n.insert(t,e?e.document.clone():qs.newInvalidDocument(t))}),ya.resolve(n)}getDocumentsMatchingQuery(t,e,n){let r=io;const s=new Ss(e.path.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:t,value:{document:s,readTime:o}}=i.getNext();if(!e.path.isPrefixOf(t.path))break;o.compareTo(n)<=0||bi(e,s)&&(r=r.insert(s.key,s.clone()))}return ya.resolve(r)}Es(t,e){return ya.forEach(this.docs,t=>e(t))}newChangeBuffer(t){return new Jh(this)}getSize(t){return ya.resolve(this.size)}}class Jh extends wh{constructor(t){super(),this.Se=t}applyChanges(n){const r=[];return this.changes.forEach((t,e)=>{e.document.isValidDocument()?r.push(this.Se.addEntry(n,e.document,this.getReadTime(t))):this.Se.removeEntry(t)}),ya.waitFor(r)}getFromCache(t,e){return this.Se.getEntry(t,e)}getAllFromCache(t,e){return this.Se.getEntries(t,e)}}class Xh{constructor(t){this.persistence=t,this.Ts=new yh(t=>Ks(t),$s),this.lastRemoteSnapshotVersion=os.min(),this.highestTargetId=0,this.Is=0,this.As=new Hh,this.targetCount=0,this.Rs=ih.se()}forEachTarget(t,n){return this.Ts.forEach((t,e)=>n(e)),ya.resolve()}getLastRemoteSnapshotVersion(t){return ya.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(t){return ya.resolve(this.Is)}allocateTargetId(t){return this.highestTargetId=this.Rs.next(),ya.resolve(this.highestTargetId)}setTargetsMetadata(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.Is&&(this.Is=e),ya.resolve()}ae(t){this.Ts.set(t.target,t);var e=t.targetId;e>this.highestTargetId&&(this.Rs=new ih(e),this.highestTargetId=e),t.sequenceNumber>this.Is&&(this.Is=t.sequenceNumber)}addTargetData(t,e){return this.ae(e),this.targetCount+=1,ya.resolve()}updateTargetData(t,e){return this.ae(e),ya.resolve()}removeTargetData(t,e){return this.Ts.delete(e.target),this.As.cs(e.targetId),--this.targetCount,ya.resolve()}removeTargets(n,r,s){let i=0;const o=[];return this.Ts.forEach((t,e)=>{e.sequenceNumber<=r&&null===s.get(e.targetId)&&(this.Ts.delete(t),o.push(this.removeMatchingKeysForTargetId(n,e.targetId)),i++)}),ya.waitFor(o).next(()=>i)}getTargetCount(t){return ya.resolve(this.targetCount)}getTargetData(t,e){e=this.Ts.get(e)||null;return ya.resolve(e)}addMatchingKeys(t,e,n){return this.As.ss(e,n),ya.resolve()}removeMatchingKeys(e,t,n){this.As.os(t,n);const r=this.persistence.referenceDelegate,s=[];return r&&t.forEach(t=>{s.push(r.markPotentiallyOrphaned(e,t))}),ya.waitFor(s)}removeMatchingKeysForTargetId(t,e){return this.As.cs(e),ya.resolve()}getMatchingKeysForTargetId(t,e){e=this.As.hs(e);return ya.resolve(e)}containsKey(t,e){return ya.resolve(this.As.containsKey(e))}}class Zh{constructor(t,e){var n;this.Ps={},this.Le=new ts(0),this.Be=!1,this.Be=!0,this.referenceDelegate=t(this),this.ze=new Xh(this),this.Ht=new za,this.He=(n=this.Ht,t=t=>this.referenceDelegate.bs(t),new Yh(n,t)),this.N=new Ra(e),this.Je=new zh(this.N)}start(){return Promise.resolve()}shutdown(){return this.Be=!1,Promise.resolve()}get started(){return this.Be}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Ht}getMutationQueue(t){let e=this.Ps[t.toKey()];return e||(e=new Wh(this.Ht,this.referenceDelegate),this.Ps[t.toKey()]=e),e}getTargetCache(){return this.ze}getRemoteDocumentCache(){return this.He}getBundleCache(){return this.Je}runTransaction(t,e,n){Ur("MemoryPersistence","Starting transaction:",t);const r=new tu(this.Le.next());return this.referenceDelegate.vs(),n(r).next(t=>this.referenceDelegate.Vs(r).next(()=>t)).toPromise().then(t=>(r.raiseOnCommittedEvent(),t))}Ss(e,n){return ya.or(Object.values(this.Ps).map(t=>()=>t.containsKey(e,n)))}}class tu extends pa{constructor(t){super(),this.currentSequenceNumber=t}}class eu{constructor(t){this.persistence=t,this.Ds=new Hh,this.Cs=null}static Ns(t){return new eu(t)}get xs(){if(this.Cs)return this.Cs;throw Kr()}addReference(t,e,n){return this.Ds.addReference(n,e),this.xs.delete(n.toString()),ya.resolve()}removeReference(t,e,n){return this.Ds.removeReference(n,e),this.xs.add(n.toString()),ya.resolve()}markPotentiallyOrphaned(t,e){return this.xs.add(e.toString()),ya.resolve()}removeTarget(t,e){this.Ds.cs(e.targetId).forEach(t=>this.xs.add(t.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(t,e.targetId).next(t=>{t.forEach(t=>this.xs.add(t.toString()))}).next(()=>n.removeTargetData(t,e))}vs(){this.Cs=new Set}Vs(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ya.forEach(this.xs,t=>{const e=Ss.fromPath(t);return this.ks(n,e).next(t=>{t||r.removeEntry(e)})}).next(()=>(this.Cs=null,r.apply(n)))}updateLimboDocument(t,e){return this.ks(t,e).next(t=>{t?this.xs.delete(e.toString()):this.xs.add(e.toString())})}bs(t){return 0}ks(t,e){return ya.or([()=>ya.resolve(this.Ds.containsKey(e)),()=>this.persistence.getTargetCache().containsKey(t,e),()=>this.persistence.Ss(t,e)])}}function nu(t,e){return`firestore_clients_${t}_${e}`}function ru(t,e,n){let r=`firestore_mutations_${t}_${n}`;return e.isAuthenticated()&&(r+=`_${e.uid}`),r}function su(t,e){return`firestore_targets_${t}_${e}`}class iu{constructor(t,e,n,r){this.user=t,this.batchId=e,this.state=n,this.error=r}static $s(t,e,n){var r=JSON.parse(n);let s,i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code,i&&(s=new zr(r.error.code,r.error.message))),i?new iu(t,e,r.state,s):(qr("SharedClientState",`Failed to parse mutation state for ID '${e}': ${n}`),null)}Os(){const t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)}}class ou{constructor(t,e,n){this.targetId=t,this.state=e,this.error=n}static $s(t,e){var n=JSON.parse(e);let r,s="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code,s&&(r=new zr(n.error.code,n.error.message))),s?new ou(t,n.state,r):(qr("SharedClientState",`Failed to parse target state for ID '${t}': ${e}`),null)}Os(){const t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)}}class au{constructor(t,e){this.clientId=t,this.activeTargetIds=e}static $s(t,e){var n=JSON.parse(e);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=co;for(let t=0;r&&tthis.shutdown()),this.started=!0}writeSequenceNumber(t){this.setItem(this.Qs,JSON.stringify(t))}getAllActiveQueryTargets(){return this.ti(this.qs)}isActiveQueryTarget(n){let r=!1;return this.qs.forEach((t,e)=>{e.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(t){this.ei(t,"pending")}updateMutationState(t,e,n){this.ei(t,e,n),this.ni(t)}addLocalQueryTarget(t){let e="not-current";var n;return this.isActiveQueryTarget(t)&&(!(n=this.storage.getItem(su(this.persistenceKey,t)))||(n=ou.$s(t,n))&&(e=n.state)),this.si.Fs(t),this.Ys(),e}removeLocalQueryTarget(t){this.si.Ms(t),this.Ys()}isLocalQueryTarget(t){return this.si.activeTargetIds.has(t)}clearQueryState(t){this.removeItem(su(this.persistenceKey,t))}updateQueryState(t,e,n){this.ii(t,e,n)}handleUserChange(t,e,n){e.forEach(t=>{this.ni(t)}),this.currentUser=t,n.forEach(t=>{this.addPendingMutation(t)})}setOnlineState(t){this.ri(t)}notifyBundleLoaded(){this.oi()}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Bs),this.removeItem(this.js),this.started=!1)}getItem(t){var e=this.storage.getItem(t);return Ur("SharedClientState","READ",t,e),e}setItem(t,e){Ur("SharedClientState","SET",t,e),this.storage.setItem(t,e)}removeItem(t){Ur("SharedClientState","REMOVE",t),this.storage.removeItem(t)}Us(t){const r=t;r.storageArea===this.storage&&(Ur("SharedClientState","EVENT",r.key,r.newValue),r.key!==this.js?this.Oe.enqueueRetryable(async()=>{if(this.started){if(null!==r.key)if(this.Ws.test(r.key)){if(null==r.newValue){var t=this.ai(r.key);return this.ci(t,null)}t=this.ui(r.key,r.newValue);if(t)return this.ci(t.clientId,t)}else if(this.Gs.test(r.key)){if(null!==r.newValue){var e=this.hi(r.key,r.newValue);if(e)return this.li(e)}}else if(this.zs.test(r.key)){if(null!==r.newValue){e=this.fi(r.key,r.newValue);if(e)return this.di(e)}}else if(r.key===this.Hs){if(null!==r.newValue){var n=this.Xs(r.newValue);if(n)return this.Zs(n)}}else if(r.key===this.Qs){n=function(t){let e=ts.T;if(null!=t)try{var n=JSON.parse(t);$r("number"==typeof n),e=n}catch(t){qr("SharedClientState","Failed to read sequence number from WebStorage",t)}return e}(r.newValue);n!==ts.T&&this.sequenceNumberHandler(n)}else if(r.key===this.Js)return this.syncEngine.wi()}else this.Ks.push(r)}):qr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get si(){return this.qs.get(this.Ls)}Ys(){this.setItem(this.js,this.si.Os())}ei(t,e,n){const r=new iu(this.currentUser,t,e,n),s=ru(this.persistenceKey,this.currentUser,t);this.setItem(s,r.Os())}ni(t){t=ru(this.persistenceKey,this.currentUser,t);this.removeItem(t)}ri(t){t={clientId:this.Ls,onlineState:t};this.storage.setItem(this.Hs,JSON.stringify(t))}ii(t,e,n){const r=su(this.persistenceKey,t),s=new ou(t,e,n);this.setItem(r,s.Os())}oi(){this.setItem(this.Js,"value-not-used")}ai(t){t=this.Ws.exec(t);return t?t[1]:null}ui(t,e){t=this.ai(t);return au.$s(t,e)}hi(t,e){var n=this.Gs.exec(t),t=Number(n[1]),n=void 0!==n[2]?n[2]:null;return iu.$s(new Mr(n),t,e)}fi(t,e){t=this.zs.exec(t),t=Number(t[1]);return ou.$s(t,e)}Xs(t){return hu.$s(t)}async li(t){if(t.user.uid===this.currentUser.uid)return this.syncEngine._i(t.batchId,t.state,t.error);Ur("SharedClientState",`Ignoring mutation for non-active user ${t.user.uid}`)}di(t){return this.syncEngine.mi(t.targetId,t.state,t.error)}ci(t,e){const n=e?this.qs.insert(t,e):this.qs.remove(t),r=this.ti(this.qs),s=this.ti(n),i=[],o=[];return s.forEach(t=>{r.has(t)||i.push(t)}),r.forEach(t=>{s.has(t)||o.push(t)}),this.syncEngine.gi(i,o).then(()=>{this.qs=n})}Zs(t){this.qs.get(t.clientId)&&this.onlineStateHandler(t.onlineState)}ti(t){let n=co;return t.forEach((t,e)=>{n=n.unionWith(e.activeTargetIds)}),n}}class lu{constructor(){this.yi=new uu,this.pi={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(t){}updateMutationState(t,e,n){}addLocalQueryTarget(t){return this.yi.Fs(t),this.pi[t]||"not-current"}updateQueryState(t,e,n){this.pi[t]=e}removeLocalQueryTarget(t){this.yi.Ms(t)}isLocalQueryTarget(t){return this.yi.activeTargetIds.has(t)}clearQueryState(t){delete this.pi[t]}getAllActiveQueryTargets(){return this.yi.activeTargetIds}isActiveQueryTarget(t){return this.yi.activeTargetIds.has(t)}start(){return this.yi=new uu,Promise.resolve()}handleUserChange(t,e,n){}setOnlineState(t){}shutdown(){}writeSequenceNumber(t){}notifyBundleLoaded(){}}class du{Ei(t){}shutdown(){}}class fu{constructor(){this.Ti=()=>this.Ii(),this.Ai=()=>this.Ri(),this.Pi=[],this.bi()}Ei(t){this.Pi.push(t)}shutdown(){window.removeEventListener("online",this.Ti),window.removeEventListener("offline",this.Ai)}bi(){window.addEventListener("online",this.Ti),window.addEventListener("offline",this.Ai)}Ii(){Ur("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const t of this.Pi)t(0)}Ri(){Ur("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const t of this.Pi)t(1)}static Pt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const gu={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class mu{constructor(t){this.vi=t.vi,this.Vi=t.Vi}Si(t){this.Di=t}Ci(t){this.Ni=t}onMessage(t){this.xi=t}close(){this.Vi()}send(t){this.vi(t)}ki(){this.Di()}$i(t){this.Ni(t)}Oi(t){this.xi(t)}}class pu extends class{constructor(t){this.databaseInfo=t,this.databaseId=t.databaseId;var e=t.ssl?"https":"http";this.Fi=e+"://"+t.host,this.Mi="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Li(e,t,n,r){const s=this.Bi(e,t);Ur("RestConnection","Sending: ",s,n);t={};return this.Ui(t,r),this.qi(e,s,t,n).then(t=>(Ur("RestConnection","Received: ",t),t),t=>{throw Br("RestConnection",`${e} failed with error: `,t,"url: ",s,"request:",n),t})}Ki(t,e,n,r){return this.Li(t,e,n,r)}Ui(t,e){if(t["X-Goog-Api-Client"]="gl-js/ fire/"+Pr,t["Content-Type"]="text/plain",this.databaseInfo.appId&&(t["X-Firebase-GMPID"]=this.databaseInfo.appId),e)for(const n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n])}Bi(t,e){t=gu[t];return`${this.Fi}/v1/${e}:${t}`}}{constructor(t){super(t),this.forceLongPolling=t.forceLongPolling,this.autoDetectLongPolling=t.autoDetectLongPolling,this.useFetchStreams=t.useFetchStreams}qi(a,e,n,r){return new Promise((s,i)=>{const o=new Or;o.listenOnce(Dr.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case Ar.NO_ERROR:var t=o.getResponseJson();Ur("Connection","XHR received:",JSON.stringify(t)),s(t);break;case Ar.TIMEOUT:Ur("Connection",'RPC "'+a+'" timed out'),i(new zr(Gr.DEADLINE_EXCEEDED,"Request time out"));break;case Ar.HTTP_ERROR:var e,n=o.getStatus();if(Ur("Connection",'RPC "'+a+'" failed with status:',n,"response text:",o.getResponseText()),0{u?Ur("Connection","Not sending because WebChannel is closed:",t):(h||(Ur("Connection","Opening WebChannel transport."),a.open(),h=!0),Ur("Connection","WebChannel sending:",t),a.send(t))},Vi:()=>a.close()}),l=(t,e,n)=>{t.listen(e,t=>{try{n(t)}catch(t){setTimeout(()=>{throw t},0)}})};return l(a,Lr.EventType.OPEN,()=>{u||Ur("Connection","WebChannel transport opened.")}),l(a,Lr.EventType.CLOSE,()=>{u||(u=!0,Ur("Connection","WebChannel transport closed"),c.$i())}),l(a,Lr.EventType.ERROR,t=>{u||(u=!0,Br("Connection","WebChannel transport errored:",t),c.$i(new zr(Gr.UNAVAILABLE,"The operation could not be completed")))}),l(a,Lr.EventType.MESSAGE,t=>{if(!u){t=t.data[0];$r(!!t);var n=t.error||(null===(n=t[0])||void 0===n?void 0:n.error);if(n){Ur("Connection","WebChannel received error:",n);const r=n.status;let t=function(t){t=Sr[t];if(void 0!==t)return Zi(t)}(r),e=n.message;void 0===t&&(t=Gr.INTERNAL,e="Unknown error status: "+r+" with message "+n.message),u=!0,c.$i(new zr(t,e)),a.close()}else Ur("Connection","WebChannel received:",t),c.Oi(t)}}),l(s,Cr.STAT_EVENT,t=>{t.stat===xr?Ur("Connection","Detected buffering proxy"):t.stat===kr&&Ur("Connection","Detected no buffering proxy")}),setTimeout(()=>{c.ki()},0),c}}function yu(){return"undefined"!=typeof window?window:null}function wu(){return"undefined"!=typeof document?document:null}function vu(t){return new Io(t,!0)}class bu{constructor(t,e,n=1e3,r=1.5,s=6e4){this.Oe=t,this.timerId=e,this.Qi=n,this.Wi=r,this.Gi=s,this.zi=0,this.Hi=null,this.Ji=Date.now(),this.reset()}reset(){this.zi=0}Yi(){this.zi=this.Gi}Xi(t){this.cancel();var e=Math.floor(this.zi+this.Zi()),n=Math.max(0,Date.now()-this.Ji),r=Math.max(0,e-n);0(this.Ji=Date.now(),t())),this.zi*=this.Wi,this.zithis.Gi&&(this.zi=this.Gi)}tr(){null!==this.Hi&&(this.Hi.skipDelay(),this.Hi=null)}cancel(){null!==this.Hi&&(this.Hi.cancel(),this.Hi=null)}Zi(){return(Math.random()-.5)*this.zi}}class Tu{constructor(t,e,n,r,s,i){this.Oe=t,this.er=n,this.nr=r,this.credentialsProvider=s,this.listener=i,this.state=0,this.sr=0,this.ir=null,this.stream=null,this.rr=new bu(t,e)}ar(){return 1===this.state||2===this.state||4===this.state}cr(){return 2===this.state}start(){3!==this.state?this.auth():this.ur()}async stop(){this.ar()&&await this.close(0)}hr(){this.state=0,this.rr.reset()}lr(){this.cr()&&null===this.ir&&(this.ir=this.Oe.enqueueAfterDelay(this.er,6e4,()=>this.dr()))}wr(t){this._r(),this.stream.send(t)}async dr(){if(this.cr())return this.close(0)}_r(){this.ir&&(this.ir.cancel(),this.ir=null)}async close(t,e){this._r(),this.rr.cancel(),this.sr++,3!==t?this.rr.reset():e&&e.code===Gr.RESOURCE_EXHAUSTED?(qr(e.toString()),qr("Using maximum backoff delay to prevent overloading the backend."),this.rr.Yi()):e&&e.code===Gr.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.mr(),this.stream.close(),this.stream=null),this.state=t,await this.listener.Ci(e)}mr(){}auth(){this.state=1;const t=this.gr(this.sr),e=this.sr;this.credentialsProvider.getToken().then(t=>{this.sr===e&&this.yr(t)},e=>{t(()=>{var t=new zr(Gr.UNKNOWN,"Fetching auth token failed: "+e.message);return this.pr(t)})})}yr(t){const e=this.gr(this.sr);this.stream=this.Er(t),this.stream.Si(()=>{e(()=>(this.state=2,this.listener.Si()))}),this.stream.Ci(t=>{e(()=>this.pr(t))}),this.stream.onMessage(t=>{e(()=>this.onMessage(t))})}ur(){this.state=4,this.rr.Xi(async()=>{this.state=0,this.start()})}pr(t){return Ur("PersistentStream",`close with error: ${t}`),this.stream=null,this.close(3,t)}gr(e){return t=>{this.Oe.enqueueAndForget(()=>this.sr===e?t():(Ur("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class Eu extends Tu{constructor(t,e,n,r,s){super(t,"listen_stream_connection_backoff","listen_stream_idle",e,n,s),this.N=r}Er(t){return this.nr.ji("Listen",t)}onMessage(t){this.rr.reset();var e=function(t,e){let n;if("targetChange"in e){e.targetChange;var r="NO_CHANGE"===(i=e.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===i?1:"REMOVE"===i?2:"CURRENT"===i?3:"RESET"===i?4:Kr(),s=e.targetChange.targetIds||[],i=(o=e.targetChange.resumeToken,t.D?($r(void 0===o||"string"==typeof o),ms.fromBase64String(o||"")):($r(void 0===o||o instanceof Uint8Array),ms.fromUint8Array(o||new Uint8Array))),o=e.targetChange.cause,a=o&&(o=void 0===(a=o).code?Gr.UNKNOWN:Zi(a.code),new zr(o,a.message||""));n=new po(r,s,i,a||null)}else if("documentChange"in e){e.documentChange;var h=e.documentChange;h.document,h.document.name,h.document.updateTime;var i=xo(t,h.document.name),u=No(h.document.updateTime),a=new Us({mapValue:{fields:h.document.fields}}),u=qs.newFoundDocument(i,u,a),a=h.targetIds||[],h=h.removedTargetIds||[];n=new go(a,h,u.key,u)}else if("documentDelete"in e){e.documentDelete;h=e.documentDelete;h.document;var u=xo(t,h.document),c=h.readTime?No(h.readTime):os.min(),c=qs.newNoDocument(u,c),h=h.removedTargetIds||[];n=new go([],h,c.key,c)}else if("documentRemove"in e){e.documentRemove;c=e.documentRemove;c.document;var l=xo(t,c.document),c=c.removedTargetIds||[];n=new go([],c,l,null)}else{if(!("filter"in e))return Kr();{e.filter;const t=e.filter;t.targetId;l=t.count||0,e=new Ji(l),l=t.targetId;n=new mo(l,e)}}var a,i;return n}(this.N,t),t=function(t){if(!("targetChange"in t))return os.min();t=t.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?No(t.readTime):os.min()}(t);return this.listener.Tr(e,t)}Ir(t){const e={};e.database=Lo(this.N),e.addTarget=function(t,e){let n;var r=e.target;return n=Gs(r)?{documents:Uo(t,r)}:{query:qo(t,r)},n.targetId=e.targetId,0function(t,e){let n=t.updateTime?No(t.updateTime):No(e);return n.isEqual(os.min())&&(n=No(e)),new Pi(n,t.transformResults||[])}(t,r))):[]),n=No(t.commitTime);return this.listener.vr(n,e)}var n,r;return $r(!t.writeResults||0===t.writeResults.length),this.Rr=!0,this.listener.Vr()}Sr(){const t={};t.database=Lo(this.N),this.wr(t)}br(t){t={streamToken:this.lastStreamToken,writes:t.map(t=>Fo(this.N,t))};this.wr(t)}}class _u extends class{}{constructor(t,e,n){super(),this.credentials=t,this.nr=e,this.N=n,this.Dr=!1}Cr(){if(this.Dr)throw new zr(Gr.FAILED_PRECONDITION,"The client has already been terminated.")}Li(e,n,r){return this.Cr(),this.credentials.getToken().then(t=>this.nr.Li(e,n,r,t)).catch(t=>{throw"FirebaseError"===t.name?(t.code===Gr.UNAUTHENTICATED&&this.credentials.invalidateToken(),t):new zr(Gr.UNKNOWN,t.toString())})}Ki(e,n,r){return this.Cr(),this.credentials.getToken().then(t=>this.nr.Ki(e,n,r,t)).catch(t=>{throw"FirebaseError"===t.name?(t.code===Gr.UNAUTHENTICATED&&this.credentials.invalidateToken(),t):new zr(Gr.UNKNOWN,t.toString())})}terminate(){this.Dr=!0}}class Su{constructor(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state="Unknown",this.Nr=0,this.kr=null,this.$r=!0}Or(){0===this.Nr&&(this.Fr("Unknown"),this.kr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.kr=null,this.Mr("Backend didn't respond within 10 seconds."),this.Fr("Offline"),Promise.resolve())))}Lr(t){"Online"===this.state?this.Fr("Unknown"):(this.Nr++,1<=this.Nr&&(this.Br(),this.Mr(`Connection failed 1 times. Most recent error: ${t.toString()}`),this.Fr("Offline")))}set(t){this.Br(),this.Nr=0,"Online"===t&&(this.$r=!1),this.Fr(t)}Fr(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))}Mr(t){t=`Could not reach Cloud Firestore backend. ${t}\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.$r?(qr(t),this.$r=!1):Ur("OnlineStateTracker",t)}Br(){null!==this.kr&&(this.kr.cancel(),this.kr=null)}}class Nu{constructor(t,e,n,r,s){this.localStore=t,this.datastore=e,this.asyncQueue=n,this.remoteSyncer={},this.Ur=[],this.qr=new Map,this.Kr=new Set,this.jr=[],this.Qr=s,this.Qr.Ei(t=>{n.enqueueAndForget(async()=>{Mu(this)&&(Ur("RemoteStore","Restarting streams for network reachability change."),await async function(t){const e=t;e.Kr.add(4),await Du(e),e.Wr.set("Unknown"),e.Kr.delete(4),await Au(e)}(this))})}),this.Wr=new Su(n,r)}}async function Au(t){if(Mu(t))for(const e of t.jr)await e(!0)}async function Du(t){for(const e of t.jr)await e(!1)}function Cu(t,e){const n=t;n.qr.has(e.targetId)||(n.qr.set(e.targetId,e),Ou(n)?Lu(n):Ku(n).cr()&&ku(n,e))}function xu(t,e){const n=t,r=Ku(n);n.qr.delete(e),r.cr()&&Ru(n,e),0===n.qr.size&&(r.cr()?r.lr():Mu(n)&&n.Wr.set("Unknown"))}function ku(t,e){t.Gr.Y(e.targetId),Ku(t).Ir(e)}function Ru(t,e){t.Gr.Y(e),Ku(t).Ar(e)}function Lu(e){e.Gr=new wo({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Et:t=>e.qr.get(t)||null}),Ku(e).start(),e.Wr.Or()}function Ou(t){return Mu(t)&&!Ku(t).ar()&&0Vh(t.localStore)),t.asyncQueue.enqueueRetryable(async()=>{Ur("RemoteStore","Retrying IndexedDB access"),await n(),t.Kr.delete(1),await Au(t)})}function Vu(e,n){return n().catch(t=>Fu(e,t,n))}async function Uu(t){const e=t,n=$u(e);let r=0(void 0===e&&(e=-1),n.In.getNextMutationBatchAfterBatchId(t,e)))}(e.localStore,r);if(null===t){0===e.Ur.length&&n.lr();break}r=t.batchId,function(t,e){t.Ur.push(e);const n=$u(t);n.cr()&&n.Pr&&n.br(e.mutations)}(e,t)}catch(t){await Fu(e,t)}var s;qu(e)&&Bu(e)}function qu(t){return Mu(t)&&!$u(t).ar()&&0{ku(n,t)})}.bind(null,e),Ci:async function(t,e){Pu(t),Ou(t)?(t.Wr.Lr(e),Lu(t)):t.Wr.set("Unknown")}.bind(null,e),Tr:async function(t,r,e){if(t.Wr.set("Online"),r instanceof po&&2===r.state&&r.cause)try{await async function(t){var e=r.cause;for(const n of r.targetIds)t.qr.has(n)&&(await t.remoteSyncer.rejectListen(n,e),t.qr.delete(n),t.Gr.removeTarget(n))}(t)}catch(e){Ur("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),e),await Fu(t,e)}else if(r instanceof go?t.Gr.rt(r):r instanceof mo?t.Gr.ft(r):t.Gr.ct(r),!e.isEqual(os.min()))try{const r=await Vh(t.localStore);0<=e.compareTo(r)&&await function(r,s){const t=r.Gr._t(s);return t.targetChanges.forEach((t,e)=>{if(0{const e=r.qr.get(t);e&&(r.qr.set(t,e.withResumeToken(ms.EMPTY_BYTE_STRING,e.snapshotVersion)),Ru(r,t),t=new ka(e.target,t,1,e.sequenceNumber),ku(r,t))}),r.remoteSyncer.applyRemoteEvent(t)}(t,e)}catch(r){Ur("RemoteStore","Failed to raise snapshot:",r),await Fu(t,r)}}.bind(null,e)}),e.jr.push(async t=>{t?(e.zr.hr(),Ou(e)?Lu(e):e.Wr.set("Unknown")):(await e.zr.stop(),Pu(e))})),e.zr}function $u(e){return e.Hr||(e.Hr=function(t,e,n){const r=t;return r.Cr(),new Iu(e,r.nr,r.credentials,r.N,n)}(e.datastore,e.asyncQueue,{Si:async function(t){$u(t).Sr()}.bind(null,e),Ci:async function(t,e){e&&$u(t).Pr&&await async function(t,e){if(Xi(n=e.code)&&n!==Gr.ABORTED){const n=t.Ur.shift();$u(t).hr(),await Vu(t,()=>t.remoteSyncer.rejectFailedWrite(n.batchId,e)),await Uu(t)}var n}(t,e),qu(t)&&Bu(t)}.bind(null,e),Vr:async function(t){const e=$u(t);for(const n of t.Ur)e.br(n.mutations)}.bind(null,e),vr:async function(t,e,n){const r=t.Ur.shift(),s=xa.from(r,e,n);await Vu(t,()=>t.remoteSyncer.applySuccessfulWrite(s)),await Uu(t)}.bind(null,e)}),e.jr.push(async t=>{t?(e.Hr.hr(),await Uu(e)):(await e.Hr.stop(),0{})}static createAndSchedule(t,e,n,r,s){const i=Date.now()+n,o=new Gu(t,e,i,r,s);return o.start(n),o}start(t){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),t)}skipDelay(){return this.handleDelayElapsed()}cancel(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new zr(Gr.CANCELLED,"Operation cancelled"+(t?": "+t:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(t=>this.deferred.resolve(t))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function zu(t,e){if(qr("AsyncQueue",`${e}: ${t}`),Ea(t))return new zr(Gr.UNAVAILABLE,`${e}: ${t}`);throw t}class Hu{constructor(n){this.comparator=n?(t,e)=>n(t,e)||Ss.comparator(t.key,e.key):(t,e)=>Ss.comparator(t.key,e.key),this.keyedMap=oo,this.sortedSet=new to(this.comparator)}static emptySet(t){return new Hu(t.comparator)}has(t){return null!=this.keyedMap.get(t)}get(t){return this.keyedMap.get(t)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(t){t=this.keyedMap.get(t);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((t,e)=>(n(t),!1))}add(t){const e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))}delete(t){var e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this}isEqual(t){if(!(t instanceof Hu))return!1;if(this.size!==t.size)return!1;const e=this.sortedSet.getIterator(),n=t.sortedSet.getIterator();for(;e.hasNext();){const t=e.getNext().key,r=n.getNext().key;if(!t.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(t,e){const n=new Hu;return n.comparator=this.comparator,n.keyedMap=t,n.sortedSet=e,n}}class Qu{constructor(){this.Jr=new to(Ss.comparator)}track(t){var e=t.doc.key,n=this.Jr.get(e);!n||0!==t.type&&3===n.type?this.Jr=this.Jr.insert(e,t):3===t.type&&1!==n.type?this.Jr=this.Jr.insert(e,{type:n.type,doc:t.doc}):2===t.type&&2===n.type?this.Jr=this.Jr.insert(e,{type:2,doc:t.doc}):2===t.type&&0===n.type?this.Jr=this.Jr.insert(e,{type:0,doc:t.doc}):1===t.type&&0===n.type?this.Jr=this.Jr.remove(e):1===t.type&&2===n.type?this.Jr=this.Jr.insert(e,{type:1,doc:n.doc}):0===t.type&&1===n.type?this.Jr=this.Jr.insert(e,{type:2,doc:t.doc}):Kr()}Yr(){const n=[];return this.Jr.inorderTraversal((t,e)=>{n.push(e)}),n}}class Wu{constructor(t,e,n,r,s,i,o,a){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(t,e,n,r){const s=[];return e.forEach(t=>{s.push({type:0,doc:t})}),new Wu(t,e,Hu.emptySet(e),s,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&yi(this.query,t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;const e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(let t=0;twi(t),yi),this.onlineState="Unknown",this.Zr=new Set}}async function Xu(t,e){const n=t,r=e.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Yu),s)try{i.Xr=await n.onListen(r)}catch(t){const n=zu(t,`Initialization of query '${vi(e.query)}' failed`);return void e.onError(n)}n.queries.set(r,i),i.listeners.push(e),e.eo(n.onlineState),!i.Xr||e.no(i.Xr)&&tc(n)}async function Zu(t,e){const n=t,r=e.query;let s=!1;const i=n.queries.get(r);if(i){const t=i.listeners.indexOf(e);0<=t&&(i.listeners.splice(t,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function tc(t){t.Zr.forEach(t=>{t.next()})}class ec{constructor(t,e,n){this.query=t,this.so=e,this.io=!1,this.ro=null,this.onlineState="Unknown",this.options=n||{}}no(t){if(!this.options.includeMetadataChanges){const e=[];for(const n of t.docChanges)3!==n.type&&e.push(n);t=new Wu(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0)}let e=!1;return this.io?this.oo(t)&&(this.so.next(t),e=!0):this.ao(t,this.onlineState)&&(this.co(t),e=!0),this.ro=t,e}onError(t){this.so.error(t)}eo(t){this.onlineState=t;let e=!1;return this.ro&&!this.io&&this.ao(this.ro,t)&&(this.co(this.ro),e=!0),e}ao(t,e){return!t.fromCache||!(this.options.uo&&"Offline"!==e||t.docs.isEmpty()&&"Offline"!==e)}oo(t){if(0qh(e,h,o,os.min(),a).next(t=>(h.apply(e),t)).next(t=>s.ze.removeMatchingKeysForTargetId(e,u.targetId).next(()=>s.ze.addMatchingKeys(e,i,u.targetId)).next(()=>s.Qn.vn(e,t)).next(()=>t)))}(this.localStore,new rc(this.N),this.documents,this.lo.id),e=this.wo(this.documents);for(const t of this.queries)await async function(t,n,r=uo()){const s=await Bh(t,mi(ja(n.bundledQuery))),i=t;return i.persistence.runTransaction("Save named query","readwrite",t=>{var e=No(n.readTime);if(0<=s.snapshotVersion.compareTo(e))return i.Je.saveNamedQuery(t,n);e=s.withResumeToken(ms.EMPTY_BYTE_STRING,e);return i.Un=i.Un.insert(e.targetId,e),i.ze.updateTargetData(t,e).next(()=>i.ze.removeMatchingKeysForTargetId(t,s.targetId)).next(()=>i.ze.addMatchingKeys(t,r,s.targetId)).next(()=>i.Je.saveNamedQuery(t,n))})}(this.localStore,t,e.get(t.name));return this.progress.taskState="Success",new kh(Object.assign({},this.progress),t)}}function ic(t){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:t.totalDocuments,totalBytes:t.totalBytes}}class oc{constructor(t){this.key=t}}class ac{constructor(t){this.key=t}}class hc{constructor(t,e){this.query=t,this._o=e,this.mo=null,this.current=!1,this.yo=uo(),this.mutatedKeys=uo(),this.po=Ti(t),this.Eo=new Hu(this.po)}get To(){return this._o}Io(t,e){const a=e?e.Ao:new Qu,h=(e||this).Eo;let u=(e||this).mutatedKeys,c=h,l=!1;const d=ui(this.query)&&h.size===this.query.limit?h.last():null,f=ci(this.query)&&h.size===this.query.limit?h.first():null;if(t.inorderTraversal((t,e)=>{const n=h.get(t),r=bi(this.query,e)?e:null,s=!!n&&this.mutatedKeys.has(n.key),i=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let o=!1;n&&r?n.data.isEqual(r.data)?s!==i&&(a.track({type:3,doc:r}),o=!0):this.Ro(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0this.query.limit;){const t=ui(this.query)?c.last():c.first();c=c.delete(t.key),u=u.delete(t.key),a.track({type:1,doc:t})}return{Eo:c,Ao:a,Ln:l,mutatedKeys:u}}Ro(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations}applyChanges(t,e,n){var r=this.Eo;this.Eo=t.Eo,this.mutatedKeys=t.mutatedKeys;const s=t.Ao.Yr();s.sort((t,e)=>function(t,e){var n=t=>{switch(t){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Kr()}};return n(t)-n(e)}(t.type,e.type)||this.po(t.doc,e.doc)),this.Po(n);var i=e?this.bo():[],n=0===this.yo.size&&this.current?1:0,e=n!==this.mo;return this.mo=n,0!==s.length||e?{snapshot:new Wu(this.query,t.Eo,r,s,t.mutatedKeys,0==n,e,!1),vo:i}:{vo:i}}eo(t){return this.current&&"Offline"===t?(this.current=!1,this.applyChanges({Eo:this.Eo,Ao:new Qu,mutatedKeys:this.mutatedKeys,Ln:!1},!1)):{vo:[]}}Vo(t){return!this._o.has(t)&&!!this.Eo.has(t)&&!this.Eo.get(t).hasLocalMutations}Po(t){t&&(t.addedDocuments.forEach(t=>this._o=this._o.add(t)),t.modifiedDocuments.forEach(t=>{}),t.removedDocuments.forEach(t=>this._o=this._o.delete(t)),this.current=t.current)}bo(){if(!this.current)return[];const e=this.yo;this.yo=uo(),this.Eo.forEach(t=>{this.Vo(t.key)&&(this.yo=this.yo.add(t.key))});const n=[];return e.forEach(t=>{this.yo.has(t)||n.push(new ac(t))}),this.yo.forEach(t=>{e.has(t)||n.push(new oc(t))}),n}So(t){this._o=t.Gn,this.yo=uo();t=this.Io(t.documents);return this.applyChanges(t,!0)}Do(){return Wu.fromInitialDocuments(this.query,this.Eo,this.mutatedKeys,0===this.mo)}}class uc{constructor(t,e,n){this.query=t,this.targetId=e,this.view=n}}class cc{constructor(t){this.key=t,this.Co=!1}}class lc{constructor(t,e,n,r,s,i){this.localStore=t,this.remoteStore=e,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.No={},this.xo=new yh(t=>wi(t),yi),this.ko=new Map,this.$o=new Set,this.Oo=new to(Ss.comparator),this.Fo=new Map,this.Mo=new Hh,this.Lo={},this.Bo=new Map,this.Uo=ih.ie(),this.onlineState="Unknown",this.qo=void 0}get isPrimaryClient(){return!0===this.qo}}async function dc(n,t,e,r){n.Ko=(t,s,e)=>async function(t,e,n){let r=e.view.Io(s);r.Ln&&(r=await Kh(t.localStore,e.query,!1).then(({documents:t})=>e.view.Io(t,r)));n=n&&n.targetChanges.get(e.targetId),n=e.view.applyChanges(r,t.isPrimaryClient,n);return Tc(t,e.targetId,n.vo),n.snapshot}(n,t,e);const s=await Kh(n.localStore,t,!0),i=new hc(t,s.Gn),o=i.Io(s.documents),a=fo.createSynthesizedTargetChangeForCurrentChange(e,r&&"Offline"!==n.onlineState),h=i.applyChanges(o,n.isPrimaryClient,a);Tc(n,e,h.vo);r=new uc(t,e,i);return n.xo.set(t,r),n.ko.has(e)?n.ko.get(e).push(t):n.ko.set(e,[t]),h.snapshot}async function fc(t,e,n){const r=Dc(t);try{const t=await function(t,r){const s=t,i=is.now(),e=r.reduce((t,e)=>t.add(e.key),uo());let o;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>s.Qn.bn(n,e).next(t=>{o=t;const e=[];for(const n of r){const r=function(t,e){let n=null;for(const r of t.fieldTransforms){const t=e.data.field(r.field),s=Ni(r.transform,t||null);null!=s&&(null==n&&(n=Us.empty()),n.set(r.field,s))}return n||null}(n,o.get(n.key));null!=r&&e.push(new Gi(n.key,r,function r(t){const s=[];return hs(t.fields,(t,e)=>{const n=new fs([t]);if(Fs(e)){const t=r(e.mapValue).fields;if(0===t.length)s.push(n);else for(const e of t)s.push(n.child(e))}else s.push(n)}),new gs(s)}(r.value.mapValue),Fi.exists(!0)))}return s.In.addMutationBatch(n,i,e,r)})).then(t=>(t.applyToLocalDocumentSet(o),{batchId:t.batchId,changes:o}))}(r.localStore,e);r.sharedClientState.addPendingMutation(t.batchId),function(t,e,n){let r=t.Lo[t.currentUser.toKey()];r=r||new to(ns),r=r.insert(e,n),t.Lo[t.currentUser.toKey()]=r}(r,t.batchId,n),await Ic(r,t.changes),await Uu(r.remoteStore)}catch(t){const e=zu(t,"Failed to persist write");n.reject(e)}}async function gc(t,e){const r=t;try{const t=await Uh(r.localStore,e);e.targetChanges.forEach((t,e)=>{const n=r.Fo.get(e);n&&($r(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1),0{e=e.view.eo(r);e.snapshot&&n.push(e.snapshot)}),function(t,n){const e=t;e.onlineState=n;let r=!1;e.queries.forEach((t,e)=>{for(const t of e.listeners)t.eo(n)&&(r=!0)}),r&&tc(e)}(e.eventManager,r),n.length&&e.No.Tr(n),e.onlineState=r,e.isPrimaryClient&&e.sharedClientState.setOnlineState(r)}}async function pc(t,e){const n=t,r=e.batch.batchId;try{const t=await function(t,r){const s=t;return s.persistence.runTransaction("Acknowledge batch","readwrite-primary",t=>{const e=r.batch.keys(),n=s.jn.newChangeBuffer({trackRemovals:!0});return function(t,e,r,s){const i=r.batch,n=i.keys();let o=ya.resolve();return n.forEach(n=>{o=o.next(()=>s.getEntry(e,n)).next(t=>{var e=r.docVersions.get(n);$r(null!==e),t.version.compareTo(e)<0&&(i.applyToRemoteDocument(t,r),t.isValidDocument()&&s.addEntry(t,r.commitVersion))})}),o.next(()=>t.In.removeMutationBatch(e,i))}(s,t,r,n).next(()=>n.apply(t)).next(()=>s.In.performConsistencyCheck(t)).next(()=>s.Qn.bn(t,e))})}(n.localStore,e);wc(n,r,null),yc(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Ic(n,t)}catch(t){await ch(t)}}function yc(t,e){(t.Bo.get(e)||[]).forEach(t=>{t.resolve()}),t.Bo.delete(e)}function wc(t,e,n){const r=t;let s=r.Lo[r.currentUser.toKey()];if(s){const t=s.get(e);t&&(n?t.reject(n):t.resolve(),s=s.remove(e)),r.Lo[r.currentUser.toKey()]=s}}function vc(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.ko.get(t))e.xo.delete(r),n&&e.No.jo(r,n);e.ko.delete(t),e.isPrimaryClient&&e.Mo.cs(t).forEach(t=>{e.Mo.containsKey(t)||bc(e,t)})}function bc(t,e){t.$o.delete(e.path.canonicalString());var n=t.Oo.get(e);null!==n&&(xu(t.remoteStore,n),t.Oo=t.Oo.remove(e),t.Fo.delete(n),Ec(t))}function Tc(t,e,n){for(const r of n)r instanceof oc?(t.Mo.addReference(r.key,e),function(t,e){const n=e.key,r=n.path.canonicalString();t.Oo.get(n)||t.$o.has(r)||(Ur("SyncEngine","New document in limbo: "+n),t.$o.add(r),Ec(t))}(t,r)):r instanceof ac?(Ur("SyncEngine","Document no longer in limbo: "+r.key),t.Mo.removeReference(r.key,e),t.Mo.containsKey(r.key)||bc(t,r.key)):Kr()}function Ec(t){for(;0{a.push(s.Ko(e,n,r).then(t=>{t&&(s.isPrimaryClient&&s.sharedClientState.updateQueryState(e.targetId,t.fromCache?"not-current":"current"),i.push(t),t=Lh.kn(e.targetId,t),o.push(t))}))}),await Promise.all(a),s.No.Tr(i),await async function(t,e){const r=t;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>ya.forEach(e,e=>ya.forEach(e.Nn,t=>r.persistence.referenceDelegate.addReference(n,e.targetId,t)).next(()=>ya.forEach(e.xn,t=>r.persistence.referenceDelegate.removeReference(n,e.targetId,t)))))}catch(t){if(!Ea(t))throw t;Ur("LocalStore","Failed to update sequence numbers: "+t)}for(const t of e){const e=t.targetId;if(!t.fromCache){const t=r.Un.get(e),n=t.snapshotVersion,s=t.withLastLimboFreeSnapshotVersion(n);r.Un=r.Un.insert(e,s)}}}(s.localStore,o))}async function _c(r,t){const s=r;if(Ac(s),Dc(s),!0===t&&!0!==s.qo){const r=s.sharedClientState.getAllActiveQueryTargets(),t=await Sc(s,r.toArray());s.qo=!0,await ju(s.remoteStore,!0);for(const r of t)Cu(s.remoteStore,r)}else if(!1===t&&!1!==s.qo){const r=[];let n=Promise.resolve();s.ko.forEach((t,e)=>{s.sharedClientState.isLocalQueryTarget(e)?r.push(e):n=n.then(()=>(vc(s,e),jh(s.localStore,e,!0))),xu(s.remoteStore,e)}),await n,await Sc(s,r),function(){const n=s;n.Fo.forEach((t,e)=>{xu(n.remoteStore,e)}),n.Mo.us(),n.Fo=new Map,n.Oo=new to(Ss.comparator)}(),s.qo=!1,await ju(s.remoteStore,!1)}}async function Sc(e,n){const r=e,s=[],i=[];for(const e of n){let t;const u=r.ko.get(e);if(u&&0!==u.length){t=await Bh(r.localStore,mi(u[0]));for(const e of u){const n=r.xo.get(e),u=(o=r,a=n,h=void 0,o=await Kh((h=o).localStore,a.query,!0),o=a.view.So(o),h.isPrimaryClient&&Tc(h,a.targetId,o.vo),await o);u.snapshot&&i.push(u.snapshot)}}else{const u=await $h(r.localStore,e);t=await Bh(r.localStore,u),await dc(r,Nc(u),e,!1)}s.push(t)}var o,a,h;return r.No.Tr(i),s}function Nc(t){return ai(t.path,t.collectionGroup,t.orderBy,t.filters,t.limit,"F",t.startAt,t.endAt)}function Ac(t){const e=t;return e.remoteStore.remoteSyncer.applyRemoteEvent=gc.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=function(t,e){const n=t,r=n.Fo.get(e);if(r&&r.Co)return uo().add(r.key);{let t=uo();const r=n.ko.get(e);if(!r)return t;for(const e of r){const r=n.xo.get(e);t=t.unionWith(r.view.To)}return t}}.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=async function(t,e,n){const r=t;r.sharedClientState.updateQueryState(e,"rejected",n);const s=r.Fo.get(e),i=s&&s.key;if(i){let t=new to(Ss.comparator);t=t.insert(i,qs.newNoDocument(i,os.min()));const n=uo().add(i),s=new lo(os.min(),new Map,new ro(ns),t,n);await gc(r,s),r.Oo=r.Oo.remove(i),r.Fo.delete(e),Ec(r)}else await jh(r.localStore,e,!1).then(()=>vc(r,e,n)).catch(ch)}.bind(null,e),e.No.Tr=function(t,e){const n=t;let r=!1;for(const t of e){const e=t.query,s=n.queries.get(e);if(s){for(const e of s.listeners)e.no(t)&&(r=!0);s.Xr=t}}r&&tc(n)}.bind(null,e.eventManager),e.No.jo=function(t,e,n){const r=t,s=r.queries.get(e);if(s)for(const t of s.listeners)t.onError(n);r.queries.delete(e)}.bind(null,e.eventManager),e}function Dc(t){const e=t;return e.remoteStore.remoteSyncer.applySuccessfulWrite=pc.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=async function(t,e,n){const r=t;try{const t=await function(t,r){const s=t;return s.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return s.In.lookupMutationBatch(e,r).next(t=>($r(null!==t),n=t.keys(),s.In.removeMutationBatch(e,t))).next(()=>s.In.performConsistencyCheck(e)).next(()=>s.Qn.bn(e,n))})}(r.localStore,e);wc(r,e,n),yc(r,e),r.sharedClientState.updateMutationState(e,"rejected",n),await Ic(r,t)}catch(n){await ch(n)}}.bind(null,e),e}class Cc{constructor(){this.synchronizeTabs=!1}async initialize(t){this.N=vu(t.databaseInfo.databaseId),this.sharedClientState=this.Wo(t),this.persistence=this.Go(t),await this.persistence.start(),this.gcScheduler=this.zo(t),this.localStore=this.Ho(t)}zo(t){return null}Ho(t){return Ph(this.persistence,new Oh,t.initialUser,this.N)}Go(t){return new Zh(eu.Ns,this.N)}Wo(t){return new lu}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class xc extends Cc{constructor(t,e,n){super(),this.Jo=t,this.cacheSizeBytes=e,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(t){await super.initialize(t),await async function(t){const e=t;return e.persistence.runTransaction("Synchronize last document change read time","readonly",e=>function(){const t=Eh(e);let r=os.min();return t.Kt({index:ia.readTimeIndex,reverse:!0},(t,e,n)=>{e.readTime&&(r=Pa(e.readTime)),n.done()}).next(()=>r)}()).then(t=>{e.Kn=t})}(this.localStore),await this.Jo.initialize(this,t),await Dc(this.Jo.syncEngine),await Uu(this.Jo.remoteStore),await this.persistence.nn(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Ho(t){return Ph(this.persistence,new Oh,t.initialUser,this.N)}zo(t){var e=this.persistence.referenceDelegate.garbageCollector;return new fh(e,t.asyncQueue)}Go(t){var e=xh(t.databaseInfo.databaseId,t.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Ja.withCacheSize(this.cacheSizeBytes):Ja.DEFAULT;return new Ah(this.synchronizeTabs,e,t.clientId,n,t.asyncQueue,yu(),wu(),this.N,this.sharedClientState,!!this.forceOwnership)}Wo(t){return new lu}}class kc extends xc{constructor(t,e){super(t,e,!1),this.Jo=t,this.cacheSizeBytes=e,this.synchronizeTabs=!0}async initialize(t){await super.initialize(t);t=this.Jo.syncEngine;this.sharedClientState instanceof cu&&(this.sharedClientState.syncEngine={_i:async function(t,e,n,r){var s=t;null!==(t=await function(t,n){const r=t,s=r.In;return r.persistence.runTransaction("Lookup mutation documents","readonly",e=>s.Xt(e,n).next(t=>t?r.Qn.bn(e,t):ya.resolve(null)))}(s.localStore,e))?("pending"===n?await Uu(s.remoteStore):"acknowledged"===n||"rejected"===n?(wc(s,e,r||null),yc(s,e),s.localStore.In.te(e)):Kr(),await Ic(s,t)):Ur("SyncEngine","Cannot apply mutation batch with id: "+e)}.bind(null,t),mi:async function(t,e,n,r){const s=t;if(s.qo)Ur("SyncEngine","Ignoring unexpected query state notification.");else if(s.ko.has(e))switch(n){case"current":case"not-current":{const t=await Gh(s.localStore),r=lo.createSynthesizedRemoteEventForCurrentChange(e,"current"===n);await Ic(s,t,r);break}case"rejected":await jh(s.localStore,e,!0),vc(s,e,r);break;default:Kr()}}.bind(null,t),gi:async function(t,e,n){const r=Ac(t);if(r.qo){for(const t of e)if(r.ko.has(t))Ur("SyncEngine","Adding an already active target "+t);else{const e=await $h(r.localStore,t),n=await Bh(r.localStore,e);await dc(r,Nc(e),n.targetId,!1),Cu(r.remoteStore,n)}for(const t of n)r.ko.has(t)&&await jh(r.localStore,t,!1).then(()=>{xu(r.remoteStore,t),vc(r,t)}).catch(ch)}}.bind(null,t),pn:function(t){return t.localStore.persistence.pn()}.bind(null,t),wi:async function(t){const e=t;return Gh(e.localStore).then(t=>Ic(e,t))}.bind(null,t)},await this.sharedClientState.start()),await this.persistence.nn(async t=>{await _c(this.Jo.syncEngine,t),this.gcScheduler&&(t&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):t||this.gcScheduler.stop())})}Wo(t){var e=yu();if(!cu.Pt(e))throw new zr(Gr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=xh(t.databaseInfo.databaseId,t.databaseInfo.persistenceKey);return new cu(e,t.asyncQueue,n,t.clientId,t.initialUser)}}class Rc{async initialize(t,e){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(e),this.remoteStore=this.createRemoteStore(e),this.eventManager=this.createEventManager(e),this.syncEngine=this.createSyncEngine(e,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=t=>mc(this.syncEngine,t,1),this.remoteStore.remoteSyncer.handleCredentialChange=async function(t,e){const n=t;if(!n.currentUser.isEqual(e)){Ur("SyncEngine","User change. New user:",e.toKey());const r=await Fh(n.localStore,e);n.currentUser=e,(t=n).Bo.forEach(t=>{t.forEach(t=>{t.reject(new zr(Gr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),t.Bo.clear(),n.sharedClientState.handleUserChange(e,r.removedBatchIds,r.addedBatchIds),await Ic(n,r.Wn)}}.bind(null,this.syncEngine),await ju(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return new Ju}createDatastore(t){var e,n=vu(t.databaseInfo.databaseId),e=(e=t.databaseInfo,new pu(e));return t=t.credentials,e=e,n=n,new _u(t,e,n)}createRemoteStore(t){return e=this.localStore,n=this.datastore,r=t.asyncQueue,s=t=>mc(this.syncEngine,t,0),t=new(fu.Pt()?fu:du),new Nu(e,n,r,s,t);var e,n,r,s}createSyncEngine(t,e){return function(t,e,n,r,s,i,o){const a=new lc(t,e,n,r,s,i);return o&&(a.qo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,t.initialUser,t.maxConcurrentLimboResolutions,e)}terminate(){return async function(t){const e=t;Ur("RemoteStore","RemoteStore shutting down."),e.Kr.add(5),await Du(e),e.Qr.shutdown(),e.Wr.set("Unknown")}(this.remoteStore)}}function Lc(e,n=10240){let r=0;return{async read(){if(r{this.muted||t(e)},0)}}class Mc{constructor(t,e){this.Zo=t,this.N=e,this.metadata=new Hr,this.buffer=new Uint8Array,this.ta=new TextDecoder("utf-8"),this.ea().then(t=>{t&&t.ho()?this.metadata.resolve(t.payload.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==t?void 0:t.payload)}`))},t=>this.metadata.reject(t))}close(){return this.Zo.cancel()}async getMetadata(){return this.metadata.promise}async Qo(){return await this.getMetadata(),this.ea()}async ea(){var t=await this.na();if(null===t)return null;var e=this.ta.decode(t),n=Number(e);isNaN(n)&&this.sa(`length string (${e}) is not valid number`);e=await this.ia(n);return new nc(JSON.parse(e),t.length+n)}ra(){return this.buffer.findIndex(t=>t==="{".charCodeAt(0))}async na(){for(;this.ra()<0&&!await this.oa(););if(0===this.buffer.length)return null;var t=this.ra();t<0&&this.sa("Reached the end of bundle when a length string is expected.");var e=this.buffer.slice(0,t);return this.buffer=this.buffer.slice(t),e}async ia(t){for(;this.buffer.lengthCo(r.N,t))},i=await r.Ki("BatchGetDocuments",n,s),o=new Map;i.forEach(t=>{const e=(n=r.N,"found"in(t=t)?function(t,e){$r(!!e.found),e.found.name,e.found.updateTime;var n=xo(t,e.found.name),t=No(e.found.updateTime),e=new Us({mapValue:{fields:e.found.fields}});return qs.newFoundDocument(n,t,e)}(n,t):"missing"in t?function(t,e){$r(!!e.missing),$r(!!e.readTime);t=xo(t,e.missing),e=No(e.readTime);return qs.newNoDocument(t,e)}(n,t):Kr());var n;o.set(e.key.toString(),e)});const a=[];return e.forEach(t=>{t=o.get(t.toString());$r(!!t),a.push(t)}),a}(this.datastore,t);return e.forEach(t=>this.recordVersion(t)),e}set(t,e){this.write(e.toMutation(t,this.precondition(t))),this.writtenDocs.add(t.toString())}update(t,e){try{this.write(e.toMutation(t,this.preconditionForUpdate(t)))}catch(t){this.lastWriteError=t}this.writtenDocs.add(t.toString())}delete(t){this.write(new Wi(t,this.precondition(t))),this.writtenDocs.add(t.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const e=this.readVersions;this.mutations.forEach(t=>{e.delete(t.key.toString())}),e.forEach((t,e)=>{e=Ss.fromPath(e);this.mutations.push(new Yi(e,this.precondition(e)))}),await async function(t,e){const n=t,r=Lo(n.N)+"/documents",s={writes:e.map(t=>Fo(n.N,t))};await n.Li("Commit",r,s)}(this.datastore,this.mutations),this.committed=!0}recordVersion(t){let e;if(t.isFoundDocument())e=t.version;else{if(!t.isNoDocument())throw Kr();e=os.min()}var n=this.readVersions.get(t.key.toString());if(n){if(!e.isEqual(n))throw new zr(Gr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(t.key.toString(),e)}precondition(t){var e=this.readVersions.get(t.toString());return!this.writtenDocs.has(t.toString())&&e?Fi.updateTime(e):Fi.none()}preconditionForUpdate(t){const e=this.readVersions.get(t.toString());if(this.writtenDocs.has(t.toString())||!e)return Fi.exists(!0);if(e.isEqual(os.min()))throw new zr(Gr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Fi.updateTime(e)}write(t){this.ensureCommitNotCalled(),this.mutations.push(t)}ensureCommitNotCalled(){}}class Fc{constructor(t,e,n,r){this.asyncQueue=t,this.datastore=e,this.updateFunction=n,this.deferred=r,this.aa=5,this.rr=new bu(this.asyncQueue,"transaction_retry")}run(){--this.aa,this.ca()}ca(){this.rr.Xi(async()=>{const e=new Pc(this.datastore),t=this.ua(e);t&&t.then(t=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(t)}).catch(t=>{this.ha(t)}))}).catch(t=>{this.ha(t)})})}ua(t){try{var e=this.updateFunction(t);return!Es(e)&&e.catch&&e.then?e:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(t){return this.deferred.reject(t),null}}ha(t){0(this.ca(),Promise.resolve()))):this.deferred.reject(t)}la(t){if("FirebaseError"!==t.name)return!1;t=t.code;return"aborted"===t||"failed-precondition"===t||!Xi(t)}}class Vc{constructor(t,e,n){this.credentials=t,this.asyncQueue=e,this.databaseInfo=n,this.user=Mr.UNAUTHENTICATED,this.clientId=es.I(),this.credentialListener=()=>Promise.resolve(),this.credentials.start(e,async t=>{Ur("FirestoreClient","Received user=",t.uid),await this.credentialListener(t),this.user=t})}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,credentials:this.credentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(t){this.credentialListener=t}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new zr(Gr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Hr;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.credentials.shutdown(),n.resolve()}catch(t){var e=zu(t,"Failed to shutdown persistence");n.reject(e)}}),n.promise}}async function Uc(t,e){t.asyncQueue.verifyOperationInProgress(),Ur("FirestoreClient","Initializing OfflineComponentProvider");var n=await t.getConfiguration();await e.initialize(n);let r=n.initialUser;t.setCredentialChangeListener(async t=>{r.isEqual(t)||(await Fh(e.localStore,t),r=t)}),e.persistence.setDatabaseDeletedListener(()=>t.terminate()),t.offlineComponents=e}async function qc(t,e){t.asyncQueue.verifyOperationInProgress();var n=await Bc(t);Ur("FirestoreClient","Initializing OnlineComponentProvider");var r=await t.getConfiguration();await e.initialize(n,r),t.setCredentialChangeListener(t=>async function(t,e){const n=t;n.asyncQueue.verifyOperationInProgress(),Ur("RemoteStore","RemoteStore received new credentials");t=Mu(n);n.Kr.add(3),await Du(n),t&&n.Wr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(e),n.Kr.delete(3),await Au(n)}(e.remoteStore,t)),t.onlineComponents=e}async function Bc(t){return t.offlineComponents||(Ur("FirestoreClient","Using default OfflineComponentProvider"),await Uc(t,new Cc)),t.offlineComponents}async function jc(t){return t.onlineComponents||(Ur("FirestoreClient","Using default OnlineComponentProvider"),await qc(t,new Rc)),t.onlineComponents}function Kc(t){return Bc(t).then(t=>t.persistence)}function $c(t){return Bc(t).then(t=>t.localStore)}function Gc(t){return jc(t).then(t=>t.remoteStore)}function zc(t){return jc(t).then(t=>t.syncEngine)}async function Hc(t){const e=await jc(t),n=e.eventManager;return n.onListen=async function(t,e){const n=Ac(t);let r,s;const i=n.xo.get(e);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.Do();else{const t=await Bh(n.localStore,mi(e)),i=n.sharedClientState.addLocalQueryTarget(t.targetId);r=t.targetId,s=await dc(n,e,r,"current"===i),n.isPrimaryClient&&Cu(n.remoteStore,t)}return s}.bind(null,e.syncEngine),n.onUnlisten=async function(t,e){const n=t,r=n.xo.get(e),s=n.ko.get(r.targetId);if(1!yi(t,e))),void n.xo.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await jh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),xu(n.remoteStore,r.targetId),vc(n,r.targetId)}).catch(ch)):(vc(n,r.targetId),await jh(n.localStore,r.targetId,!0))}.bind(null,e.syncEngine),n}function Qc(t,e,n={}){const r=new Hr;return t.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,o){const t=new Oc({next:t=>{r.enqueueAndForget(()=>Zu(n,a));var e=t.docs.has(s);!e&&t.fromCache?o.reject(new zr(Gr.UNAVAILABLE,"Failed to get document because the client is offline.")):e&&t.fromCache&&i&&"server"===i.source?o.reject(new zr(Gr.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):o.resolve(t)},error:t=>o.reject(t)}),a=new ec(hi(s.path),t,{includeMetadataChanges:!0,uo:!0});return Xu(n,a)}(await Hc(t),t.asyncQueue,e,n,r)),r.promise}function Wc(t,e,n={}){const r=new Hr;return t.asyncQueue.enqueueAndForget(async()=>function(e,n,t,r,s){const i=new Oc({next:t=>{n.enqueueAndForget(()=>Zu(e,o)),t.fromCache&&"server"===r.source?s.reject(new zr(Gr.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.)')):s.resolve(t)},error:t=>s.reject(t)}),o=new ec(t,i,{includeMetadataChanges:!0,uo:!0});return Xu(e,o)}(await Hc(t),t.asyncQueue,e,n,r)),r.promise}function Yc(t,e,n,r){const s=function(t,e){t="string"==typeof t?(new TextEncoder).encode(t):t;return t=function(t){if(t instanceof Uint8Array)return Lc(t,void 0);if(t instanceof ArrayBuffer)return Lc(new Uint8Array(t),void 0);if(t instanceof ReadableStream)return t.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(t),e=e,new Mc(t,e)}(n,vu(e));t.asyncQueue.enqueueAndForget(async()=>{!function(t,e,n){const r=t;!async function(e,n,r){try{var s=await n.getMetadata();if(await function(t,e){const n=t,r=No(e.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",t=>n.Je.getBundleMetadata(t,e.id)).then(t=>!!t&&0<=t.createTime.compareTo(r))}(e.localStore,s))return await n.close(),void r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes});r._updateProgress(ic(s));const o=new sc(s,e.localStore,n.N);let t=await n.Qo();for(;t;){const e=await o.fo(t);e&&r._updateProgress(e),t=await n.Qo()}var i=await o.complete();await Ic(e,i.Tn,void 0),await function(t,e){const n=t;return n.persistence.runTransaction("Save bundle","readwrite",t=>n.Je.saveBundleMetadata(t,e))}(e.localStore,s),r._completeWith(i.progress)}catch(e){Br("SyncEngine",`Loading bundle failed with ${e}`),r._failWith(e)}}(r,e,n).then(()=>{r.sharedClientState.notifyBundleLoaded()})}(await zc(t),s,r)})}class Jc{constructor(t,e,n,r,s,i,o,a){this.databaseId=t,this.appId=e,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class Xc{constructor(t,e){this.projectId=t,this.database=e||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(t){return t instanceof Xc&&t.projectId===this.projectId&&t.database===this.database}}const Zc=new Map;function tl(t,e,n){if(!n)throw new zr(Gr.INVALID_ARGUMENT,`Function ${t}() cannot be called with an empty ${e}.`)}function el(t,e,n,r){if(!0===e&&!0===r)throw new zr(Gr.INVALID_ARGUMENT,`${t} and ${n} cannot be used together.`)}function nl(t){if(!Ss.isDocumentKey(t))throw new zr(Gr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`)}function rl(t){if(Ss.isDocumentKey(t))throw new zr(Gr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`)}function sl(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20{var t=wu();t&&Ur("AsyncQueue","Visibility state changed to "+t.visibilityState),this.rr.tr()};const t=wu();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Ea)}get isShuttingDown(){return this.wa}enqueueAndForget(t){this.enqueue(t)}enqueueAndForgetEvenWhileRestricted(t){this.Ta(),this.Ia(t)}enterRestrictedMode(t){if(!this.wa){this.wa=!0,this.ya=t||!1;const e=wu();e&&"function"==typeof e.removeEventListener&&e.removeEventListener("visibilitychange",this.Ea)}}enqueue(t){if(this.Ta(),this.wa)return new Promise(()=>{});const e=new Hr;return this.Ia(()=>this.wa&&this.ya?Promise.resolve():(t().then(e.resolve,e.reject),e.promise)).then(()=>e.promise)}enqueueRetryable(t){this.enqueueAndForget(()=>(this.da.push(t),this.Aa()))}async Aa(){if(0!==this.da.length){try{await this.da[0](),this.da.shift(),this.rr.reset()}catch(t){if(!Ea(t))throw t;Ur("AsyncQueue","Operation failed with retryable error: "+t)}0this.Aa())}}Ia(t){var e=this.fa.then(()=>(this.ga=!0,t().catch(t=>{throw this.ma=t,this.ga=!1,qr("INTERNAL UNHANDLED ERROR: ",function(t){let e=t.message||"";return t.stack&&(e=t.stack.includes(t.message)?t.stack:t.message+"\n"+t.stack),e}(t)),t}).then(t=>(this.ga=!1,t))));return this.fa=e}enqueueAfterDelay(t,e,n){this.Ta(),-1this.Ra(t));return this._a.push(n),n}Ta(){this.ma&&Kr()}verifyOperationInProgress(){}async Pa(){for(var t;await(t=this.fa),t!==this.fa;);}ba(t){for(const e of this._a)if(e.timerId===t)return!0;return!1}va(e){return this.Pa().then(()=>{this._a.sort((t,e)=>t.targetTimeMs-e.targetTimeMs);for(const t of this._a)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Pa()})}Va(t){this.pa.push(t)}Ra(t){t=this._a.indexOf(t);this._a.splice(t,1)}}function wl(t){return function(t){if("object"==typeof t&&null!==t){var e=t;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return 1}}(t)}class vl{constructor(){this._progressObserver={},this._taskCompletionResolver=new Hr,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(t,e,n){this._progressObserver={next:t,error:e,complete:n}}catch(t){return this._taskCompletionResolver.promise.catch(t)}then(t,e){return this._taskCompletionResolver.promise.then(t,e)}_completeWith(t){this._updateProgress(t),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(t)}_failWith(t){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(t),this._taskCompletionResolver.reject(t)}_updateProgress(t){this._lastProgress=t,this._progressObserver.next&&this._progressObserver.next(t)}}var bl,Tl;class El extends hl{constructor(t,e){super(t,e),this.type="firestore",this._queue=new yl,this._persistenceKey="name"in t?t.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||_l(this),this._firestoreClient.terminate()}}function Il(t){return t._firestoreClient||_l(t),t._firestoreClient.verifyNotTerminated(),t._firestoreClient}function _l(t){var e,n,r,s=t._freezeSettings(),s=(e=t._databaseId,n=(null===(r=t._app)||void 0===r?void 0:r.options.appId)||"",r=t._persistenceKey,s=s,new Jc(e,n,r,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));t._firestoreClient=new Vc(t._credentials,t._queue,s)}function Sl(t,n,r){const s=new Hr;return t.asyncQueue.enqueue(async()=>{try{await Uc(t,r),await qc(t,n),s.resolve()}catch(t){if(!("FirebaseError"===(e=t).name?e.code===Gr.FAILED_PRECONDITION||e.code===Gr.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||(22===e.code||20===e.code||11===e.code)))throw t;console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+t),s.reject(t)}var e}).then(()=>s.promise)}function Nl(t){return function(t){const e=new Hr;return t.asyncQueue.enqueueAndForget(async()=>async function(t,e){const n=t;Mu(n.remoteStore)||Ur("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const t=await function(){const e=n.localStore;return e.persistence.runTransaction("Get highest unacknowledged batch id","readonly",t=>e.In.getHighestUnacknowledgedBatchId(t))}();if(-1===t)return void e.resolve();const r=n.Bo.get(t)||[];r.push(e),n.Bo.set(t,r)}catch(t){const n=zu(t,"Initialization of waitForPendingWrites() operation failed");e.reject(n)}}(await zc(t),e)),e.promise}(Il(t=il(t,El)))}function Al(t){return(n=Il(t=il(t,El))).asyncQueue.enqueue(async()=>{const t=await Kc(n),e=await Gc(n);return t.setNetworkEnabled(!0),function(){const t=e;return t.Kr.delete(0),Au(t)}()});var n}function Dl(t){return(n=Il(t=il(t,El))).asyncQueue.enqueue(async()=>{const t=await Kc(n),e=await Gc(n);return t.setNetworkEnabled(!1),async function(){const t=e;t.Kr.add(0),await Du(t),t.Wr.set("Offline")}()});var n}function Cl(e,t){return n=Il(e=il(e,El)),r=t,n.asyncQueue.enqueue(async()=>function(t,e){const n=t;return n.persistence.runTransaction("Get named query","readonly",t=>n.Je.getNamedQuery(t,e))}(await $c(n),r)).then(t=>t?new ll(e,null,t.query):null);var n,r}function xl(t){if(t._initialized||t._terminated)throw new zr(Gr.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 kl{constructor(...e){for(let t=0;te.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}Sa(){if(this.path)for(let t=0;ta.covers(t.field))}else a=null,h=o.fieldTransforms;return new Pl(new Us(r),a,h)}class Kl extends Ll{_toFieldTransform(t){if(2!==t.Da)throw 1===t.Da?t.Fa(`${this._methodName}() can only appear at the top level of your update data`):t.Fa(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return t.fieldMask.push(t.path),null}isEqual(t){return t instanceof Kl}}function $l(t,e,n){return new Ul({Da:3,La:e.settings.La,methodName:t._methodName,xa:n},e.databaseId,e.N,e.ignoreUndefinedProperties)}class Gl extends Ll{_toFieldTransform(t){return new Mi(t.path,new Ai)}isEqual(t){return t instanceof Gl}}class zl extends Ll{constructor(t,e){super(t),this.Ua=e}_toFieldTransform(t){const e=$l(this,t,!0),n=this.Ua.map(t=>Xl(t,e)),r=new Di(n);return new Mi(t.path,r)}isEqual(t){return this===t}}class Hl extends Ll{constructor(t,e){super(t),this.Ua=e}_toFieldTransform(t){const e=$l(this,t,!0),n=this.Ua.map(t=>Xl(t,e)),r=new xi(n);return new Mi(t.path,r)}isEqual(t){return this===t}}class Ql extends Ll{constructor(t,e){super(t),this.qa=e}_toFieldTransform(t){var e=new Ri(t.N,_i(t.N,this.qa));return new Mi(t.path,e)}isEqual(t){return this===t}}function Wl(t,s,i,e){const o=t.Ba(1,s,i);ed("Data must be an object, but it was:",o,e);const a=[],h=Us.empty();hs(e,(t,e)=>{var n=sd(s,t,i);e=y(e);t=o.$a(n);if(e instanceof Kl)a.push(n);else{const r=Xl(e,t);null!=r&&(a.push(n),h.set(n,r))}});e=new gs(a);return new Fl(h,e,o.fieldTransforms)}function Yl(e,n,t,r,s,i){const o=e.Ba(1,n,t),a=[nd(n,r,t)],h=[s];if(i.length%2!=0)throw new zr(Gr.INVALID_ARGUMENT,`Function ${n}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let t=0;t{e=Xl(e,n.Na(t));null!=e&&(r[t]=e)}),{mapValue:{fields:r}}}function td(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof is||t instanceof Ol||t instanceof Rl||t instanceof cl||t instanceof Ll)}function ed(t,e,n){if(!td(n)||("object"!=typeof(r=n)||null===r||Object.getPrototypeOf(r)!==Object.prototype&&null!==Object.getPrototypeOf(r))){n=sl(n);throw"an object"===n?e.Fa(t+" a custom object"):e.Fa(t+" "+n)}var r}function nd(t,e,n){if((e=y(e))instanceof kl)return e._internalPath;if("string"==typeof e)return sd(t,e);throw id("Field path arguments must be of type string or FieldPath.",t,!1,void 0,n)}const rd=new RegExp("[~\\*/\\[\\]]");function sd(e,n,r){if(0<=n.search(rd))throw id(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,r);try{return new kl(...n.split("."))._internalPath}catch(t){throw id(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,r)}}function id(t,e,n,r,s){var i=r&&!r.isEmpty(),o=void 0!==s;let a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let h="";return(i||o)&&(h+=" (found",i&&(h+=` in field ${r}`),o&&(h+=` in document ${s}`),h+=")"),new zr(Gr.INVALID_ARGUMENT,a+t+h)}function od(t,e){return t.some(t=>t.isEqual(e))}class ad{constructor(t,e,n,r,s){this._firestore=t,this._userDataWriter=e,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new cl(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var t=new hd(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}return this._userDataWriter.convertValue(this._document.data.value)}}get(t){if(this._document){t=this._document.data.field(ud("DocumentSnapshot.get",t));if(null!==t)return this._userDataWriter.convertValue(t)}}}class hd extends ad{data(){return super.data()}}function ud(t,e){return"string"==typeof e?sd(t,e):(e instanceof kl?e:e._delegate)._internalPath}class cd{constructor(t,e){this.hasPendingWrites=t,this.fromCache=e}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}}class ld extends ad{constructor(t,e,n,r,s,i){super(t,e,n,r,i),this._firestore=t,this._firestoreImpl=t,this.metadata=s}exists(){return super.exists()}data(t={}){if(this._document){if(this._converter){var e=new dd(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(e,t)}return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps)}}get(t,e={}){if(this._document){t=this._document.data.field(ud("DocumentSnapshot.get",t));if(null!==t)return this._userDataWriter.convertValue(t,e.serverTimestamps)}}}class dd extends ld{data(t={}){return super.data(t)}}class fd{constructor(t,e,n,r){this._firestore=t,this._userDataWriter=e,this._snapshot=r,this.metadata=new cd(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,n){this._snapshot.docs.forEach(t=>{e.call(n,new dd(this._firestore,this._userDataWriter,t.key,t,new cd(this._snapshot.mutatedKeys.has(t.key),this._snapshot.fromCache),this.query.converter))})}docChanges(t={}){t=!!t.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new zr(Gr.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(i,e){if(i._snapshot.oldDocs.isEmpty()){let e=0;return i._snapshot.docChanges.map(t=>({type:"added",doc:new dd(i._firestore,i._userDataWriter,t.doc.key,t.doc,new cd(i._snapshot.mutatedKeys.has(t.doc.key),i._snapshot.fromCache),i.query.converter),oldIndex:-1,newIndex:e++}))}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(t=>e||3!==t.type).map(t=>{var e=new dd(i._firestore,i._userDataWriter,t.doc.key,t.doc,new cd(i._snapshot.mutatedKeys.has(t.doc.key),i._snapshot.fromCache),i.query.converter);let n=-1,r=-1;return 0!==t.type&&(n=s.indexOf(t.doc.key),s=s.delete(t.doc.key)),1!==t.type&&(s=s.add(t.doc),r=s.indexOf(t.doc.key)),{type:function(t){switch(t){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Kr()}}(t.type),doc:e,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function gd(t,e){return t instanceof ld&&e instanceof ld?t._firestore===e._firestore&&t._key.isEqual(e._key)&&(null===t._document?null===e._document:t._document.isEqual(e._document))&&t._converter===e._converter:t instanceof fd&&e instanceof fd&&t._firestore===e._firestore&&pl(t.query,e.query)&&t.metadata.isEqual(e.metadata)&&t._snapshot.isEqual(e._snapshot)}function md(t){if(ci(t)&&0===t.explicitOrderBy.length)throw new zr(Gr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class pd{}function yd(t,...e){for(const n of e)t=n._apply(t);return t}class wd extends pd{constructor(t,e,n){super(),this.Ka=t,this.ja=e,this.Qa=n,this.type="where"}_apply(t){var e=Bl(t.firestore),e=function(t,e,n,r,s,i,o){let a;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new zr(Gr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on FieldPath.documentId().`);if("in"===i||"not-in"===i){Sd(o,i);const e=[];for(const n of o)e.push(_d(r,t,n));a={arrayValue:{values:e}}}else a=_d(r,t,o)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||Sd(o,i),a=Jl(n,e,o,"in"===i||"not-in"===i);i=zs.create(s,i,a);return function(t,e){if(e.v()){const r=di(t);if(null!==r&&!r.isEqual(e.field))throw new zr(Gr.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${e.field.toString()}'`);var n=li(t);null!==n&&Nd(0,e.field,n)}const r=function(t,e){for(const n of t.filters)if(0<=e.indexOf(n.op))return n.op;return null}(t,function(){switch(e.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===e.op?new zr(Gr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${e.op.toString()}' filter.`):new zr(Gr.INVALID_ARGUMENT,`Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`)}(t,i),i}(t._query,"where",e,t.firestore._databaseId,this.Ka,this.ja,this.Qa);return new ll(t.firestore,t.converter,(t=t._query,e=t.filters.concat([e]),new oi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),e,t.limit,t.limitType,t.startAt,t.endAt)))}}class vd extends pd{constructor(t,e){super(),this.Ka=t,this.Wa=e,this.type="orderBy"}_apply(t){var e=function(t,e,n){if(null!==t.startAt)throw new zr(Gr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==t.endAt)throw new zr(Gr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r=new ri(e,n);return e=r,null!==li(n=t)||null!==(t=di(n))&&Nd(0,t,e.field),r}(t._query,this.Ka,this.Wa);return new ll(t.firestore,t.converter,(t=t._query,e=t.explicitOrderBy.concat([e]),new oi(t.path,t.collectionGroup,e,t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt)))}}class bd extends pd{constructor(t,e,n){super(),this.type=t,this.Ga=e,this.za=n}_apply(t){return new ll(t.firestore,t.converter,pi(t._query,this.Ga,this.za))}}class Td extends pd{constructor(t,e,n){super(),this.type=t,this.Ha=e,this.Ja=n}_apply(t){var e=Id(t,this.type,this.Ha,this.Ja);return new ll(t.firestore,t.converter,(t=t._query,e=e,new oi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class Ed extends pd{constructor(t,e,n){super(),this.type=t,this.Ha=e,this.Ja=n}_apply(t){var e=Id(t,this.type,this.Ha,this.Ja);return new ll(t.firestore,t.converter,(t=t._query,e=e,new oi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function Id(t,e,n,r){if(n[0]=y(n[0]),n[0]instanceof ad)return function(t,e,n,r,s){if(!r)throw new zr(Gr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of gi(t))if(n.field.isKeyField())i.push(Rs(e,r.key));else{const t=r.data.field(n.field);if(bs(t))throw new zr(Gr.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===t){const t=n.field.canonicalString();throw new zr(Gr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`)}i.push(t)}return new ei(i,s)}(t._query,t.firestore._databaseId,e,n[0]._document,r);var s=Bl(t.firestore);return function(e,n,r,s,i,t){const o=e.explicitOrderBy;if(i.length>o.length)throw new zr(Gr.INVALID_ARGUMENT,`Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let t=0;t, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class Ad{convertValue(t,e="none"){switch(Ns(t)){case 0:return null;case 1:return t.booleanValue;case 2:return ws(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,e);case 5:return t.stringValue;case 6:return this.convertBytes(vs(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,e);case 10:return this.convertObject(t.mapValue,e);default:throw Kr()}}convertObject(t,n){const r={};return hs(t.fields,(t,e)=>{r[t]=this.convertValue(e,n)}),r}convertGeoPoint(t){return new Ol(ws(t.latitude),ws(t.longitude))}convertArray(t,e){return(t.values||[]).map(t=>this.convertValue(t,e))}convertServerTimestamp(t,e){switch(e){case"previous":var n=function t(e){e=e.mapValue.fields.__previous_value__;return bs(e)?t(e):e}(t);return null==n?null:this.convertValue(n,e);case"estimate":return this.convertTimestamp(Ts(t));default:return null}}convertTimestamp(t){t=ys(t);return new is(t.seconds,t.nanos)}convertDocumentKey(t,e){const n=ls.fromString(t);$r(Qo(n));const r=new Xc(n.get(1),n.get(3)),s=new Ss(n.popFirst(5));return r.isEqual(e)||qr(`Document ${s} 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 (${e.projectId}/${e.database}) instead.`),s}}function Dd(t,e,n){return t?n&&(n.merge||n.mergeFields)?t.toFirestore(e,n):t.toFirestore(e):e}class Cd extends Ad{constructor(t){super(),this.firestore=t}convertBytes(t){return new Rl(t)}convertReference(t){t=this.convertDocumentKey(t,this.firestore._databaseId);return new cl(this.firestore,null,t)}}class xd{constructor(t,e){this._firestore=t,this._commitHandler=e,this._mutations=[],this._committed=!1,this._dataReader=Bl(t)}set(t,e,n){this._verifyNotCommitted();const r=kd(t,this._firestore),s=Dd(r.converter,e,n),i=jl(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,Fi.none())),this}update(t,e,n,...r){this._verifyNotCommitted();t=kd(t,this._firestore);let s;return s="string"==typeof(e=y(e))||e instanceof kl?Yl(this._dataReader,"WriteBatch.update",t._key,e,n,r):Wl(this._dataReader,"WriteBatch.update",t._key,e),this._mutations.push(s.toMutation(t._key,Fi.exists(!0))),this}delete(t){this._verifyNotCommitted();t=kd(t,this._firestore);return this._mutations=this._mutations.concat(new Wi(t._key,Fi.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0async function(t,e,n){try{const r=await function(e){const n=t;return n.persistence.runTransaction("read document","readonly",t=>n.Qn.An(t,e))}(e);r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new zr(Gr.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(t){e=zu(t,`Failed to get document '${e} from cache`);n.reject(e)}}(await $c(t),e,n)),n.promise}(t,e._key).then(t=>new ld(n,r,e._key,t,new cd(null!==t&&t.hasLocalMutations,!0),e.converter))}function Od(e){e=il(e,ll);const n=il(e.firestore,El),t=Il(n),r=new Rd(n);return function(t,e){const n=new Hr;return t.asyncQueue.enqueueAndForget(async()=>async function(t,e,n){try{const r=await Kh(t,e,!0),s=new hc(e,r.Gn),i=s.Io(r.documents),o=s.applyChanges(i,!1);n.resolve(o.snapshot)}catch(t){e=zu(t,`Failed to execute query '${e} against cache`);n.reject(e)}}(await $c(t),e,n)),n.promise}(t,e._query).then(t=>new fd(n,r,e,t))}function Md(t,e,n){t=il(t,cl);var r=il(t.firestore,El),e=Dd(t.converter,e,n);return Ud(r,[jl(Bl(r),"setDoc",t._key,e,null!==t.converter,n).toMutation(t._key,Fi.none())])}function Pd(t,e,n,...r){t=il(t,cl);var s=il(t.firestore,El),i=Bl(s);let o;return o="string"==typeof(e=y(e))||e instanceof kl?Yl(i,"updateDoc",t._key,e,n,r):Wl(i,"updateDoc",t._key,e),Ud(s,[o.toMutation(t._key,Fi.exists(!0))])}function Fd(e,...n){var t;e=y(e);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||wl(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(wl(n[s])){const e=n[s];n[s]=null===(t=e.next)||void 0===t?void 0:t.bind(e),n[s+1]=null===(t=e.error)||void 0===t?void 0:t.bind(e),n[s+2]=null===(t=e.complete)||void 0===t?void 0:t.bind(e)}let o,a,h;if(e instanceof cl)a=il(e.firestore,El),h=hi(e._key.path),o={next:t=>{n[s]&&n[s](qd(a,e,t))},error:n[s+1],complete:n[s+2]};else{const u=il(e,ll);a=il(u.firestore,El),h=u._query;const c=new Rd(a);o={next:t=>{n[s]&&n[s](new fd(a,c,u,t))},error:n[s+1],complete:n[s+2]},md(e._query)}return function(t,e,n,r){const s=new Oc(r),i=new ec(e,s,n);return t.asyncQueue.enqueueAndForget(async()=>Xu(await Hc(t),i)),()=>{s.Xo(),t.asyncQueue.enqueueAndForget(async()=>Zu(await Hc(t),i))}}(Il(a),h,i,o)}function Vd(t,e){return function(t,e){const n=new Oc(e);return t.asyncQueue.enqueueAndForget(async()=>function(t,e){t.Zr.add(e),e.next()}(await Hc(t),n)),()=>{n.Xo(),t.asyncQueue.enqueueAndForget(async()=>function(t,e){t.Zr.delete(e)}(await Hc(t),n))}}(Il(t=il(t,El)),wl(e)?e:{next:e})}function Ud(t,e){return function(t,e){const n=new Hr;return t.asyncQueue.enqueueAndForget(async()=>fc(await zc(t),e,n)),n.promise}(Il(t),e)}function qd(t,e,n){var r=n.docs.get(e._key),s=new Rd(t);return new ld(t,s,e._key,r,new cd(n.hasPendingWrites,n.fromCache),e.converter)}class Bd extends class{constructor(t,e){this._firestore=t,this._transaction=e,this._dataReader=Bl(t)}get(t){const n=kd(t,this._firestore),r=new Cd(this._firestore);return this._transaction.lookup([n._key]).then(t=>{if(!t||1!==t.length)return Kr();const e=t[0];if(e.isFoundDocument())return new ad(this._firestore,r,e.key,e,n.converter);if(e.isNoDocument())return new ad(this._firestore,r,n._key,null,n.converter);throw Kr()})}set(t,e,n){t=kd(t,this._firestore),e=Dd(t.converter,e,n),n=jl(this._dataReader,"Transaction.set",t._key,e,null!==t.converter,n);return this._transaction.set(t._key,n),this}update(t,e,n,...r){t=kd(t,this._firestore),e="string"==typeof(e=y(e))||e instanceof kl?Yl(this._dataReader,"Transaction.update",t._key,e,n,r):Wl(this._dataReader,"Transaction.update",t._key,e);return this._transaction.update(t._key,e),this}delete(t){t=kd(t,this._firestore);return this._transaction.delete(t._key),this}}{constructor(t,e){super(t,e),this._firestore=t}get(t){const e=kd(t,this._firestore),n=new Rd(this._firestore);return super.get(t).then(t=>new ld(this._firestore,n,e._key,t._document,new cd(!1,!1),e.converter))}}function jd(e,n){return function(e,n){const r=new Hr;return e.asyncQueue.enqueueAndForget(async()=>{var t=await jc(e).then(t=>t.datastore);new Fc(e.asyncQueue,t,n,r).run()}),r.promise}(Il(e),t=>n(new Bd(e,t)))}S=gf.SDK_VERSION,Pr=S,gf._registerComponent(new v("firestore",(t,{options:e})=>{const n=t.getProvider("app").getImmediate(),r=new El(n,new Jr(t.getProvider("auth-internal")));return e=Object.assign({useFetchStreams:!0},e),r._setSettings(e),r},"PUBLIC")),gf.registerVersion("@firebase/firestore","3.0.0",void 0);function Kd(t,e){if(void 0===e)return{merge:!1};if(void 0!==e.mergeFields&&void 0!==e.merge)throw new zr("invalid-argument",`Invalid options passed to function ${t}(): You cannot `+'specify both "merge" and "mergeFields".');return e}function $d(){if("undefined"==typeof Uint8Array)throw new zr("unimplemented","Uint8Arrays are not available in this environment.")}function Gd(){if("undefined"==typeof atob)throw new zr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class zd{constructor(t){this._delegate=t}static fromBase64String(t){return Gd(),new zd(Rl.fromBase64String(t))}static fromUint8Array(t){return $d(),new zd(Rl.fromUint8Array(t))}toBase64(){return Gd(),this._delegate.toBase64()}toUint8Array(){return $d(),this._delegate.toUint8Array()}isEqual(t){return this._delegate.isEqual(t._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Hd(t){return function(t,e){if("object"!=typeof t||null===t)return;var n=t;for(const r of e)if(r in n&&"function"==typeof n[r])return 1;return}(t,["next","error","complete"])}class Qd{enableIndexedDbPersistence(t,e){return function(t,e){xl(t=il(t,El));var n=Il(t),r=t._freezeSettings(),t=new Rc;return Sl(n,t,new xc(t,r.cacheSizeBytes,null==e?void 0:e.forceOwnership))}(t._delegate,{forceOwnership:e})}enableMultiTabIndexedDbPersistence(t){return function(t){xl(t=il(t,El));var e=Il(t),n=t._freezeSettings(),t=new Rc;return Sl(e,t,new kc(t,n.cacheSizeBytes))}(t._delegate)}clearIndexedDbPersistence(t){return function(t){if(t._initialized&&!t._terminated)throw new zr(Gr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const e=new Hr;return t._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(t){if(!va.Pt())return Promise.resolve();t+="main";await va.delete(t)}(xh(t._databaseId,t._persistenceKey)),e.resolve()}catch(t){e.reject(t)}}),e.promise}(t._delegate)}}class Wd{constructor(t,e,n){this._delegate=e,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},t instanceof Xc||(this._appCompat=t)}get _databaseId(){return this._delegate._databaseId}settings(t){var e=this._delegate._getSettings();t.merge||e.host===t.host||Br("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),t.merge&&delete(t=Object.assign(Object.assign({},e),t)).merge,this._delegate._setSettings(t)}useEmulator(t,e,n={}){ul(this._delegate,t,e,n)}enableNetwork(){return Al(this._delegate)}disableNetwork(){return Dl(this._delegate)}enablePersistence(t){let e=!1,n=!1;return t&&(e=!!t.synchronizeTabs,n=!!t.experimentalForceOwningTab,el("synchronizeTabs",e,"experimentalForceOwningTab",n)),e?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 Nl(this._delegate)}onSnapshotsInSync(t){return Vd(this._delegate,t)}get app(){if(!this._appCompat)throw new zr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(t){try{return new cf(this,fl(this._delegate,t))}catch(t){throw ef(t,"collection()","Firestore.collection()")}}doc(t){try{return new tf(this,gl(this._delegate,t))}catch(t){throw ef(t,"doc()","Firestore.doc()")}}collectionGroup(t){try{return new af(this,function(t,e){if(t=il(t,hl),tl("collectionGroup","collection id",e),0<=e.indexOf("/"))throw new zr(Gr.INVALID_ARGUMENT,`Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new ll(t,null,(e=e,new oi(ls.emptyPath(),e)))}(this._delegate,t))}catch(t){throw ef(t,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(e){return jd(this._delegate,t=>e(new Jd(this,t)))}batch(){return Il(this._delegate),new Xd(new xd(this._delegate,t=>Ud(this._delegate,t)))}loadBundle(t){return e=this._delegate,n=t,r=Il(e=il(e,El)),t=new vl,Yc(r,e._databaseId,n,t),t;var e,n,r}namedQuery(t){return Cl(this._delegate,t).then(t=>t?new af(this,t):null)}}class Yd extends Ad{constructor(t){super(),this.firestore=t}convertBytes(t){return new zd(new Rl(t))}convertReference(t){t=this.convertDocumentKey(t,this.firestore._databaseId);return tf.forKey(t,this.firestore,null)}}class Jd{constructor(t,e){this._firestore=t,this._delegate=e,this._userDataWriter=new Yd(t)}get(t){const e=lf(t);return this._delegate.get(e).then(t=>new sf(this._firestore,new ld(this._firestore._delegate,this._userDataWriter,t._key,t._document,t.metadata,e.converter)))}set(t,e,n){t=lf(t);return n?(Kd("Transaction.set",n),this._delegate.set(t,e,n)):this._delegate.set(t,e),this}update(t,e,n,...r){t=lf(t);return 2===arguments.length?this._delegate.update(t,e):this._delegate.update(t,e,n,...r),this}delete(t){t=lf(t);return this._delegate.delete(t),this}}class Xd{constructor(t){this._delegate=t}set(t,e,n){t=lf(t);return n?(Kd("WriteBatch.set",n),this._delegate.set(t,e,n)):this._delegate.set(t,e),this}update(t,e,n,...r){t=lf(t);return 2===arguments.length?this._delegate.update(t,e):this._delegate.update(t,e,n,...r),this}delete(t){t=lf(t);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Zd{constructor(t,e,n){this._firestore=t,this._userDataWriter=e,this._delegate=n}fromFirestore(t,e){t=new dd(this._firestore._delegate,this._userDataWriter,t._key,t._document,t.metadata,null);return this._delegate.fromFirestore(new of(this._firestore,t),null!=e?e:{})}toFirestore(t,e){return e?this._delegate.toFirestore(t,e):this._delegate.toFirestore(t)}static getInstance(t,e){const n=Zd.INSTANCES;let r=n.get(t);r||(r=new WeakMap,n.set(t,r));let s=r.get(e);return s||(s=new Zd(t,new Yd(t),e),r.set(e,s)),s}}Zd.INSTANCES=new WeakMap;class tf{constructor(t,e){this.firestore=t,this._delegate=e,this._userDataWriter=new Yd(t)}static forPath(t,e,n){if(t.length%2!=0)throw new zr("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${t.canonicalString()} has ${t.length}`);return new tf(e,new cl(e._delegate,n,new Ss(t)))}static forKey(t,e,n){return new tf(e,new cl(e._delegate,n,t))}get id(){return this._delegate.id}get parent(){return new cf(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(t){try{return new cf(this.firestore,fl(this._delegate,t))}catch(t){throw ef(t,"collection()","DocumentReference.collection()")}}isEqual(t){return(t=y(t))instanceof cl&&ml(this._delegate,t)}set(t,e){e=Kd("DocumentReference.set",e);try{return e?Md(this._delegate,t,e):Md(this._delegate,t)}catch(t){throw ef(t,"setDoc()","DocumentReference.set()")}}update(t,e,...n){try{return 1===arguments.length?Pd(this._delegate,t):Pd(this._delegate,t,e,...n)}catch(t){throw ef(t,"updateDoc()","DocumentReference.update()")}}delete(){return Ud(il((t=this._delegate).firestore,El),[new Wi(t._key,Fi.none())]);var t}onSnapshot(...t){var e=nf(t),t=rf(t,t=>new sf(this.firestore,new ld(this.firestore._delegate,this._userDataWriter,t._key,t._document,t.metadata,this._delegate.converter)));return Fd(this._delegate,e,t)}get(t){let e;return e=("cache"===(null==t?void 0:t.source)?Ld:"server"===(null==t?void 0:t.source)?function(e){e=il(e,cl);const n=il(e.firestore,El);return Qc(Il(n),e._key,{source:"server"}).then(t=>qd(n,e,t))}:function(e){e=il(e,cl);const n=il(e.firestore,El);return Qc(Il(n),e._key).then(t=>qd(n,e,t))})(this._delegate),e.then(t=>new sf(this.firestore,new ld(this.firestore._delegate,this._userDataWriter,t._key,t._document,t.metadata,this._delegate.converter)))}withConverter(t){return new tf(this.firestore,t?this._delegate.withConverter(Zd.getInstance(this.firestore,t)):this._delegate.withConverter(null))}}function ef(t,e,n){return t.message=t.message.replace(e,n),t}function nf(t){for(const e of t)if("object"==typeof e&&!Hd(e))return e;return{}}function rf(t,e){let n;return n=Hd(t[0])?t[0]:Hd(t[1])?t[1]:"function"==typeof t[0]?{next:t[0],error:t[1],complete:t[2]}:{next:t[1],error:t[2],complete:t[3]},{next:t=>{n.next&&n.next(e(t))},error:null===(t=n.error)||void 0===t?void 0:t.bind(n),complete:null===(t=n.complete)||void 0===t?void 0:t.bind(n)}}class sf{constructor(t,e){this._firestore=t,this._delegate=e}get ref(){return new tf(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(t){return this._delegate.data(t)}get(t,e){return this._delegate.get(t,e)}isEqual(t){return gd(this._delegate,t._delegate)}}class of extends sf{data(t){t=this._delegate.data(t);return void 0!==t||Kr(),t}}class af{constructor(t,e){this.firestore=t,this._delegate=e,this._userDataWriter=new Yd(t)}where(t,e,n){try{return new af(this.firestore,yd(this._delegate,(r=t,s=e,i=n,r=ud("where",t),new wd(r,s,i))))}catch(t){throw ef(t,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(t,e){try{return new af(this.firestore,yd(this._delegate,([n,r="asc"]=[t,e],n=ud("orderBy",n),new vd(n,r))))}catch(t){throw ef(t,/(orderBy|where)\(\)/,"Query.$1()")}var n,r}limit(t){try{return new af(this.firestore,yd(this._delegate,(ol("limit",e=t),new bd("limit",e,"F"))))}catch(t){throw ef(t,"limit()","Query.limit()")}var e}limitToLast(t){try{return new af(this.firestore,yd(this._delegate,(ol("limitToLast",e=t),new bd("limitToLast",e,"L"))))}catch(t){throw ef(t,"limitToLast()","Query.limitToLast()")}var e}startAt(...t){try{return new af(this.firestore,yd(this._delegate,function(...t){return new Td("startAt",t,!0)}(...t)))}catch(t){throw ef(t,"startAt()","Query.startAt()")}}startAfter(...t){try{return new af(this.firestore,yd(this._delegate,function(...t){return new Td("startAfter",t,!1)}(...t)))}catch(t){throw ef(t,"startAfter()","Query.startAfter()")}}endBefore(...t){try{return new af(this.firestore,yd(this._delegate,function(...t){return new Ed("endBefore",t,!0)}(...t)))}catch(t){throw ef(t,"endBefore()","Query.endBefore()")}}endAt(...t){try{return new af(this.firestore,yd(this._delegate,function(...t){return new Ed("endAt",t,!1)}(...t)))}catch(t){throw ef(t,"endAt()","Query.endAt()")}}isEqual(t){return pl(this._delegate,t._delegate)}get(t){let e;return e=("cache"===(null==t?void 0:t.source)?Od:"server"===(null==t?void 0:t.source)?function(e){e=il(e,ll);const n=il(e.firestore,El),t=Il(n),r=new Rd(n);return Wc(t,e._query,{source:"server"}).then(t=>new fd(n,r,e,t))}:function(e){e=il(e,ll);const n=il(e.firestore,El),t=Il(n),r=new Rd(n);return md(e._query),Wc(t,e._query).then(t=>new fd(n,r,e,t))})(this._delegate),e.then(t=>new uf(this.firestore,new fd(this.firestore._delegate,this._userDataWriter,this._delegate,t._snapshot)))}onSnapshot(...t){var e=nf(t),t=rf(t,t=>new uf(this.firestore,new fd(this.firestore._delegate,this._userDataWriter,this._delegate,t._snapshot)));return Fd(this._delegate,e,t)}withConverter(t){return new af(this.firestore,t?this._delegate.withConverter(Zd.getInstance(this.firestore,t)):this._delegate.withConverter(null))}}class hf{constructor(t,e){this._firestore=t,this._delegate=e}get type(){return this._delegate.type}get doc(){return new of(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class uf{constructor(t,e){this._firestore=t,this._delegate=e}get query(){return new af(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(t=>new of(this._firestore,t))}docChanges(t){return this._delegate.docChanges(t).map(t=>new hf(this._firestore,t))}forEach(e,n){this._delegate.forEach(t=>{e.call(n,new of(this._firestore,t))})}isEqual(t){return gd(this._delegate,t._delegate)}}class cf extends af{constructor(t,e){super(t,e),this.firestore=t,this._delegate=e}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var t=this._delegate.parent;return t?new tf(this.firestore,t):null}doc(t){try{return void 0===t?new tf(this.firestore,gl(this._delegate)):new tf(this.firestore,gl(this._delegate,t))}catch(t){throw ef(t,"doc()","CollectionReference.doc()")}}add(t){return function(t,e){const n=il(t.firestore,El),r=gl(t),s=Dd(t.converter,e);return Ud(n,[jl(Bl(t.firestore),"addDoc",r._key,s,null!==t.converter,{}).toMutation(r._key,Fi.exists(!1))]).then(()=>r)}(this._delegate,t).then(t=>new tf(this.firestore,t))}isEqual(t){return ml(this._delegate,t._delegate)}withConverter(t){return new cf(this.firestore,t?this._delegate.withConverter(Zd.getInstance(this.firestore,t)):this._delegate.withConverter(null))}}function lf(t){return il(t,cl)}const df={Firestore:Wd,GeoPoint:Ol,Timestamp:is,Blob:zd,Transaction:Jd,WriteBatch:Xd,DocumentReference:tf,DocumentSnapshot:sf,Query:af,QueryDocumentSnapshot:of,QuerySnapshot:uf,CollectionReference:cf,FieldPath:class t{constructor(...t){this._delegate=new kl(...t)}static documentId(){return new t(fs.keyField().canonicalString())}isEqual(t){return(t=y(t))instanceof kl&&this._delegate._internalPath.isEqual(t._internalPath)}},FieldValue:class n{constructor(t){this._delegate=t}static serverTimestamp(){const t=new Gl("serverTimestamp");return t._methodName="FieldValue.serverTimestamp",new n(t)}static delete(){const t=new Kl("deleteField");return t._methodName="FieldValue.delete",new n(t)}static arrayUnion(...t){const e=function(...t){return new zl("arrayUnion",t)}(...t);return e._methodName="FieldValue.arrayUnion",new n(e)}static arrayRemove(...t){const e=function(...t){return new Hl("arrayRemove",t)}(...t);return e._methodName="FieldValue.arrayRemove",new n(e)}static increment(t){const e=new Ql("increment",t);return e._methodName="FieldValue.increment",new n(e)}isEqual(t){return this._delegate.isEqual(t._delegate)}},setLogLevel:function(t){t=t,Fr.setLogLevel(t)},CACHE_SIZE_UNLIMITED:-1};bl=e.default,Tl=(t,e)=>new Wd(t,e,new Qd),bl.INTERNAL.registerComponent(new v("firestore-compat",t=>{var e=t.getProvider("app-compat").getImmediate(),t=t.getProvider("firestore").getImmediate();return Tl(e,t)},"PUBLIC").setServiceProps(Object.assign({},df))),bl.registerVersion("@firebase/firestore-compat","0.1.0")}.apply(this,arguments)}catch(t){throw console.error(t),new Error("Cannot instantiate firebase-firestore-compat.js - be sure to load firebase-app.js first.")}}); //# sourceMappingURL=firebase-firestore-compat.js.map