"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[992],{4150:(e,t,n)=>{n.d(t,{BN:()=>lt,H9:()=>oo,P:()=>oj,_M:()=>oW,aQ:()=>ln,aU:()=>oc,rJ:()=>oa,x7:()=>o7});var r,i,s,a,o=n(1972),l=n(7086),u=n(4075),h=n(2213),c=n(7898),d=n(426),f=n(7358),m=n(5714).Buffer;let g="@firebase/firestore";class p{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}p.UNAUTHENTICATED=new p(null),p.GOOGLE_CREDENTIALS=new p("google-credentials-uid"),p.FIRST_PARTY=new p("first-party-uid"),p.MOCK_USER=new p("mock-user");let y="11.0.2",w=new u.Vy("@firebase/firestore");function v(){return w.logLevel}function I(e,...t){if(w.logLevel<=u.$b.DEBUG){let n=t.map(E);w.debug(`Firestore (${y}): ${e}`,...n)}}function _(e,...t){if(w.logLevel<=u.$b.ERROR){let n=t.map(E);w.error(`Firestore (${y}): ${e}`,...n)}}function T(e,...t){if(w.logLevel<=u.$b.WARN){let n=t.map(E);w.warn(`Firestore (${y}): ${e}`,...n)}}function E(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function b(e="Unexpected state"){let t=`FIRESTORE (${y}) INTERNAL ASSERTION FAILED: `+e;throw _(t),Error(t)}let x={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class S extends h.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class D{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class C{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class N{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(p.UNAUTHENTICATED))}shutdown(){}}class k{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class A{constructor(e){this.t=e,this.currentUser=p.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){void 0===this.o||b();let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),i=new D;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new D,e.enqueueRetryable(()=>r(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},a=e=>{I("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(I("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new D)}},0),s()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(I("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?("string"==typeof t.accessToken||b(),new C(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return null===e||"string"==typeof e||b(),new p(e)}}class R{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=p.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);let e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}}class V{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new R(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(p.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class L{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class M{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){void 0===this.o||b();let n=e=>{null!=e.error&&I("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let n=e.token!==this.R;return this.R=e.token,I("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>{I("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){let e=this.A.getImmediate({optional:!0});e?r(e):I("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?("string"==typeof e.token||b(),this.R=e.token,new L(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class O{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Math.floor(256/e.length)*e.length,n="";for(;n.length<20;){let r=function(e){let t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(40);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let e=0;e<40;e++)n[e]=Math.floor(256*Math.random());return n}(0);for(let i=0;i<r.length;++i)n.length<20&&r[i]<t&&(n+=e.charAt(r[i]%e.length))}return n}}function F(e,t){return e<t?-1:e>t?1:0}function P(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}class U{static now(){return U.fromMillis(Date.now())}static fromDate(e){return U.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new U(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new S(x.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new S(x.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?F(this.nanoseconds,e.nanoseconds):F(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class q{static fromTimestamp(e){return new q(e)}static min(){return new q(new U(0,0))}static max(){return new q(new U(0x3afff4417f,0x3b9ac9ff))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class B{constructor(e,t,n){void 0===t?t=0:t>e.length&&b(),void 0===n?n=e.length-t:n>e.length-t&&b(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===B.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof B?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=e.get(r),i=t.get(r);if(n<i)return -1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class K extends B{construct(e,t,n){return new K(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new S(x.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new K(t)}static emptyPath(){return new K([])}}let z=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class $ extends B{construct(e,t,n){return new $(e,t,n)}static isValidIdentifier(e){return z.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),$.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new $(["__name__"])}static fromServerFormat(e){let t=[],n="",r=0,i=()=>{if(0===n.length)throw new S(x.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},s=!1;for(;r<e.length;){let t=e[r];if("\\"===t){if(r+1===e.length)throw new S(x.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new S(x.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new S(x.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new $(t)}static emptyPath(){return new $([])}}class G{constructor(e){this.path=e}static fromPath(e){return new G(K.fromString(e))}static fromName(e){return new G(K.fromString(e).popFirst(5))}static empty(){return new G(K.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===K.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return K.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new G(new K(e.slice()))}}class j{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Q(e){return e.fields.find(e=>2===e.kind)}function W(e){return e.fields.filter(e=>2!==e.kind)}j.UNKNOWN_ID=-1;class H{constructor(e,t){this.fieldPath=e,this.kind=t}}class J{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new J(0,Z.min())}}function Y(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;return new Z(q.fromTimestamp(1e9===r?new U(n+1,0):new U(n,r)),G.empty(),t)}function X(e){return new Z(e.readTime,e.key,-1)}class Z{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Z(q.min(),G.empty(),-1)}static max(){return new Z(q.max(),G.empty(),-1)}}function ee(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:0!==(n=G.comparator(e.documentKey,t.documentKey))?n:F(e.largestBatchId,t.largestBatchId)}let et="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class en{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function er(e){if(e.code!==x.FAILED_PRECONDITION||e.message!==et)throw e;I("LocalStore","Unexpectedly lost primary lease")}class ei{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&b(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new ei((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof ei?t:ei.resolve(t)}catch(e){return ei.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):ei.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):ei.reject(t)}static resolve(e){return new ei((t,n)=>{t(e)})}static reject(e){return new ei((t,n)=>{n(e)})}static waitFor(e){return new ei((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=ei.resolve(!1);for(let n of e)t=t.next(e=>e?ei.resolve(e):n());return t}static forEach(e,t){let n=[];return e.forEach((e,r)=>{n.push(t.call(this,e,r))}),this.waitFor(n)}static mapArray(e,t){return new ei((n,r)=>{let i=e.length,s=Array(i),a=0;for(let o=0;o<i;o++){let l=o;t(e[l]).next(e=>{s[l]=e,++a===i&&n(s)},e=>r(e))}})}static doWhile(e,t){return new ei((n,r)=>{let i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}class es{static open(e,t,n,r){try{return new es(t,e.transaction(r,n))}catch(e){throw new eu(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.V=new D,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{t.error?this.V.reject(new eu(e,t.error)):this.V.resolve()},this.transaction.onerror=t=>{let n=em(t.target.error);this.V.reject(new eu(e,n))}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(I("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){let e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){return new ec(this.transaction.objectStore(e))}}class ea{static delete(e){return I("SimpleDb","Removing database:",e),ed(window.indexedDB.deleteDatabase(e)).toPromise()}static p(){if(!(0,h.zW)())return!1;if(ea.S())return!0;let e=(0,h.ZQ)(),t=ea.D(e),n=eo(e);return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||0<t&&t<10||0<n&&n<4.5)}static S(){var e;return void 0!==f&&"YES"===(null===(e=f.__PRIVATE_env)||void 0===e?void 0:e.v)}static C(e,t){return e.store(t)}static D(e){let t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i);return Number(t?t[1].split("_").slice(0,2).join("."):"-1")}constructor(e,t,n){this.name=e,this.version=t,this.F=n,12.2===ea.D((0,h.ZQ)())&&_("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.")}async M(e){return this.db||(I("SimpleDb","Opening database:",this.name),this.db=await new Promise((t,n)=>{let r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{t(e.target.result)},r.onblocked=()=>{n(new eu(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{let r=t.target.error;"VersionError"===r.name?n(new S(x.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===r.name?n(new S(x.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+r)):n(new eu(e,r))},r.onupgradeneeded=e=>{I("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);let t=e.target.result;this.F.O(t,r.transaction,e.oldVersion,this.version).next(()=>{I("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(e){this.N=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){let i="readonly"===t,s=0;for(;;){++s;try{this.db=await this.M(e);let t=es.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.g(),e)).catch(e=>(t.abort(e),ei.reject(e))).toPromise();return s.catch(()=>{}),await t.m,s}catch(t){let e="FirebaseError"!==t.name&&s<3;if(I("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}}function eo(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class el{constructor(e){this.B=e,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(e){this.B=e}done(){this.k=!0}$(e){this.q=e}delete(){return ed(this.B.delete())}}class eu extends S{constructor(e,t){super(x.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function eh(e){return"IndexedDbTransactionError"===e.name}class ec{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(I("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(I("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),ed(n)}add(e){return I("SimpleDb","ADD",this.store.name,e,e),ed(this.store.add(e))}get(e){return ed(this.store.get(e)).next(t=>(void 0===t&&(t=null),I("SimpleDb","GET",this.store.name,e,t),t))}delete(e){return I("SimpleDb","DELETE",this.store.name,e),ed(this.store.delete(e))}count(){return I("SimpleDb","COUNT",this.store.name),ed(this.store.count())}U(e,t){let n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){let e=r.getAll(n.range);return new ei((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),t=[];return this.W(e,(e,n)=>{t.push(n)}).next(()=>t)}}G(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new ei((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}j(e,t){I("SimpleDb","DELETE ALL",this.store.name);let n=this.options(e,t);n.H=!1;let r=this.cursor(n);return this.W(r,(e,t,n)=>n.delete())}J(e,t){let n;t?n=e:(n={},t=e);let r=this.cursor(n);return this.W(r,t)}Y(e){let t=this.cursor({});return new ei((n,r)=>{t.onerror=e=>{r(em(e.target.error))},t.onsuccess=t=>{let r=t.target.result;r?e(r.primaryKey,r.value).next(e=>{e?r.continue():n()}):n()}})}W(e,t){let n=[];return new ei((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{let i=e.target.result;if(!i)return void r();let s=new el(i),a=t(i.primaryKey,i.value,s);if(a instanceof ei){let e=a.catch(e=>(s.done(),ei.reject(e)));n.push(e)}s.isDone?r():null===s.K?i.continue():i.continue(s.K)}}).next(()=>ei.waitFor(n))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){let n=this.store.index(e.index);return e.H?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function ed(e){return new ei((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{n(em(e.target.error))}})}let ef=!1;function em(e){let t=ea.D((0,h.ZQ)());if(t>=12.2&&t<13){let t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){let e=new S("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return ef||(ef=!0,setTimeout(()=>{throw e},0)),e}}return e}class eg{constructor(e,t){this.asyncQueue=e,this.Z=t,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){I("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{I("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){eh(e)?I("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await er(e)}await this.X(6e4)})}}class ep{constructor(e,t){this.localStore=e,this.persistence=t}async ee(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.te(t,e))}te(e,t){let n=new Set,r=t,i=!0;return ei.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!n.has(t))return I("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next(e=>{r-=e,n.add(t)});i=!1})).next(()=>t-r)}ne(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next(n=>{let i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next(()=>this.re(r,n)).next(n=>(I("IndexBackfiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n))).next(()=>i.size)}))}re(e,t){let n=e;return t.changes.forEach((e,t)=>{let r=X(t);ee(r,n)>0&&(n=r)}),new Z(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ey{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.se&&this.se(e),e}}function ew(e){return null==e}function ev(e){return 0===e&&1/e==-1/0}function eI(e){return"number"==typeof e&&Number.isInteger(e)&&!ev(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function e_(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let n=t,r=e.length;for(let t=0;t<r;t++){let r=e.charAt(t);switch(r){case"\0":n+="\x01\x10";break;case"\x01":n+="\x01\x11";break;default:n+=r}}return n}(e.get(n),t);return t+"\x01\x01"}function eT(e){let t=e.length;if(t>=2||b(),2===t)return"\x01"===e.charAt(0)&&"\x01"===e.charAt(1)||b(),K.emptyPath();let n=t-2,r=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>n)&&b(),e.charAt(t+1)){case"\x01":let a;let o=e.substring(s,t);0===i.length?a=o:(i+=o,a=i,i=""),r.push(a);break;case"\x10":i+=e.substring(s,t),i+="\0";break;case"\x11":i+=e.substring(s,t+1);break;default:b()}s=t+2}return new K(r)}ey.oe=-1;let eE=["userId","batchId"],eb={},ex=["prefixPath","collectionGroup","readTime","documentId"],eS=["prefixPath","collectionGroup","documentId"],eD=["collectionGroup","readTime","prefixPath","documentId"],eC=["canonicalId","targetId"],eN=["targetId","path"],ek=["path","targetId"],eA=["collectionId","parent"],eR=["indexId","uid"],eV=["uid","sequenceNumber"],eL=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],eM=["indexId","uid","orderedDocumentKey"],eO=["userId","collectionPath","documentId"],eF=["userId","collectionPath","largestBatchId"],eP=["userId","collectionGroup","largestBatchId"],eU=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],eq=[...eU,"documentOverlays"],eB=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],eK=[...eB,"indexConfiguration","indexState","indexEntries"],ez=[...eK,"globals"];class e$ extends en{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function eG(e,t){return ea.C(e._e,t)}function ej(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function eQ(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function eW(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class eH{constructor(e,t){this.comparator=e,this.root=t||eY.EMPTY}insert(e,t){return new eH(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,eY.BLACK,null,null))}remove(e){return new eH(this.comparator,this.root.remove(e,this.comparator).copy(null,null,eY.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){let r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return -1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new eJ(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new eJ(this.root,e,this.comparator,!1)}getReverseIterator(){return new eJ(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new eJ(this.root,e,this.comparator,!0)}}class eJ{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class eY{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:eY.RED,this.left=null!=r?r:eY.EMPTY,this.right=null!=i?i:eY.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new eY(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this,i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp()}removeMin(){if(this.left.isEmpty())return eY.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()}remove(e,t){let n,r=this;if(0>t(e,r.key))r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return eY.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}rotateLeft(){let e=this.copy(null,null,eY.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,eY.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed()||this.right.isRed())throw b();let e=this.left.check();if(e!==this.right.check())throw b();return e+(this.isRed()?0:1)}}eY.EMPTY=null,eY.RED=!0,eY.BLACK=!1,eY.EMPTY=new class{constructor(){this.size=0}get key(){throw b()}get value(){throw b()}get color(){throw b()}get left(){throw b()}get right(){throw b()}copy(e,t,n,r,i){return this}insert(e,t,n){return new eY(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class eX{constructor(e){this.comparator=e,this.data=new eH(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,n)=>(e(t),!1))}forEachInRange(e,t){let n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){let r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new eZ(this.data.getIterator())}getIteratorFrom(e){return new eZ(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof eX)||this.size!==e.size)return!1;let t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new eX(this.comparator);return t.data=e,t}}class eZ{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function e0(e){return e.hasNext()?e.getNext():void 0}class e1{constructor(e){this.fields=e,e.sort($.comparator)}static empty(){return new e1([])}unionWith(e){let t=new eX($.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new e1(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return P(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class e2 extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class e5{constructor(e){this.binaryString=e}static fromBase64String(e){return new e5(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new e2("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new e5(function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e))}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return btoa(this.binaryString)}toUint8Array(){return function(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return F(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}e5.EMPTY_BYTE_STRING=new e5("");let e4=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function e8(e){if(e||b(),"string"==typeof e){let t=0,n=e4.exec(e);if(n||b(),n[1]){let e=n[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:e3(e.seconds),nanos:e3(e.nanos)}}function e3(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function e6(e){return"string"==typeof e?e5.fromBase64String(e):e5.fromUint8Array(e)}function e9(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function e7(e){let t=e.mapValue.fields.__previous_value__;return e9(t)?e7(t):t}function te(e){let t=e8(e.mapValue.fields.__local_write_time__.timestampValue);return new U(t.seconds,t.nanos)}class tt{constructor(e,t,n,r,i,s,a,o,l){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l}}class tn{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new tn("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof tn&&e.projectId===this.projectId&&e.database===this.database}}let tr={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},ti={nullValue:"NULL_VALUE"};function ts(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?e9(e)?4:tI(e)?0x1fffffffffffff:tw(e)?10:11:b()}function ta(e,t){if(e===t)return!0;let n=ts(e);if(n!==ts(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return te(e).isEqual(te(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let n=e8(e.timestampValue),r=e8(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return e6(e.bytesValue).isEqual(e6(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return e3(e.geoPointValue.latitude)===e3(t.geoPointValue.latitude)&&e3(e.geoPointValue.longitude)===e3(t.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return e3(e.integerValue)===e3(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=e3(e.doubleValue),r=e3(t.doubleValue);return n===r?ev(n)===ev(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return P(e.arrayValue.values||[],t.arrayValue.values||[],ta);case 10:case 11:return function(e,t){let n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(ej(n)!==ej(r))return!1;for(let e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!ta(n[e],r[e])))return!1;return!0}(e,t);default:return b()}}function to(e,t){return void 0!==(e.values||[]).find(e=>ta(e,t))}function tl(e,t){if(e===t)return 0;let n=ts(e),r=ts(t);if(n!==r)return F(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return F(e.booleanValue,t.booleanValue);case 2:return function(e,t){let n=e3(e.integerValue||e.doubleValue),r=e3(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return tu(e.timestampValue,t.timestampValue);case 4:return tu(te(e),te(t));case 5:return F(e.stringValue,t.stringValue);case 6:return function(e,t){let n=e6(e),r=e6(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){let n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){let t=F(n[e],r[e]);if(0!==t)return t}return F(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let n=F(e3(e.latitude),e3(t.latitude));return 0!==n?n:F(e3(e.longitude),e3(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return th(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,i,s;let a=e.fields||{},o=t.fields||{},l=null===(n=a.value)||void 0===n?void 0:n.arrayValue,u=null===(r=o.value)||void 0===r?void 0:r.arrayValue,h=F((null===(i=null==l?void 0:l.values)||void 0===i?void 0:i.length)||0,(null===(s=null==u?void 0:u.values)||void 0===s?void 0:s.length)||0);return 0!==h?h:th(l,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===tr.mapValue&&t===tr.mapValue)return 0;if(e===tr.mapValue)return 1;if(t===tr.mapValue)return -1;let n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){let t=F(r[e],s[e]);if(0!==t)return t;let a=tl(n[r[e]],i[s[e]]);if(0!==a)return a}return F(r.length,s.length)}(e.mapValue,t.mapValue);default:throw b()}}function tu(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return F(e,t);let n=e8(e),r=e8(t),i=F(n.seconds,r.seconds);return 0!==i?i:F(n.nanos,r.nanos)}function th(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=tl(n[e],r[e]);if(t)return t}return F(n.length,r.length)}function tc(e){var t,n;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){let t=e8(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?e6(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,G.fromName(t).toString()):"geoPointValue"in e?(n=e.geoPointValue,`geo(${n.latitude},${n.longitude})`):"arrayValue"in e?function(e){let t="[",n=!0;for(let r of e.values||[])n?n=!1:t+=",",t+=tc(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),n="{",r=!0;for(let i of t)r?r=!1:n+=",",n+=`${i}:${tc(e.fields[i])}`;return n+"}"}(e.mapValue):b()}function td(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function tf(e){return!!e&&"integerValue"in e}function tm(e){return!!e&&"arrayValue"in e}function tg(e){return!!e&&"nullValue"in e}function tp(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function ty(e){return!!e&&"mapValue"in e}function tw(e){var t,n;return"__vector__"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function tv(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){let t={mapValue:{fields:{}}};return eQ(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=tv(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=tv(e.arrayValue.values[n]);return t}return Object.assign({},e)}function tI(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}let t_={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function tT(e,t){let n=tl(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function tE(e,t){let n=tl(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class tb{constructor(e){this.value=e}static empty(){return new tb({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!ty(t=(t.mapValue.fields||{})[e.get(n)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=tv(t)}setAll(e){let t=$.emptyPath(),n={},r=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){let e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=tv(e):r.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){let t=this.field(e.popLast());ty(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ta(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];ty(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){for(let r of(eQ(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new tb(tv(this.value))}}class tx{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new tx(e,0,q.min(),q.min(),q.min(),tb.empty(),0)}static newFoundDocument(e,t,n,r){return new tx(e,1,t,q.min(),n,r,0)}static newNoDocument(e,t){return new tx(e,2,t,q.min(),q.min(),tb.empty(),0)}static newUnknownDocument(e,t){return new tx(e,3,t,q.min(),q.min(),tb.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(q.min())&&(2===this.documentType||0===this.documentType)&&(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=tb.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=tb.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=q.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof tx&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new tx(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class tS{constructor(e,t){this.position=e,this.inclusive=t}}function tD(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){let s=t[i],a=e.position[i];if(r=s.field.isKeyField()?G.comparator(G.fromName(a.referenceValue),n.key):tl(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function tC(e,t){if(null===e)return null===t;if(null===t||e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!ta(e.position[n],t.position[n]))return!1;return!0}class tN{constructor(e,t="asc"){this.field=e,this.dir=t}}class tk{}class tA extends tk{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new tP(e,t,n):"array-contains"===t?new tK(e,n):"in"===t?new tz(e,n):"not-in"===t?new t$(e,n):"array-contains-any"===t?new tG(e,n):new tA(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new tU(e,n):new tq(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(tl(t,this.value)):null!==t&&ts(this.value)===ts(t)&&this.matchesComparison(tl(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return b()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tR extends tk{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new tR(e,t)}matches(e){return tV(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function tV(e){return"and"===e.op}function tL(e){return"or"===e.op}function tM(e){return tO(e)&&tV(e)}function tO(e){for(let t of e.filters)if(t instanceof tR)return!1;return!0}function tF(e,t){let n=e.filters.concat(t);return tR.create(n,e.op)}class tP extends tA{constructor(e,t,n){super(e,t,n),this.key=G.fromName(n.referenceValue)}matches(e){let t=G.comparator(e.key,this.key);return this.matchesComparison(t)}}class tU extends tA{constructor(e,t){super(e,"in",t),this.keys=tB("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class tq extends tA{constructor(e,t){super(e,"not-in",t),this.keys=tB("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function tB(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>G.fromName(e.referenceValue))}class tK extends tA{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return tm(t)&&to(t.arrayValue,this.value)}}class tz extends tA{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&to(this.value.arrayValue,t)}}class t$ extends tA{constructor(e,t){super(e,"not-in",t)}matches(e){if(to(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&!to(this.value.arrayValue,t)}}class tG extends tA{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!tm(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>to(this.value.arrayValue,e))}}class tj{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.ue=null}}function tQ(e,t=null,n=[],r=[],i=null,s=null,a=null){return new tj(e,t,n,r,i,s,a)}function tW(e){if(null===e.ue){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(e=>(function e(t){if(t instanceof tA)return t.field.canonicalString()+t.op.toString()+tc(t.value);if(tM(t))return t.filters.map(t=>e(t)).join(",");{let n=t.filters.map(t=>e(t)).join(",");return`${t.op}(${n})`}})(e)).join(","),t+="|ob:",t+=e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),null==e.limit||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>tc(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>tc(e)).join(",")),e.ue=t}return e.ue}function tH(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++){var n,r;if(n=e.orderBy[i],r=t.orderBy[i],!(n.dir===r.dir&&n.field.isEqual(r.field)))return!1}if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!function e(t,n){return t instanceof tA?n instanceof tA&&t.op===n.op&&t.field.isEqual(n.field)&&ta(t.value,n.value):t instanceof tR?n instanceof tR&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,i)=>t&&e(r,n.filters[i]),!0):void b()}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!tC(e.startAt,t.startAt)&&tC(e.endAt,t.endAt)}function tJ(e){return G.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function tY(e,t){return e.filters.filter(e=>e instanceof tA&&e.field.isEqual(t))}function tX(e,t,n){let r=ti,i=!0;for(let n of tY(e,t)){let e=ti,t=!0;switch(n.op){case"<":case"<=":var s;e="nullValue"in(s=n.value)?ti:"booleanValue"in s?{booleanValue:!1}:"integerValue"in s||"doubleValue"in s?{doubleValue:NaN}:"timestampValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in s?{stringValue:""}:"bytesValue"in s?{bytesValue:""}:"referenceValue"in s?td(tn.empty(),G.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?tw(s)?t_:{mapValue:{}}:b();break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=ti}0>tT({value:r,inclusive:i},{value:e,inclusive:t})&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];0>tT({value:r,inclusive:i},{value:e,inclusive:n.inclusive})&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}function tZ(e,t,n){let r=tr,i=!0;for(let n of tY(e,t)){let e=tr,t=!0;switch(n.op){case">=":case">":var s;e="nullValue"in(s=n.value)?{booleanValue:!1}:"booleanValue"in s?{doubleValue:NaN}:"integerValue"in s||"doubleValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in s?{stringValue:""}:"stringValue"in s?{bytesValue:""}:"bytesValue"in s?td(tn.empty(),G.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?t_:"mapValue"in s?tw(s)?{mapValue:{}}:tr:b(),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=tr}tE({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];tE({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}class t0{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function t1(e){return new t0(e)}function t2(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function t5(e){return null!==e.collectionGroup}function t4(e){if(null===e.ce){let t;e.ce=[];let n=new Set;for(let t of e.explicitOrderBy)e.ce.push(t),n.add(t.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(t=new eX($.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t).forEach(t=>{n.has(t.canonicalString())||t.isKeyField()||e.ce.push(new tN(t,r))}),n.has($.keyField().canonicalString())||e.ce.push(new tN($.keyField(),r))}return e.ce}function t8(e){return e.le||(e.le=function(e,t){if("F"===e.limitType)return tQ(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{let t="desc"===e.dir?"asc":"desc";return new tN(e.field,t)});let n=e.endAt?new tS(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new tS(e.startAt.position,e.startAt.inclusive):null;return tQ(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(e,t4(e))),e.le}function t3(e,t){let n=e.filters.concat([t]);return new t0(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function t6(e,t,n){return new t0(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function t9(e,t){return tH(t8(e),t8(t))&&e.limitType===t.limitType}function t7(e){return`${tW(t8(e))}|lt:${e.limitType}`}function ne(e){var t;let n;return`Query(target=${n=(t=t8(e)).path.canonicalString(),null!==t.collectionGroup&&(n+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(n+=`, filters: [${t.filters.map(e=>(function e(t){return t instanceof tA?`${t.field.canonicalString()} ${t.op} ${tc(t.value)}`:t instanceof tR?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),null==t.limit||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(e=>tc(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>tc(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function nt(e,t){return t.isFoundDocument()&&function(e,t){let n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):G.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(let n of t4(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(let n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&(!e.startAt||!!function(e,t,n){let r=tD(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,t4(e),t))&&(!e.endAt||!!function(e,t,n){let r=tD(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,t4(e),t))}function nn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function nr(e){return(t,n)=>{let r=!1;for(let i of t4(e)){let e=function(e,t,n){let r=e.field.isKeyField()?G.comparator(t.key,n.key):function(e,t,n){let r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?tl(r,i):b()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return b()}}(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}class ni{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n){for(let[t,r]of n)if(this.equalsFn(t,e))return r}}has(e){return void 0!==this.get(e)}set(e,t){let n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){eQ(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){return eW(this.inner)}size(){return this.innerSize}}let ns=new eH(G.comparator),na=new eH(G.comparator);function no(...e){let t=na;for(let n of e)t=t.insert(n.key,n);return t}function nl(e){let t=na;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function nu(){return new ni(e=>e.toString(),(e,t)=>e.isEqual(t))}let nh=new eH(G.comparator),nc=new eX(G.comparator);function nd(...e){let t=nc;for(let n of e)t=t.add(n);return t}let nf=new eX(F);function nm(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:ev(t)?"-0":t}}function ng(e){return{integerValue:""+e}}function np(e,t){return eI(t)?ng(t):nm(e,t)}class ny{constructor(){this._=void 0}}function nw(e,t){return e instanceof nb?tf(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}class nv extends ny{}class nI extends ny{constructor(e){super(),this.elements=e}}function n_(e,t){let n=nS(t);for(let t of e.elements)n.some(e=>ta(e,t))||n.push(t);return{arrayValue:{values:n}}}class nT extends ny{constructor(e){super(),this.elements=e}}function nE(e,t){let n=nS(t);for(let t of e.elements)n=n.filter(e=>!ta(e,t));return{arrayValue:{values:n}}}class nb extends ny{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function nx(e){return e3(e.integerValue||e.doubleValue)}function nS(e){return tm(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class nD{constructor(e,t){this.field=e,this.transform=t}}class nC{constructor(e,t){this.version=e,this.transformResults=t}}class nN{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new nN}static exists(e){return new nN(void 0,e)}static updateTime(e){return new nN(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function nk(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class nA{}function nR(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new nq(e.key,nN.none()):new nM(e.key,e.data,nN.none());{let n=e.data,r=tb.empty(),i=new eX($.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new nO(e.key,r,new e1(i.toArray()),nN.none())}}function nV(e,t,n,r){return e instanceof nM?function(e,t,n,r){if(!nk(e.precondition,t))return n;let i=e.value.clone(),s=nU(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof nO?function(e,t,n,r){if(!nk(e.precondition,t))return n;let i=nU(e.fieldTransforms,r,t),s=t.data;return(s.setAll(nF(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n)?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):nk(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function nL(e,t){var n,r;return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||!(!n||!r)&&P(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof nI&&r instanceof nI||n instanceof nT&&r instanceof nT?P(n.elements,r.elements,ta):n instanceof nb&&r instanceof nb?ta(n.Pe,r.Pe):n instanceof nv&&r instanceof nv)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class nM extends nA{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class nO extends nA{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function nF(e){let t=new Map;return e.fieldMask.fields.forEach(n=>{if(!n.isEmpty()){let r=e.data.field(n);t.set(n,r)}}),t}function nP(e,t,n){var r;let i=new Map;e.length===n.length||b();for(let s=0;s<n.length;s++){let a=e[s],o=a.transform,l=t.data.field(a.field);i.set(a.field,(r=n[s],o instanceof nI?n_(o,l):o instanceof nT?nE(o,l):r))}return i}function nU(e,t,n){let r=new Map;for(let i of e){let e=i.transform,s=n.data.field(i.field);r.set(i.field,e instanceof nv?function(e,t){let n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&e9(t)&&(t=e7(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(t,s):e instanceof nI?n_(e,s):e instanceof nT?nE(e,s):function(e,t){let n=nw(e,t),r=nx(n)+nx(e.Pe);return tf(n)&&tf(e.Pe)?ng(r):nm(e.serializer,r)}(e,s))}return r}class nq extends nA{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class nB extends nA{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class nK{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let i=this.mutations[t];if(i.key.isEqual(e.key)){var r;r=n[t],i instanceof nM?function(e,t,n){let r=e.value.clone(),i=nP(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(i,e,r):i instanceof nO?function(e,t,n){if(!nk(e.precondition,t))return void t.convertToUnknownDocument(n.version);let r=nP(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(nF(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(i,e,r):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,e,r)}}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=nV(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=nV(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=nu();return this.mutations.forEach(r=>{let i=e.get(r.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=nR(s,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(q.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),nd())}isEqual(e){return this.batchId===e.batchId&&P(this.mutations,e.mutations,(e,t)=>nL(e,t))&&P(this.baseMutations,e.baseMutations,(e,t)=>nL(e,t))}}class nz{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){e.mutations.length===n.length||b();let r=nh,i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new nz(e,t,n,r)}}class n${constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{
      largestBatchId: ${this.largestBatchId},
      mutation: ${this.mutation.toString()}
    }`}}class nG{constructor(e,t){this.count=e,this.unchangedNames=t}}function nj(e){if(void 0===e)return _("GRPC error has no .code"),x.UNKNOWN;switch(e){case r.OK:return x.OK;case r.CANCELLED:return x.CANCELLED;case r.UNKNOWN:return x.UNKNOWN;case r.DEADLINE_EXCEEDED:return x.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return x.RESOURCE_EXHAUSTED;case r.INTERNAL:return x.INTERNAL;case r.UNAVAILABLE:return x.UNAVAILABLE;case r.UNAUTHENTICATED:return x.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return x.INVALID_ARGUMENT;case r.NOT_FOUND:return x.NOT_FOUND;case r.ALREADY_EXISTS:return x.ALREADY_EXISTS;case r.PERMISSION_DENIED:return x.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return x.FAILED_PRECONDITION;case r.ABORTED:return x.ABORTED;case r.OUT_OF_RANGE:return x.OUT_OF_RANGE;case r.UNIMPLEMENTED:return x.UNIMPLEMENTED;case r.DATA_LOSS:return x.DATA_LOSS;default:return b()}}(i=r||(r={}))[i.OK=0]="OK",i[i.CANCELLED=1]="CANCELLED",i[i.UNKNOWN=2]="UNKNOWN",i[i.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",i[i.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",i[i.NOT_FOUND=5]="NOT_FOUND",i[i.ALREADY_EXISTS=6]="ALREADY_EXISTS",i[i.PERMISSION_DENIED=7]="PERMISSION_DENIED",i[i.UNAUTHENTICATED=16]="UNAUTHENTICATED",i[i.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",i[i.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",i[i.ABORTED=10]="ABORTED",i[i.OUT_OF_RANGE=11]="OUT_OF_RANGE",i[i.UNIMPLEMENTED=12]="UNIMPLEMENTED",i[i.INTERNAL=13]="INTERNAL",i[i.UNAVAILABLE=14]="UNAVAILABLE",i[i.DATA_LOSS=15]="DATA_LOSS";let nQ=new c.jz([0xffffffff,0xffffffff],0);function nW(e){let t=(new TextEncoder).encode(e),n=new c.VV;return n.update(t),new Uint8Array(n.digest())}function nH(e){let t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new c.jz([n,r],0),new c.jz([i,s],0)]}class nJ{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new nY(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new nY(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new nY(`Invalid padding when bitmap length is 0: ${t}`);this.Te=8*e.length-t,this.Ie=c.jz.fromNumber(this.Te)}Ee(e,t,n){let r=e.add(t.multiply(c.jz.fromNumber(n)));return 1===r.compare(nQ)&&(r=new c.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Ie).toNumber()}de(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Te)return!1;let[t,n]=nH(nW(e));for(let e=0;e<this.hashCount;e++){let r=this.Ee(t,n,e);if(!this.de(r))return!1}return!0}static create(e,t,n){let r=new nJ(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);return n.forEach(e=>r.insert(e)),r}insert(e){if(0===this.Te)return;let[t,n]=nH(nW(e));for(let e=0;e<this.hashCount;e++){let r=this.Ee(t,n,e);this.Ae(r)}}Ae(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class nY extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class nX{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let r=new Map;return r.set(e,nZ.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new nX(q.min(),r,new eH(F),ns,nd())}}class nZ{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new nZ(n,t,nd(),nd(),nd())}}class n0{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class n1{constructor(e,t){this.targetId=e,this.me=t}}class n2{constructor(e,t,n=e5.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class n5{constructor(){this.fe=0,this.ge=n3(),this.pe=e5.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){e.approximateByteSize()>0&&(this.we=!0,this.pe=e)}ve(){let e=nd(),t=nd(),n=nd();return this.ge.forEach((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:b()}}),new nZ(this.pe,this.ye,e,t,n)}Ce(){this.we=!1,this.ge=n3()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){this.fe-=1,this.fe>=0||b()}Ne(){this.we=!0,this.ye=!0}}class n4{constructor(e){this.Le=e,this.Be=new Map,this.ke=ns,this.qe=n8(),this.Qe=n8(),this.Ke=new eH(F)}$e(e){for(let t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.Ue(t,e.Ve):this.We(t,e.key,e.Ve);for(let t of e.removedTargetIds)this.We(t,e.key,e.Ve)}Ge(e){this.forEachTarget(e,t=>{let n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.De(e.resumeToken);break;case 1:n.Oe(),n.Se||n.Ce(),n.De(e.resumeToken);break;case 2:n.Oe(),n.Se||this.removeTarget(t);break;case 3:this.je(t)&&(n.Ne(),n.De(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.De(e.resumeToken));break;default:b()}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Be.forEach((e,n)=>{this.je(n)&&t(n)})}Je(e){let t=e.targetId,n=e.me.count,r=this.Ye(t);if(r){let i=r.target;if(tJ(i)){if(0===n){let e=new G(i.path);this.We(t,e,tx.newNoDocument(e,q.min()))}else 1===n||b()}else{let r=this.Ze(t);if(r!==n){let n=this.Xe(e),i=n?this.et(n,e,r):1;0!==i&&(this.He(t),this.Ke=this.Ke.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}Xe(e){let t,n;let r=e.me.unchangedNames;if(!r||!r.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=r;try{t=e6(i).toUint8Array()}catch(e){if(e instanceof e2)return T("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{n=new nJ(t,s,a)}catch(e){return T(e instanceof nY?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===n.Te?null:n}et(e,t,n){return t.me.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){let n=this.Le.getRemoteKeysForTarget(t),r=0;return n.forEach(n=>{let i=this.Le.nt(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.We(t,n,null),r++)}),r}it(e){let t=new Map;this.Be.forEach((n,r)=>{let i=this.Ye(r);if(i){if(n.current&&tJ(i.target)){let t=new G(i.target.path);this.st(t).has(r)||this.ot(r,t)||this.We(r,t,tx.newNoDocument(t,e))}n.be&&(t.set(r,n.ve()),n.Ce())}});let n=nd();this.Qe.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{let t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.ke.forEach((t,n)=>n.setReadTime(e));let r=new nX(e,t,this.Ke,this.ke,n);return this.ke=ns,this.qe=n8(),this.Qe=n8(),this.Ke=new eH(F),r}Ue(e,t){if(!this.je(e))return;let n=this.ot(e,t.key)?2:0;this.ze(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e)),this.Qe=this.Qe.insert(t.key,this._t(t.key).add(e))}We(e,t,n){if(!this.je(e))return;let r=this.ze(e);this.ot(e,t)?r.Fe(t,1):r.Me(t),this.Qe=this.Qe.insert(t,this._t(t).delete(e)),this.Qe=this.Qe.insert(t,this._t(t).add(e)),n&&(this.ke=this.ke.insert(t,n))}removeTarget(e){this.Be.delete(e)}Ze(e){let t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.ze(e).xe()}ze(e){let t=this.Be.get(e);return t||(t=new n5,this.Be.set(e,t)),t}_t(e){let t=this.Qe.get(e);return t||(t=new eX(F),this.Qe=this.Qe.insert(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new eX(F),this.qe=this.qe.insert(e,t)),t}je(e){let t=null!==this.Ye(e);return t||I("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){let t=this.Be.get(e);return t&&t.Se?null:this.Le.ut(e)}He(e){this.Be.set(e,new n5),this.Le.getRemoteKeysForTarget(e).forEach(t=>{this.We(e,t,null)})}ot(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function n8(){return new eH(G.comparator)}function n3(){return new eH(G.comparator)}let n6={asc:"ASCENDING",desc:"DESCENDING"},n9={"<":"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"},n7={and:"AND",or:"OR"};class re{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function rt(e,t){return e.useProto3Json||null==t?t:{value:t}}function rn(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function rr(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function ri(e){return e||b(),q.fromTimestamp(function(e){let t=e8(e);return new U(t.seconds,t.nanos)}(e))}function rs(e,t){return ra(e,t).canonicalString()}function ra(e,t){let n=new K(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function ro(e){let t=K.fromString(e);return rE(t)||b(),t}function rl(e,t){return rs(e.databaseId,t.path)}function ru(e,t){let n=ro(t);if(n.get(1)!==e.databaseId.projectId)throw new S(x.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new S(x.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new G(rf(n))}function rh(e,t){return rs(e.databaseId,t)}function rc(e){let t=ro(e);return 4===t.length?K.emptyPath():rf(t)}function rd(e){return new K(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function rf(e){return e.length>4&&"documents"===e.get(4)||b(),e.popFirst(5)}function rm(e,t,n){return{name:rl(e,t),fields:n.value.mapValue.fields}}function rg(e,t,n){let r=ru(e,t.name),i=ri(t.updateTime),s=t.createTime?ri(t.createTime):q.min(),a=new tb({mapValue:{fields:t.fields}}),o=tx.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function rp(e,t){var n;let r;if(t instanceof nM)r={update:rm(e,t.key,t.value)};else if(t instanceof nq)r={delete:rl(e,t.key)};else if(t instanceof nO)r={update:rm(e,t.key,t.data),updateMask:function(e){let t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof nB))return b();r={verify:rl(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof nv)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof nI)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof nT)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof nb)return{fieldPath:t.field.canonicalString(),increment:n.Pe};throw b()})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:rn(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:b()),r}function ry(e,t){var n;let r=t.currentDocument?void 0!==(n=t.currentDocument).updateTime?nN.updateTime(ri(n.updateTime)):void 0!==n.exists?nN.exists(n.exists):nN.none():nN.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let n;return n=null,"setToServerValue"in t?("REQUEST_TIME"===t.setToServerValue||b(),n=new nv):"appendMissingElements"in t?n=new nI(t.appendMissingElements.values||[]):"removeAllFromArray"in t?n=new nT(t.removeAllFromArray.values||[]):"increment"in t?n=new nb(e,t.increment):b(),new nD($.fromServerFormat(t.fieldPath),n)}):[];if(t.update){t.update.name;let n=ru(e,t.update.name),s=new tb({mapValue:{fields:t.update.fields}});return t.updateMask?new nO(n,s,new e1((t.updateMask.fieldPaths||[]).map(e=>$.fromServerFormat(e))),r,i):new nM(n,s,r,i)}return t.delete?new nq(ru(e,t.delete),r):t.verify?new nB(ru(e,t.verify),r):b()}function rw(e,t){return{documents:[rh(e,t.path)]}}function rv(e,t){var n,r;let i;let s={structuredQuery:{}},a=t.path;null!==t.collectionGroup?(i=a,s.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=a.popLast(),s.structuredQuery.from=[{collectionId:a.lastSegment()}]),s.parent=rh(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof tA?function(e){if("=="===e.op){if(tp(e.value))return{unaryFilter:{field:r_(e.field),op:"IS_NAN"}};if(tg(e.value))return{unaryFilter:{field:r_(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(tp(e.value))return{unaryFilter:{field:r_(e.field),op:"IS_NOT_NAN"}};if(tg(e.value))return{unaryFilter:{field:r_(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:r_(e.field),op:n9[e.op],value:e.value}}}(t):t instanceof tR?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:n7[t.op],filters:n}}}(t):b()}(tR.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:r_(e.field),direction:n6[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=rt(e,t.limit);return null!==u&&(s.structuredQuery.limit=u),t.startAt&&(s.structuredQuery.startAt={before:(n=t.startAt).inclusive,values:n.position}),t.endAt&&(s.structuredQuery.endAt={before:!(r=t.endAt).inclusive,values:r.position}),{ct:s,parent:i}}function rI(e){var t;let n,r=rc(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){1===s||b();let e=i.from[0];e.allDescendants?a=e.collectionId:r=r.child(e.collectionId)}let o=[];i.where&&(o=function(e){let t=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=rT(e.unaryFilter.field);return tA.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=rT(e.unaryFilter.field);return tA.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=rT(e.unaryFilter.field);return tA.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=rT(e.unaryFilter.field);return tA.create(i,"!=",{nullValue:"NULL_VALUE"});default:return b()}}(t):void 0!==t.fieldFilter?tA.create(rT(t.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return b()}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?tR.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return b()}}(t.compositeFilter.op)):b()}(e);return t instanceof tR&&tM(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new tN(rT(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=null==(n="object"==typeof(t=i.limit)?t.value:t)?null:n);let h=null;i.startAt&&(h=function(e){let t=!!e.before;return new tS(e.values||[],t)}(i.startAt));let c=null;return i.endAt&&(c=function(e){let t=!e.before;return new tS(e.values||[],t)}(i.endAt)),new t0(r,a,l,o,u,"F",h,c)}function r_(e){return{fieldPath:e.canonicalString()}}function rT(e){return $.fromServerFormat(e.fieldPath)}function rE(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class rb{constructor(e,t,n,r,i=q.min(),s=q.min(),a=e5.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new rb(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new rb(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new rb(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new rb(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class rx{constructor(e){this.ht=e}}function rS(e,t){let n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:rD(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;r.document={name:rl(i=e.ht,t.key),fields:t.data.value.mapValue.fields,updateTime:rn(i,t.version.toTimestamp()),createTime:rn(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:rC(t.version)};else{if(!t.isUnknownDocument())return b();r.unknownDocument={path:n.path.toArray(),version:rC(t.version)}}return r}function rD(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function rC(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function rN(e){let t=new U(e.seconds,e.nanoseconds);return q.fromTimestamp(t)}function rk(e,t){let n=(t.baseMutations||[]).map(t=>ry(e.ht,t));for(let e=0;e<t.mutations.length-1;++e){let n=t.mutations[e];if(e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform){let r=t.mutations[e+1];n.updateTransforms=r.transform.fieldTransforms,t.mutations.splice(e+1,1),++e}}let r=t.mutations.map(t=>ry(e.ht,t)),i=U.fromMillis(t.localWriteTimeMs);return new nK(t.batchId,i,n,r)}function rA(e){var t;let n=rN(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?rN(e.lastLimboFreeSnapshotVersion):q.min();return new rb(void 0!==e.query.documents?(1===(t=e.query).documents.length||b(),t8(t1(rc(t.documents[0])))):t8(rI(e.query)),e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,e5.fromBase64String(e.resumeToken))}function rR(e,t){let n;let r=rC(t.snapshotVersion),i=rC(t.lastLimboFreeSnapshotVersion);n=tJ(t.target)?rw(e.ht,t.target):rv(e.ht,t.target).ct;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:tW(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function rV(e){let t=rI({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?t6(t,t.limit,"L"):t}function rL(e,t){return new n$(t.largestBatchId,ry(e.ht,t.overlayMutation))}function rM(e,t){let n=t.path.lastSegment();return[e,e_(t.path.popLast()),n]}function rO(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:rC(r.readTime),documentKey:e_(r.documentKey.path),largestBatchId:r.largestBatchId}}class rF{getBundleMetadata(e,t){return rP(e).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:rN(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return rP(e).put({bundleId:t.id,createTime:rC(ri(t.createTime)),version:t.version})}getNamedQuery(e,t){return rU(e).get(t).next(e=>{if(e)return{name:e.name,query:rV(e.bundledQuery),readTime:rN(e.readTime)}})}saveNamedQuery(e,t){return rU(e).put({name:t.name,readTime:rC(ri(t.readTime)),bundledQuery:t.bundledQuery})}}function rP(e){return eG(e,"bundles")}function rU(e){return eG(e,"namedQueries")}class rq{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){return new rq(e,t.uid||"")}getOverlay(e,t){return rB(e).get(rM(this.userId,t)).next(e=>e?rL(this.serializer,e):null)}getOverlays(e,t){let n=nu();return ei.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){let r=[];return n.forEach((n,i)=>{let s=new n$(t,i);r.push(this.Tt(e,s))}),ei.waitFor(r)}removeOverlaysForBatchId(e,t,n){let r=new Set;t.forEach(e=>r.add(e_(e.getCollectionPath())));let i=[];return r.forEach(t=>{let r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(rB(e).j("collectionPathOverlayIndex",r))}),ei.waitFor(i)}getOverlaysForCollection(e,t,n){let r=nu(),i=e_(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return rB(e).U("collectionPathOverlayIndex",s).next(e=>{for(let t of e){let e=rL(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){let i;let s=nu(),a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return rB(e).J({index:"collectionGroupOverlayIndex",range:a},(e,t,n)=>{let a=rL(this.serializer,t);s.size()<r||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):n.done()}).next(()=>s)}Tt(e,t){return rB(e).put(function(e,t,n){let[r,i,s]=rM(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:rp(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function rB(e){return eG(e,"documentOverlays")}class rK{It(e){return eG(e,"globals")}getSessionToken(e){return this.It(e).get("sessionToken").next(e=>{let t=null==e?void 0:e.value;return t?e5.fromUint8Array(t):e5.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.It(e).put({name:"sessionToken",value:t.toUint8Array()})}}class rz{constructor(){}Et(e,t){this.dt(e,t),t.At()}dt(e,t){if("nullValue"in e)this.Rt(t,5);else if("booleanValue"in e)this.Rt(t,10),t.Vt(e.booleanValue?1:0);else if("integerValue"in e)this.Rt(t,15),t.Vt(e3(e.integerValue));else if("doubleValue"in e){let n=e3(e.doubleValue);isNaN(n)?this.Rt(t,13):(this.Rt(t,15),ev(n)?t.Vt(0):t.Vt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Rt(t,20),"string"==typeof n&&(n=e8(n)),t.ft(`${n.seconds||""}`),t.Vt(n.nanos||0)}else if("stringValue"in e)this.gt(e.stringValue,t),this.yt(t);else if("bytesValue"in e)this.Rt(t,30),t.wt(e6(e.bytesValue)),this.yt(t);else if("referenceValue"in e)this.St(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Rt(t,45),t.Vt(n.latitude||0),t.Vt(n.longitude||0)}else"mapValue"in e?tI(e)?this.Rt(t,Number.MAX_SAFE_INTEGER):tw(e)?this.bt(e.mapValue,t):(this.Dt(e.mapValue,t),this.yt(t)):"arrayValue"in e?(this.vt(e.arrayValue,t),this.yt(t)):b()}gt(e,t){this.Rt(t,25),this.Ct(e,t)}Ct(e,t){t.ft(e)}Dt(e,t){let n=e.fields||{};for(let e of(this.Rt(t,55),Object.keys(n)))this.gt(e,t),this.dt(n[e],t)}bt(e,t){var n,r;let i=e.fields||{};this.Rt(t,53);let s="value",a=(null===(r=null===(n=i[s].arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.length)||0;this.Rt(t,15),t.Vt(e3(a)),this.gt(s,t),this.dt(i[s],t)}vt(e,t){let n=e.values||[];for(let e of(this.Rt(t,50),n))this.dt(e,t)}St(e,t){this.Rt(t,37),G.fromName(e).path.forEach(e=>{this.Rt(t,60),this.Ct(e,t)})}Rt(e,t){e.Vt(t)}yt(e){e.Vt(2)}}function r$(e){return Math.ceil((64-function(e){let t=0;for(let n=0;n<8;++n){let r=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[n]);if(t+=r,8!==r)break}return t}(e))/8)}rz.Ft=new rz;class rG{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Mt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.xt(n.value),n=t.next();this.Ot()}Nt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.Lt(n.value),n=t.next();this.Bt()}kt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.xt(e);else if(e<2048)this.xt(960|e>>>6),this.xt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.xt(480|e>>>12),this.xt(128|63&e>>>6),this.xt(128|63&e);else{let e=t.codePointAt(0);this.xt(240|e>>>18),this.xt(128|63&e>>>12),this.xt(128|63&e>>>6),this.xt(128|63&e)}}this.Ot()}qt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Lt(e);else if(e<2048)this.Lt(960|e>>>6),this.Lt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Lt(480|e>>>12),this.Lt(128|63&e>>>6),this.Lt(128|63&e);else{let e=t.codePointAt(0);this.Lt(240|e>>>18),this.Lt(128|63&e>>>12),this.Lt(128|63&e>>>6),this.Lt(128|63&e)}}this.Bt()}Qt(e){let t=this.Kt(e),n=r$(t);this.$t(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}Ut(e){let t=this.Kt(e),n=r$(t);this.$t(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}Wt(){this.Gt(255),this.Gt(255)}zt(){this.jt(255),this.jt(255)}reset(){this.position=0}seed(e){this.$t(e.length),this.buffer.set(e,this.position),this.position+=e.length}Ht(){return this.buffer.slice(0,this.position)}Kt(e){let t=function(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=n?255:0;return t}xt(e){let t=255&e;0===t?(this.Gt(0),this.Gt(255)):255===t?(this.Gt(255),this.Gt(0)):this.Gt(t)}Lt(e){let t=255&e;0===t?(this.jt(0),this.jt(255)):255===t?(this.jt(255),this.jt(0)):this.jt(e)}Ot(){this.Gt(0),this.Gt(1)}Bt(){this.jt(0),this.jt(1)}Gt(e){this.$t(1),this.buffer[this.position++]=e}jt(e){this.$t(1),this.buffer[this.position++]=~e}$t(e){let t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);let r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class rj{constructor(e){this.Jt=e}wt(e){this.Jt.Mt(e)}ft(e){this.Jt.kt(e)}Vt(e){this.Jt.Qt(e)}At(){this.Jt.Wt()}}class rQ{constructor(e){this.Jt=e}wt(e){this.Jt.Nt(e)}ft(e){this.Jt.qt(e)}Vt(e){this.Jt.Ut(e)}At(){this.Jt.zt()}}class rW{constructor(){this.Jt=new rG,this.Yt=new rj(this.Jt),this.Zt=new rQ(this.Jt)}seed(e){this.Jt.seed(e)}Xt(e){return 0===e?this.Yt:this.Zt}Ht(){return this.Jt.Ht()}reset(){this.Jt.reset()}}class rH{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}en(){let e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new rH(this.indexId,this.documentKey,this.arrayValue,n)}}function rJ(e,t){let n=e.indexId-t.indexId;return 0!==n?n:0!==(n=rY(e.arrayValue,t.arrayValue))?n:0!==(n=rY(e.directionalValue,t.directionalValue))?n:G.comparator(e.documentKey,t.documentKey)}function rY(e,t){for(let n=0;n<e.length&&n<t.length;++n){let r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}class rX{constructor(e){for(let t of(this.tn=new eX((e,t)=>$.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.nn=e.orderBy,this.rn=[],e.filters))t.isInequality()?this.tn=this.tn.add(t):this.rn.push(t)}get sn(){return this.tn.size>1}on(e){if(e.collectionGroup===this.collectionId||b(),this.sn)return!1;let t=Q(e);if(void 0!==t&&!this._n(t))return!1;let n=W(e),r=new Set,i=0,s=0;for(;i<n.length&&this._n(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.tn.size>0){let e=this.tn.getIterator().getNext();if(!r.has(e.field.canonicalString())){let t=n[i];if(!this.an(e,t)||!this.un(this.nn[s++],t))return!1}++i}for(;i<n.length;++i){let e=n[i];if(s>=this.nn.length||!this.un(this.nn[s++],e))return!1}return!0}cn(){if(this.sn)return null;let e=new eX($.comparator),t=[];for(let n of this.rn)if(!n.field.isKeyField()){if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new H(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new H(n.field,0))}}for(let n of this.nn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new H(n.field,"asc"===n.dir?0:1)));return new j(j.UNKNOWN_ID,this.collectionId,t,J.empty())}_n(e){for(let t of this.rn)if(this.an(t,e))return!0;return!1}an(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;let n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}un(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function rZ(e){return e instanceof tA}function r0(e){return e instanceof tR&&tM(e)}function r1(e){return rZ(e)||r0(e)||function(e){if(e instanceof tR&&tL(e)){for(let t of e.getFilters())if(!rZ(t)&&!r0(t))return!1;return!0}return!1}(e)}function r2(e,t){return e instanceof tA||e instanceof tR||b(),t instanceof tA||t instanceof tR||b(),r4(e instanceof tA?t instanceof tA?tR.create([e,t],"and"):r5(e,t):t instanceof tA?r5(t,e):function(e,t){if(e.filters.length>0&&t.filters.length>0||b(),tV(e)&&tV(t))return tF(e,t.getFilters());let n=tL(e)?e:t,r=tL(e)?t:e,i=n.filters.map(e=>r2(e,r));return tR.create(i,"or")}(e,t))}function r5(e,t){if(tV(t))return tF(t,e.getFilters());{let n=t.filters.map(t=>r2(e,t));return tR.create(n,"or")}}function r4(e){if(e instanceof tA||e instanceof tR||b(),e instanceof tA)return e;let t=e.getFilters();if(1===t.length)return r4(t[0]);if(tO(e))return e;let n=t.map(e=>r4(e)),r=[];return n.forEach(t=>{t instanceof tA?r.push(t):t instanceof tR&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:tR.create(r,e.op)}class r8{constructor(){this.ln=new r3}addToCollectionParentIndex(e,t){return this.ln.add(t),ei.resolve()}getCollectionParents(e,t){return ei.resolve(this.ln.getEntries(t))}addFieldIndex(e,t){return ei.resolve()}deleteFieldIndex(e,t){return ei.resolve()}deleteAllFieldIndexes(e){return ei.resolve()}createTargetIndexes(e,t){return ei.resolve()}getDocumentsMatchingTarget(e,t){return ei.resolve(null)}getIndexType(e,t){return ei.resolve(0)}getFieldIndexes(e,t){return ei.resolve([])}getNextCollectionGroupToUpdate(e){return ei.resolve(null)}getMinOffset(e,t){return ei.resolve(Z.min())}getMinOffsetFromCollectionGroup(e,t){return ei.resolve(Z.min())}updateCollectionGroup(e,t,n){return ei.resolve()}updateIndexEntries(e,t){return ei.resolve()}}class r3{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new eX(K.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new eX(K.comparator)).toArray()}}let r6=new Uint8Array(0);class r9{constructor(e,t){this.databaseId=t,this.hn=new r3,this.Pn=new ni(e=>tW(e),(e,t)=>tH(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.hn.has(t)){let n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.hn.add(t)});let i={collectionId:n,parent:e_(r)};return r7(e).put(i)}return ei.resolve()}getCollectionParents(e,t){let n=[],r=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return r7(e).U(r).next(e=>{for(let r of e){if(r.collectionId!==t)break;n.push(eT(r.parent))}return n})}addFieldIndex(e,t){let n=it(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;let i=n.add(r);if(t.indexState){let n=ir(e);return i.next(e=>{n.put(rO(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let n=it(e),r=ir(e),i=ie(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=it(e),n=ie(e),r=ir(e);return t.j().next(()=>n.j()).next(()=>r.j())}createTargetIndexes(e,t){return ei.forEach(this.Tn(t),t=>this.getIndexType(e,t).next(n=>{if(0===n||1===n){let n=new rX(t).cn();if(null!=n)return this.addFieldIndex(e,n)}}))}getDocumentsMatchingTarget(e,t){let n=ie(e),r=!0,i=new Map;return ei.forEach(this.Tn(t),t=>this.In(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>{if(r){let e=nd(),r=[];return ei.forEach(i,(i,s)=>{I("IndexedDbIndexManager",`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${tW(t)}`);let a=function(e,t){let n=Q(t);if(void 0===n)return null;for(let t of tY(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),o=function(e,t){let n=new Map;for(let r of W(t))for(let t of tY(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(s,i),l=function(e,t){let n=[],r=!0;for(let i of W(t)){let t=0===i.kind?tX(e,i.fieldPath,e.startAt):tZ(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new tS(n,r)}(s,i),u=function(e,t){let n=[],r=!0;for(let i of W(t)){let t=0===i.kind?tZ(e,i.fieldPath,e.endAt):tX(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new tS(n,r)}(s,i),h=this.En(i,s,l),c=this.En(i,s,u),d=this.dn(i,s,o),f=this.An(i.indexId,a,h,l.inclusive,c,u.inclusive,d);return ei.forEach(f,i=>n.G(i,t.limit).next(t=>{t.forEach(t=>{let n=G.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return ei.resolve(null)})}Tn(e){let t=this.Pn.get(e);return t||(t=0===e.filters.length?[e]:(function(e){if(0===e.getFilters().length)return[];let t=function e(t){if(t instanceof tA||t instanceof tR||b(),t instanceof tA)return t;if(1===t.filters.length)return e(t.filters[0]);let n=t.filters.map(t=>e(t)),r=tR.create(n,t.op);return r1(r=r4(r))?r:(r instanceof tR||b(),tV(r)||b(),r.filters.length>1||b(),r.filters.reduce((e,t)=>r2(e,t)))}(function e(t){var n,r;if(t instanceof tA||t instanceof tR||b(),t instanceof tA){if(t instanceof tz){let e=(null===(r=null===(n=t.value.arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.map(e=>tA.create(t.field,"==",e)))||[];return tR.create(e,"or")}return t}let i=t.filters.map(t=>e(t));return tR.create(i,t.op)}(e));return r1(t)||b(),rZ(t)||r0(t)?[t]:t.getFilters()})(tR.create(e.filters,"and")).map(t=>tQ(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.Pn.set(e,t)),t}An(e,t,n,r,i,s,a){let o=(null!=t?t.length:1)*Math.max(n.length,i.length),l=o/(null!=t?t.length:1),u=[];for(let h=0;h<o;++h){let o=t?this.Rn(t[h/l]):r6,c=this.Vn(e,o,n[h%l],r),d=this.mn(e,o,i[h%l],s),f=a.map(t=>this.Vn(e,o,t,!0));u.push(...this.createRange(c,d,f))}return u}Vn(e,t,n,r){let i=new rH(e,G.empty(),t,n);return r?i:i.en()}mn(e,t,n,r){let i=new rH(e,G.empty(),t,n);return r?i.en():i}In(e,t){let n=new rX(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{let t=null;for(let r of e)n.on(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let n=2,r=this.Tn(t);return ei.forEach(r,t=>this.In(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new eX($.comparator),n=!1;for(let r of e.filters)for(let e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(let n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>null!==t.limit&&r.length>1&&2===n?1:n)}fn(e,t){let n=new rW;for(let r of W(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;let i=n.Xt(r.kind);rz.Ft.Et(e,i)}return n.Ht()}Rn(e){let t=new rW;return rz.Ft.Et(e,t.Xt(0)),t.Ht()}gn(e,t){let n=new rW;return rz.Ft.Et(td(this.databaseId,t),n.Xt(function(e){let t=W(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Ht()}dn(e,t,n){if(null===n)return[];let r=[];r.push(new rW);let i=0;for(let s of W(e)){let e=n[i++];for(let n of r)if(this.pn(t,s.fieldPath)&&tm(e))r=this.yn(r,s,e);else{let t=n.Xt(s.kind);rz.Ft.Et(e,t)}}return this.wn(r)}En(e,t,n){return this.dn(e,t,n.position)}wn(e){let t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Ht();return t}yn(e,t,n){let r=[...e],i=[];for(let e of n.arrayValue.values||[])for(let n of r){let r=new rW;r.seed(n.Ht()),rz.Ft.Et(e,r.Xt(t.kind)),i.push(r)}return i}pn(e,t){return!!e.filters.find(e=>e instanceof tA&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let n=it(e),r=ir(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next(e=>{let t=[];return ei.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){let n=t?new J(t.sequenceNumber,new Z(rN(t.readTime),new G(eT(t.documentKey)),t.largestBatchId)):J.empty(),r=e.fields.map(([e,t])=>new H($.fromServerFormat(e),t));return new j(e.indexId,e.collectionGroup,r,n)}(e,n))})).next(()=>t)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{let n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:F(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){let r=it(e),i=ir(e);return this.Sn(e).next(e=>r.U("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(t=>ei.forEach(t,t=>i.put(rO(t.indexId,this.uid,e,n)))))}updateIndexEntries(e,t){let n=new Map;return ei.forEach(t,(t,r)=>{let i=n.get(t.collectionGroup);return(i?ei.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),ei.forEach(i,n=>this.bn(e,t,n).next(t=>{let i=this.Dn(r,n);return t.isEqual(i)?ei.resolve():this.vn(e,r,n,t,i)}))))})}Cn(e,t,n,r){return ie(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.gn(n,t.key),documentKey:t.key.path.toArray()})}Fn(e,t,n,r){return ie(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.gn(n,t.key),t.key.path.toArray()])}bn(e,t,n){let r=ie(e),i=new eX(rJ);return r.J({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},(e,r)=>{i=i.add(new rH(n.indexId,t,r.arrayValue,r.directionalValue))}).next(()=>i)}Dn(e,t){let n=new eX(rJ),r=this.fn(t,e);if(null==r)return n;let i=Q(t);if(null!=i){let s=e.data.field(i.fieldPath);if(tm(s))for(let i of s.arrayValue.values||[])n=n.add(new rH(t.indexId,e.key,this.Rn(i),r))}else n=n.add(new rH(t.indexId,e.key,r6,r));return n}vn(e,t,n,r,i){I("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);let s=[];return function(e,t,n,r,i){let s=e.getIterator(),a=t.getIterator(),o=e0(s),l=e0(a);for(;o||l;){let e=!1,t=!1;if(o&&l){let r=n(o,l);r<0?t=!0:r>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(l),l=e0(a)):t?(i(o),o=e0(s)):(o=e0(s),l=e0(a))}}(r,i,rJ,r=>{s.push(this.Cn(e,t,n,r))},r=>{s.push(this.Fn(e,t,n,r))}),ei.waitFor(s)}Sn(e){let t=1;return ir(e).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,n,r)=>{r.done(),t=n.sequenceNumber+1}).next(()=>t)}createRange(e,t,n){n=n.sort((e,t)=>rJ(e,t)).filter((e,t,n)=>!t||0!==rJ(e,n[t-1]));let r=[];for(let i of(r.push(e),n)){let n=rJ(i,e),s=rJ(i,t);if(0===n)r[0]=e.en();else if(n>0&&s<0)r.push(i),r.push(i.en());else if(s>0)break}r.push(t);let i=[];for(let e=0;e<r.length;e+=2){if(this.Mn(r[e],r[e+1]))return[];let t=[r[e].indexId,this.uid,r[e].arrayValue,r[e].directionalValue,r6,[]],n=[r[e+1].indexId,this.uid,r[e+1].arrayValue,r[e+1].directionalValue,r6,[]];i.push(IDBKeyRange.bound(t,n))}return i}Mn(e,t){return rJ(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(ii)}getMinOffset(e,t){return ei.mapArray(this.Tn(t),t=>this.In(e,t).next(e=>e||b())).next(ii)}}function r7(e){return eG(e,"collectionParents")}function ie(e){return eG(e,"indexEntries")}function it(e){return eG(e,"indexConfiguration")}function ir(e){return eG(e,"indexState")}function ii(e){0!==e.length||b();let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){let i=e[r].indexState.offset;0>ee(i,t)&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new Z(t.readTime,t.documentKey,n)}let is={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class ia{static withCacheSize(e){return new ia(e,ia.DEFAULT_COLLECTION_PERCENTILE,ia.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function io(e,t,n){let r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId),o=0,l=r.J({range:a},(e,t,n)=>(o++,n.delete()));s.push(l.next(()=>{1===o||b()}));let u=[];for(let e of n.mutations){var h,c;let r=(h=e.key.path,c=n.batchId,[t,e_(h),c]);s.push(i.delete(r)),u.push(e.key)}return ei.waitFor(s).next(()=>u)}function il(e){let t;if(!e)return 0;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw b();t=e.noDocument}return JSON.stringify(t).length}ia.DEFAULT_COLLECTION_PERCENTILE=10,ia.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,ia.DEFAULT=new ia(0x2800000,ia.DEFAULT_COLLECTION_PERCENTILE,ia.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),ia.DISABLED=new ia(-1,0,0);class iu{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.xn={}}static Pt(e,t,n,r){return""!==e.uid||b(),new iu(e.isAuthenticated()?e.uid:"",t,n,r)}checkEmpty(e){let t=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return ic(e).J({index:"userMutationsIndex",range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){let i=id(e),s=ic(e);return s.add({}).next(a=>{"number"==typeof a||b();let o=new nK(a,t,n,r),l=function(e,t,n){let r=n.baseMutations.map(t=>rp(e.ht,t)),i=n.mutations.map(t=>rp(e.ht,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,o),u=[],h=new eX((e,t)=>F(e.canonicalString(),t.canonicalString()));for(let e of r){let t=[this.userId,e_(e.key.path),a];h=h.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,eb))}return h.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.xn[a]=o.keys()}),ei.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return ic(e).get(t).next(e=>e?(e.userId===this.userId||b(),rk(this.serializer,e)):null)}On(e,t){return this.xn[t]?ei.resolve(this.xn[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){let n=e.keys();return this.xn[t]=n,n}return null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return ic(e).J({index:"userMutationsIndex",range:r},(e,t,r)=>{t.userId===this.userId&&(t.batchId>=n||b(),i=rk(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=-1;return ic(e).J({index:"userMutationsIndex",range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return ic(e).U("userMutationsIndex",t).next(e=>e.map(e=>rk(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let n=[this.userId,e_(t.path)],r=IDBKeyRange.lowerBound(n),i=[];return id(e).J({range:r},(n,r,s)=>{let[a,o,l]=n,u=eT(o);if(a===this.userId&&t.path.isEqual(u))return ic(e).get(l).next(e=>{if(!e)throw b();e.userId===this.userId||b(),i.push(rk(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new eX(F),r=[];return t.forEach(t=>{let i=[this.userId,e_(t.path)],s=IDBKeyRange.lowerBound(i),a=id(e).J({range:s},(e,r,i)=>{let[s,a,o]=e,l=eT(a);s===this.userId&&t.path.isEqual(l)?n=n.add(o):i.done()});r.push(a)}),ei.waitFor(r).next(()=>this.Nn(e,n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=[this.userId,e_(n)],s=IDBKeyRange.lowerBound(i),a=new eX(F);return id(e).J({range:s},(e,t,i)=>{let[s,o,l]=e,u=eT(o);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(a=a.add(l)):i.done()}).next(()=>this.Nn(e,a))}Nn(e,t){let n=[],r=[];return t.forEach(t=>{r.push(ic(e).get(t).next(e=>{if(null===e)throw b();e.userId===this.userId||b(),n.push(rk(this.serializer,e))}))}),ei.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return io(e._e,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.Ln(t.batchId)}),ei.forEach(n,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}Ln(e){delete this.xn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>{if(!t)return ei.resolve();let n=IDBKeyRange.lowerBound([this.userId]),r=[];return id(e).J({range:n},(e,t,n)=>{if(e[0]===this.userId){let t=eT(e[1]);r.push(t)}else n.done()}).next(()=>{0===r.length||b()})})}containsKey(e,t){return ih(e,this.userId,t)}Bn(e){return im(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function ih(e,t,n){let r=[t,e_(n.path)],i=r[1],s=IDBKeyRange.lowerBound(r),a=!1;return id(e).J({range:s,H:!0},(e,n,r)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),r.done()}).next(()=>a)}function ic(e){return eG(e,"mutations")}function id(e){return eG(e,"documentMutations")}function im(e){return eG(e,"mutationQueues")}class ig{constructor(e){this.kn=e}next(){return this.kn+=2,this.kn}static qn(){return new ig(0)}static Qn(){return new ig(-1)}}class ip{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.Kn(e).next(t=>{let n=new ig(t.highestTargetId);return t.highestTargetId=n.next(),this.$n(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Kn(e).next(e=>q.fromTimestamp(new U(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Kn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,n){return this.Kn(e).next(r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.$n(e,r)))}addTargetData(e,t){return this.Un(e,t).next(()=>this.Kn(e).next(n=>(n.targetCount+=1,this.Wn(t,n),this.$n(e,n))))}updateTargetData(e,t){return this.Un(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>iy(e).delete(t.targetId)).next(()=>this.Kn(e)).next(t=>(t.targetCount>0||b(),t.targetCount-=1,this.$n(e,t)))}removeTargets(e,t,n){let r=0,i=[];return iy(e).J((s,a)=>{let o=rA(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,i.push(this.removeTargetData(e,o)))}).next(()=>ei.waitFor(i)).next(()=>r)}forEachTarget(e,t){return iy(e).J((e,n)=>{t(rA(n))})}Kn(e){return iw(e).get("targetGlobalKey").next(e=>(null!==e||b(),e))}$n(e,t){return iw(e).put("targetGlobalKey",t)}Un(e,t){return iy(e).put(rR(this.serializer,t))}Wn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Kn(e).next(e=>e.targetCount)}getTargetData(e,t){let n=tW(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]),i=null;return iy(e).J({range:r,index:"queryTargetsIndex"},(e,n,r)=>{let s=rA(n);tH(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){let r=[],i=iv(e);return t.forEach(t=>{let s=e_(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),ei.waitFor(r)}removeMatchingKeys(e,t,n){let r=iv(e);return ei.forEach(t,t=>{let i=e_(t.path);return ei.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){let n=iv(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){let n=IDBKeyRange.bound([t],[t+1],!1,!0),r=iv(e),i=nd();return r.J({range:n,H:!0},(e,t,n)=>{let r=new G(eT(e[1]));i=i.add(r)}).next(()=>i)}containsKey(e,t){let n=e_(t.path),r=IDBKeyRange.bound([n],[n+"\0"],!1,!0),i=0;return iv(e).J({index:"documentTargetsIndex",H:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}ut(e,t){return iy(e).get(t).next(e=>e?rA(e):null)}}function iy(e){return eG(e,"targets")}function iw(e){return eG(e,"targetGlobal")}function iv(e){return eG(e,"targetDocuments")}function iI([e,t],[n,r]){let i=F(e,n);return 0===i?F(t,r):i}class i_{constructor(e){this.Gn=e,this.buffer=new eX(iI),this.zn=0}jn(){return++this.zn}Hn(e){let t=[e,this.jn()];if(this.buffer.size<this.Gn)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>iI(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class iT{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Jn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Yn(6e4)}stop(){this.Jn&&(this.Jn.cancel(),this.Jn=null)}get started(){return null!==this.Jn}Yn(e){I("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Jn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Jn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){eh(e)?I("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await er(e)}await this.Yn(3e5)})}}class iE{constructor(e,t){this.Zn=e,this.params=t}calculateTargetCount(e,t){return this.Zn.Xn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return ei.resolve(ey.oe);let n=new i_(t);return this.Zn.forEachTarget(e,e=>n.Hn(e.sequenceNumber)).next(()=>this.Zn.er(e,e=>n.Hn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Zn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Zn.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(I("LruGarbageCollector","Garbage collection skipped; disabled"),ei.resolve(is)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(I("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),is):this.tr(e,t))}getCacheSize(e){return this.Zn.getCacheSize(e)}tr(e,t){let n,r,i,s,a,o,l;let h=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(I("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,s=Date.now(),this.nthSequenceNumber(e,r))).next(r=>(n=r,a=Date.now(),this.removeTargets(e,n,t))).next(t=>(i=t,o=Date.now(),this.removeOrphanedDocuments(e,n))).next(e=>(l=Date.now(),v()<=u.$b.DEBUG&&I("LruGarbageCollector",`LRU Garbage Collection
	Counted targets in ${s-h}ms
	Determined least recently used ${r} in `+(a-s)+"ms\n"+`	Removed ${i} targets in `+(o-a)+"ms\n"+`	Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-h}ms`),ei.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class ib{constructor(e,t){this.db=e,this.garbageCollector=new iE(this,t)}Xn(e){let t=this.nr(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}nr(e){let t=0;return this.er(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}er(e,t){return this.rr(e,(e,n)=>t(n))}addReference(e,t,n){return ix(e,n)}removeReference(e,t,n){return ix(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return ix(e,t)}ir(e,t){let n;return n=!1,im(e).Y(r=>ih(e,r,t).next(e=>(e&&(n=!0),ei.resolve(!e)))).next(()=>n)}removeOrphanedDocuments(e,t){let n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[],i=0;return this.rr(e,(s,a)=>{if(a<=t){let t=this.ir(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,q.min()),iv(e).delete([0,e_(s.path)])))});r.push(t)}}).next(()=>ei.waitFor(r)).next(()=>n.apply(e)).next(()=>i)}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return ix(e,t)}rr(e,t){let n=iv(e),r,i=ey.oe;return n.J({index:"documentTargetsIndex"},([e,n],{path:s,sequenceNumber:a})=>{0===e?(i!==ey.oe&&t(new G(eT(r)),i),i=a,r=s):i=ey.oe}).next(()=>{i!==ey.oe&&t(new G(eT(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function ix(e,t){var n;return iv(e).put((n=e.currentSequenceNumber,{targetId:0,path:e_(t.path),sequenceNumber:n}))}class iS{constructor(){this.changes=new ni(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,tx.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?ei.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class iD{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return ik(e).put(n)}removeEntry(e,t,n){return ik(e).delete(function(e,t){let n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],rD(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next(n=>(n.byteSize+=t,this.sr(e,n)))}getEntry(e,t){let n=tx.newInvalidDocument(t);return ik(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(iA(t))},(e,r)=>{n=this._r(t,r)}).next(()=>n)}ar(e,t){let n={size:0,document:tx.newInvalidDocument(t)};return ik(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(iA(t))},(e,r)=>{n={document:this._r(t,r),size:il(r)}}).next(()=>n)}getEntries(e,t){let n=ns;return this.ur(e,t,(e,t)=>{let r=this._r(e,t);n=n.insert(e,r)}).next(()=>n)}cr(e,t){let n=ns,r=new eH(G.comparator);return this.ur(e,t,(e,t)=>{let i=this._r(e,t);n=n.insert(e,i),r=r.insert(e,il(t))}).next(()=>({documents:n,lr:r}))}ur(e,t,n){if(t.isEmpty())return ei.resolve();let r=new eX(iV);t.forEach(e=>r=r.add(e));let i=IDBKeyRange.bound(iA(r.first()),iA(r.last())),s=r.getIterator(),a=s.getNext();return ik(e).J({index:"documentKeyIndex",range:i},(e,t,r)=>{let i=G.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>iV(a,i);)n(a,null),a=s.getNext();a&&a.isEqual(i)&&(n(a,t),a=s.hasNext()?s.getNext():null),a?r.$(iA(a)):r.done()}).next(()=>{for(;a;)n(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,t,n,r,i){let s=t.path,a=[s.popLast().toArray(),s.lastSegment(),rD(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return ik(e).U(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let n=ns;for(let i of e){let e=this._r(G.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(nt(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=ns,s=iR(t,n),a=iR(t,Z.max());return ik(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,a,!0)},(e,t,n)=>{let s=this._r(G.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(i=i.insert(s.key,s)).size===r&&n.done()}).next(()=>i)}newChangeBuffer(e){return new iC(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return iN(e).get("remoteDocumentGlobalKey").next(e=>(e||b(),e))}sr(e,t){return iN(e).put("remoteDocumentGlobalKey",t)}_r(e,t){if(t){let e=function(e,t){let n;if(t.document)n=rg(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=G.fromSegments(t.noDocument.path),r=rN(t.noDocument.readTime);n=tx.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return b();{let e=G.fromSegments(t.unknownDocument.path),r=rN(t.unknownDocument.version);n=tx.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){let t=new U(e[0],e[1]);return q.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual(q.min())))return e}return tx.newInvalidDocument(e)}}class iC extends iS{constructor(e,t){super(),this.hr=e,this.trackRemovals=t,this.Pr=new ni(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],n=0,r=new eX((e,t)=>F(e.canonicalString(),t.canonicalString()));return this.changes.forEach((i,s)=>{let a=this.Pr.get(i);if(t.push(this.hr.removeEntry(e,i,a.readTime)),s.isValidDocument()){let o=rS(this.hr.serializer,s);r=r.add(i.path.popLast());let l=il(o);n+=l-a.size,t.push(this.hr.addEntry(e,i,o))}else if(n-=a.size,this.trackRemovals){let n=rS(this.hr.serializer,s.convertToNoDocument(q.min()));t.push(this.hr.addEntry(e,i,n))}}),r.forEach(n=>{t.push(this.hr.indexManager.addToCollectionParentIndex(e,n))}),t.push(this.hr.updateMetadata(e,n)),ei.waitFor(t)}getFromCache(e,t){return this.hr.ar(e,t).next(e=>(this.Pr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.hr.cr(e,t).next(({documents:e,lr:t})=>(t.forEach((t,n)=>{this.Pr.set(t,{size:n,readTime:e.get(t).readTime})}),e))}}function iN(e){return eG(e,"remoteDocumentGlobal")}function ik(e){return eG(e,"remoteDocumentsV14")}function iA(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function iR(e,t){let n=t.documentKey.path.toArray();return[e,rD(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function iV(e,t){let n=e.path.toArray(),r=t.path.toArray(),i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=F(n[e],r[e]))return i;return(i=F(n.length,r.length))||(i=F(n[n.length-2],r[r.length-2]))||F(n[n.length-1],r[r.length-1])}class iL{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class iM{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(r=>(n=r,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==n&&nV(n.mutation,e,e1.empty(),U.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,nd()).next(()=>t))}getLocalViewOfDocuments(e,t,n=nd()){let r=nu();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=no();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=nu();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,nd()))}populateOverlays(e,t,n){let r=[];return n.forEach(e=>{t.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,n)=>{t.set(e,n)})})}computeViews(e,t,n,r){let i=ns,s=nu(),a=nu();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof nO)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),nV(a.mutation,t,a.mutation.getFieldMask(),U.now())):s.set(t.key,e1.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>{var n;return a.set(e,new iL(t,null!==(n=s.get(e))&&void 0!==n?n:null))}),a))}recalculateAndSaveOverlays(e,t){let n=nu(),r=new eH((e,t)=>e-t),i=nd();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let i of e)i.keys().forEach(e=>{let s=t.get(e);if(null===s)return;let a=n.get(e)||e1.empty();a=i.applyToLocalView(s,a),n.set(e,a);let o=(r.get(i.batchId)||nd()).add(e);r=r.insert(i.batchId,o)})}).next(()=>{let s=[],a=r.getReverseIterator();for(;a.hasNext();){let r=a.getNext(),o=r.key,l=r.value,u=nu();l.forEach(e=>{if(!i.has(e)){let r=nR(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,o,u))}return ei.waitFor(s)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,n,r){return G.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):t5(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(i=>{let s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):ei.resolve(nu()),a=-1,o=i;return s.next(t=>ei.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?ei.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,o,t,nd())).next(e=>({batchId:a,changes:nl(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new G(t)).next(e=>{let t=no();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let i=t.collectionGroup,s=no();return this.indexManager.getCollectionParents(e,i).next(a=>ei.forEach(a,a=>{let o=new t0(a.child(i),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r))).next(e=>{i.forEach((t,n)=>{let r=n.getKey();null===e.get(r)&&(e=e.insert(r,tx.newInvalidDocument(r)))});let n=no();return e.forEach((e,r)=>{let s=i.get(e);void 0!==s&&nV(s.mutation,r,e1.empty(),U.now()),nt(t,r)&&(n=n.insert(e,r))}),n})}}class iO{constructor(e){this.serializer=e,this.Tr=new Map,this.Ir=new Map}getBundleMetadata(e,t){return ei.resolve(this.Tr.get(t))}saveBundleMetadata(e,t){return this.Tr.set(t.id,{id:t.id,version:t.version,createTime:ri(t.createTime)}),ei.resolve()}getNamedQuery(e,t){return ei.resolve(this.Ir.get(t))}saveNamedQuery(e,t){return this.Ir.set(t.name,{name:t.name,query:rV(t.bundledQuery),readTime:ri(t.readTime)}),ei.resolve()}}class iF{constructor(){this.overlays=new eH(G.comparator),this.Er=new Map}getOverlay(e,t){return ei.resolve(this.overlays.get(t))}getOverlays(e,t){let n=nu();return ei.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){return n.forEach((n,r)=>{this.Tt(e,t,r)}),ei.resolve()}removeOverlaysForBatchId(e,t,n){let r=this.Er.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Er.delete(n)),ei.resolve()}getOverlaysForCollection(e,t,n){let r=nu(),i=t.length+1,s=new G(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){let e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return ei.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new eH((e,t)=>e-t),s=this.overlays.getIterator();for(;s.hasNext();){let e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=nu(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=nu(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return ei.resolve(a)}Tt(e,t,n){let r=this.overlays.get(n.key);if(null!==r){let e=this.Er.get(r.largestBatchId).delete(n.key);this.Er.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new n$(t,n));let i=this.Er.get(t);void 0===i&&(i=nd(),this.Er.set(t,i)),this.Er.set(t,i.add(n.key))}}class iP{constructor(){this.sessionToken=e5.EMPTY_BYTE_STRING}getSessionToken(e){return ei.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,ei.resolve()}}class iU{constructor(){this.dr=new eX(iq.Ar),this.Rr=new eX(iq.Vr)}isEmpty(){return this.dr.isEmpty()}addReference(e,t){let n=new iq(e,t);this.dr=this.dr.add(n),this.Rr=this.Rr.add(n)}mr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.gr(new iq(e,t))}pr(e,t){e.forEach(e=>this.removeReference(e,t))}yr(e){let t=new G(new K([])),n=new iq(t,e),r=new iq(t,e+1),i=[];return this.Rr.forEachInRange([n,r],e=>{this.gr(e),i.push(e.key)}),i}wr(){this.dr.forEach(e=>this.gr(e))}gr(e){this.dr=this.dr.delete(e),this.Rr=this.Rr.delete(e)}Sr(e){let t=new G(new K([])),n=new iq(t,e),r=new iq(t,e+1),i=nd();return this.Rr.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new iq(e,0),n=this.dr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class iq{constructor(e,t){this.key=e,this.br=t}static Ar(e,t){return G.comparator(e.key,t.key)||F(e.br,t.br)}static Vr(e,t){return F(e.br,t.br)||G.comparator(e.key,t.key)}}class iB{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Dr=1,this.vr=new eX(iq.Ar)}checkEmpty(e){return ei.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let i=this.Dr;this.Dr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new nK(i,t,n,r);for(let t of(this.mutationQueue.push(s),r))this.vr=this.vr.add(new iq(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ei.resolve(s)}lookupMutationBatch(e,t){return ei.resolve(this.Cr(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.Fr(t+1),r=n<0?0:n;return ei.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return ei.resolve(0===this.mutationQueue.length?-1:this.Dr-1)}getAllMutationBatches(e){return ei.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new iq(t,0),r=new iq(t,Number.POSITIVE_INFINITY),i=[];return this.vr.forEachInRange([n,r],e=>{let t=this.Cr(e.br);i.push(t)}),ei.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new eX(F);return t.forEach(e=>{let t=new iq(e,0),r=new iq(e,Number.POSITIVE_INFINITY);this.vr.forEachInRange([t,r],e=>{n=n.add(e.br)})}),ei.resolve(this.Mr(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=n;G.isDocumentKey(i)||(i=i.child(""));let s=new iq(new G(i),0),a=new eX(F);return this.vr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.br)),!0)},s),ei.resolve(this.Mr(a))}Mr(e){let t=[];return e.forEach(e=>{let n=this.Cr(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){0===this.Or(t.batchId,"removed")||b(),this.mutationQueue.shift();let n=this.vr;return ei.forEach(t.mutations,r=>{let i=new iq(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.vr=n})}Ln(e){}containsKey(e,t){let n=new iq(t,0),r=this.vr.firstAfterOrEqual(n);return ei.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,ei.resolve()}Or(e,t){return this.Fr(e)}Fr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Cr(e){let t=this.Fr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class iK{constructor(e){this.Nr=e,this.docs=new eH(G.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Nr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let n=this.docs.get(t);return ei.resolve(n?n.document.mutableCopy():tx.newInvalidDocument(t))}getEntries(e,t){let n=ns;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():tx.newInvalidDocument(e))}),ei.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=ns,s=t.path,a=new G(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){let{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||0>=ee(X(a),n)||(r.has(a.key)||nt(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return ei.resolve(i)}getAllFromCollectionGroup(e,t,n,r){b()}Lr(e,t){return ei.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new iz(this)}getSize(e){return ei.resolve(this.size)}}class iz extends iS{constructor(e){super(),this.hr=e}applyChanges(e){let t=[];return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.hr.addEntry(e,r)):this.hr.removeEntry(n)}),ei.waitFor(t)}getFromCache(e,t){return this.hr.getEntry(e,t)}getAllFromCache(e,t){return this.hr.getEntries(e,t)}}class i${constructor(e){this.persistence=e,this.Br=new ni(e=>tW(e),tH),this.lastRemoteSnapshotVersion=q.min(),this.highestTargetId=0,this.kr=0,this.qr=new iU,this.targetCount=0,this.Qr=ig.qn()}forEachTarget(e,t){return this.Br.forEach((e,n)=>t(n)),ei.resolve()}getLastRemoteSnapshotVersion(e){return ei.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ei.resolve(this.kr)}allocateTargetId(e){return this.highestTargetId=this.Qr.next(),ei.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.kr&&(this.kr=t),ei.resolve()}Un(e){this.Br.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.Qr=new ig(t),this.highestTargetId=t),e.sequenceNumber>this.kr&&(this.kr=e.sequenceNumber)}addTargetData(e,t){return this.Un(t),this.targetCount+=1,ei.resolve()}updateTargetData(e,t){return this.Un(t),ei.resolve()}removeTargetData(e,t){return this.Br.delete(t.target),this.qr.yr(t.targetId),this.targetCount-=1,ei.resolve()}removeTargets(e,t,n){let r=0,i=[];return this.Br.forEach((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.Br.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)}),ei.waitFor(i).next(()=>r)}getTargetCount(e){return ei.resolve(this.targetCount)}getTargetData(e,t){let n=this.Br.get(t)||null;return ei.resolve(n)}addMatchingKeys(e,t,n){return this.qr.mr(t,n),ei.resolve()}removeMatchingKeys(e,t,n){this.qr.pr(t,n);let r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(t=>{i.push(r.markPotentiallyOrphaned(e,t))}),ei.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.qr.yr(t),ei.resolve()}getMatchingKeysForTargetId(e,t){let n=this.qr.Sr(t);return ei.resolve(n)}containsKey(e,t){return ei.resolve(this.qr.containsKey(t))}}class iG{constructor(e,t){this.Kr={},this.overlays={},this.$r=new ey(0),this.Ur=!1,this.Ur=!0,this.Wr=new iP,this.referenceDelegate=e(this),this.Gr=new i$(this),this.indexManager=new r8,this.remoteDocumentCache=new iK(e=>this.referenceDelegate.zr(e)),this.serializer=new rx(t),this.jr=new iO(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Ur=!1,Promise.resolve()}get started(){return this.Ur}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new iF,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Kr[e.toKey()];return n||(n=new iB(t,this.referenceDelegate),this.Kr[e.toKey()]=n),n}getGlobalsCache(){return this.Wr}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.jr}runTransaction(e,t,n){I("MemoryPersistence","Starting transaction:",e);let r=new ij(this.$r.next());return this.referenceDelegate.Hr(),n(r).next(e=>this.referenceDelegate.Jr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Yr(e,t){return ei.or(Object.values(this.Kr).map(n=>()=>n.containsKey(e,t)))}}class ij extends en{constructor(e){super(),this.currentSequenceNumber=e}}class iQ{constructor(e){this.persistence=e,this.Zr=new iU,this.Xr=null}static ei(e){return new iQ(e)}get ti(){if(this.Xr)return this.Xr;throw b()}addReference(e,t,n){return this.Zr.addReference(n,t),this.ti.delete(n.toString()),ei.resolve()}removeReference(e,t,n){return this.Zr.removeReference(n,t),this.ti.add(n.toString()),ei.resolve()}markPotentiallyOrphaned(e,t){return this.ti.add(t.toString()),ei.resolve()}removeTarget(e,t){this.Zr.yr(t.targetId).forEach(e=>this.ti.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.ti.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Hr(){this.Xr=new Set}Jr(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ei.forEach(this.ti,n=>{let r=G.fromPath(n);return this.ni(e,r).next(e=>{e||t.removeEntry(r,q.min())})}).next(()=>(this.Xr=null,t.apply(e)))}updateLimboDocument(e,t){return this.ni(e,t).next(e=>{e?this.ti.delete(t.toString()):this.ti.add(t.toString())})}zr(e){return 0}ni(e,t){return ei.or([()=>ei.resolve(this.Zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Yr(e,t)])}}class iW{constructor(e,t){this.persistence=e,this.ri=new ni(e=>e_(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new iE(this,t)}static ei(e,t){return new iW(e,t)}Hr(){}Jr(e){return ei.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}Xn(e){let t=this.nr(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}nr(e){let t=0;return this.er(e,e=>{t++}).next(()=>t)}er(e,t){return ei.forEach(this.ri,(n,r)=>this.ir(e,n,r).next(e=>e?ei.resolve():t(r)))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0,r=this.persistence.getRemoteDocumentCache(),i=r.newChangeBuffer();return r.Lr(e,r=>this.ir(e,r,t).next(e=>{e||(n++,i.removeEntry(r,q.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.ri.set(t,e.currentSequenceNumber),ei.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),ei.resolve()}removeReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),ei.resolve()}updateLimboDocument(e,t){return this.ri.set(t,e.currentSequenceNumber),ei.resolve()}zr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(ts(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let n=e7(t);return n?16+e(n):16;case 5:return 2*t.stringValue.length;case 6:return e6(t.bytesValue).approximateByteSize();case 7:return t.referenceValue.length;case 9:return(t.arrayValue.values||[]).reduce((t,n)=>t+e(n),0);case 10:case 11:var r;let i;return r=t.mapValue,i=0,eQ(r.fields,(t,n)=>{i+=t.length+e(n)}),i;default:throw b()}}(e.data.value)),t}ir(e,t,n){return ei.or([()=>this.persistence.Yr(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.ri.get(t);return ei.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class iH{constructor(e){this.serializer=e}O(e,t,n,r){let i=new es("createOrUpgrade",t);n<1&&r>=1&&(!function(e){e.createObjectStore("owner")}(e),e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",eE,{unique:!0}),e.createObjectStore("documentMutations"),iJ(e),function(e){e.createObjectStore("remoteDocuments")}(e));let s=ei.resolve();return n<3&&r>=3&&(0!==n&&(e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal"),iJ(e)),s=s.next(()=>(function(e){let t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:q.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)})(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>i.store("mutations").U().next(t=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",eE,{unique:!0});let n=i.store("mutations"),r=t.map(e=>n.put(e));return ei.waitFor(r)}))),s=s.next(()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)})),n<5&&r>=5&&(s=s.next(()=>this.ii(i))),n<6&&r>=6&&(s=s.next(()=>((function(e){e.createObjectStore("remoteDocumentGlobal")})(e),this.si(i)))),n<7&&r>=7&&(s=s.next(()=>this.oi(i))),n<8&&r>=8&&(s=s.next(()=>this._i(e,i))),n<9&&r>=9&&(s=s.next(()=>{e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&r>=10&&(s=s.next(()=>this.ai(i))),n<11&&r>=11&&(s=s.next(()=>{(function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})})(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)})),n<12&&r>=12&&(s=s.next(()=>{!function(e){let t=e.createObjectStore("documentOverlays",{keyPath:eO});t.createIndex("collectionPathOverlayIndex",eF,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",eP,{unique:!1})}(e)})),n<13&&r>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore("remoteDocumentsV14",{keyPath:ex});t.createIndex("documentKeyIndex",eS),t.createIndex("collectionGroupIndex",eD)})(e)).next(()=>this.ui(e,i)).next(()=>e.deleteObjectStore("remoteDocuments"))),n<14&&r>=14&&(s=s.next(()=>this.ci(e,i))),n<15&&r>=15&&(s=s.next(()=>{e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:eR}).createIndex("sequenceNumberIndex",eV,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:eL}).createIndex("documentKeyIndex",eM,{unique:!1})})),n<16&&r>=16&&(s=s.next(()=>{t.objectStore("indexState").clear()}).next(()=>{t.objectStore("indexEntries").clear()})),n<17&&r>=17&&(s=s.next(()=>{!function(e){e.createObjectStore("globals",{keyPath:"name"})}(e)})),s}si(e){let t=0;return e.store("remoteDocuments").J((e,n)=>{t+=il(n)}).next(()=>{let n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)})}ii(e){let t=e.store("mutationQueues"),n=e.store("mutations");return t.U().next(t=>ei.forEach(t,t=>{let r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.U("userMutationsIndex",r).next(n=>ei.forEach(n,n=>{n.userId===t.userId||b();let r=rk(this.serializer,n);return io(e,t.userId,r).next(()=>{})}))}))}oi(e){let t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(e=>{let r=[];return n.J((n,i)=>{let s=new K(n),a=[0,e_(s)];r.push(t.get(a).next(n=>n?ei.resolve():t.put({targetId:0,path:e_(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>ei.waitFor(r))})}_i(e,t){e.createObjectStore("collectionParents",{keyPath:eA});let n=t.store("collectionParents"),r=new r3,i=e=>{if(r.add(e)){let t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:e_(r)})}};return t.store("remoteDocuments").J({H:!0},(e,t)=>i(new K(e).popLast())).next(()=>t.store("documentMutations").J({H:!0},([e,t,n],r)=>i(eT(t).popLast())))}ai(e){let t=e.store("targets");return t.J((e,n)=>{let r=rA(n),i=rR(this.serializer,r);return t.put(i)})}ui(e,t){let n=t.store("remoteDocuments"),r=[];return n.J((e,n)=>{let i=t.store("remoteDocumentsV14"),s=(n.document?new G(K.fromString(n.document.name).popFirst(5)):n.noDocument?G.fromSegments(n.noDocument.path):n.unknownDocument?G.fromSegments(n.unknownDocument.path):b()).path.toArray(),a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))}).next(()=>ei.waitFor(r))}ci(e,t){let n=t.store("mutations"),r=new iD(this.serializer),i=new iG(iQ.ei,this.serializer.ht);return n.U().next(e=>{let n=new Map;return e.forEach(e=>{var t;let r=null!==(t=n.get(e.userId))&&void 0!==t?t:nd();rk(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),ei.forEach(n,(e,n)=>{let s=new p(n),a=rq.Pt(this.serializer,s),o=i.getIndexManager(s);return new iM(r,iu.Pt(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new e$(t,ey.oe),e).next()})})}}function iJ(e){e.createObjectStore("targetDocuments",{keyPath:eN}).createIndex("documentTargetsIndex",ek,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",eC,{unique:!0}),e.createObjectStore("targetGlobal")}let iY="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 iX{constructor(e,t,n,r,i,s,a,o,l,u,h=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.li=i,this.window=s,this.document=a,this.hi=l,this.Pi=u,this.Ti=h,this.$r=null,this.Ur=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ii=null,this.inForeground=!1,this.Ei=null,this.di=null,this.Ai=Number.NEGATIVE_INFINITY,this.Ri=e=>Promise.resolve(),!iX.p())throw new S(x.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new ib(this,r),this.Vi=t+"main",this.serializer=new rx(o),this.mi=new ea(this.Vi,this.Ti,new iH(this.serializer)),this.Wr=new rK,this.Gr=new ip(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new iD(this.serializer),this.jr=new rF,this.window&&this.window.localStorage?this.fi=this.window.localStorage:(this.fi=null,!1===u&&_("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.gi().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new S(x.FAILED_PRECONDITION,iY);return this.pi(),this.yi(),this.wi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Gr.getHighestSequenceNumber(e))}).then(e=>{this.$r=new ey(e,this.hi)}).then(()=>{this.Ur=!0}).catch(e=>(this.mi&&this.mi.close(),Promise.reject(e)))}Si(e){return this.Ri=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.mi.L(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.li.enqueueAndForget(async()=>{this.started&&await this.gi()}))}gi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>i0(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.bi(e).next(e=>{e||(this.isPrimary=!1,this.li.enqueueRetryable(()=>this.Ri(!1)))})}).next(()=>this.Di(e)).next(t=>this.isPrimary&&!t?this.vi(e).next(()=>!1):!!t&&this.Ci(e).next(()=>!0))).catch(e=>{if(eh(e))return I("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return I("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.li.enqueueRetryable(()=>this.Ri(e)),this.isPrimary=e})}bi(e){return iZ(e).get("owner").next(e=>ei.resolve(this.Fi(e)))}Mi(e){return i0(e).delete(this.clientId)}async xi(){if(this.isPrimary&&!this.Oi(this.Ai,18e5)){this.Ai=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let t=eG(e,"clientMetadata");return t.U().next(e=>{let n=this.Ni(e,18e5),r=e.filter(e=>-1===n.indexOf(e));return ei.forEach(r,e=>t.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.fi)for(let t of e)this.fi.removeItem(this.Li(t.clientId))}}wi(){this.di=this.li.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.gi().then(()=>this.xi()).then(()=>this.wi()))}Fi(e){return!!e&&e.ownerId===this.clientId}Di(e){return this.Pi?ei.resolve(!0):iZ(e).get("owner").next(t=>{if(null!==t&&this.Oi(t.leaseTimestampMs,5e3)&&!this.Bi(t.ownerId)){if(this.Fi(t)&&this.networkEnabled)return!0;if(!this.Fi(t)){if(!t.allowTabSynchronization)throw new S(x.FAILED_PRECONDITION,iY);return!1}}return!(!this.networkEnabled||!this.inForeground)||i0(e).U().next(e=>void 0===this.Ni(e,5e3).find(e=>{if(this.clientId!==e.clientId){let t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&I("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Ur=!1,this.ki(),this.di&&(this.di.cancel(),this.di=null),this.qi(),this.Qi(),await this.mi.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{let t=new e$(e,ey.oe);return this.vi(t).next(()=>this.Mi(t))}),this.mi.close(),this.Ki()}Ni(e,t){return e.filter(e=>this.Oi(e.updateTimeMs,t)&&!this.Bi(e.clientId))}$i(){return this.runTransaction("getActiveClients","readonly",e=>i0(e).U().next(e=>this.Ni(e,18e5).map(e=>e.clientId)))}get started(){return this.Ur}getGlobalsCache(){return this.Wr}getMutationQueue(e,t){return iu.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new r9(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return rq.Pt(this.serializer,e)}getBundleCache(){return this.jr}runTransaction(e,t,n){var r;let i;I("IndexedDbPersistence","Starting transaction:",e);let s=17===(r=this.Ti)?ez:16===r?eK:15===r?eK:14===r?eB:13===r?eB:12===r?eq:11===r?eU:void b();return this.mi.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,r=>(i=new e$(r,this.$r?this.$r.next():ey.oe),"readwrite-primary"===t?this.bi(i).next(e=>!!e||this.Di(i)).next(t=>{if(!t)throw _(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.li.enqueueRetryable(()=>this.Ri(!1)),new S(x.FAILED_PRECONDITION,et);return n(i)}).next(e=>this.Ci(i).next(()=>e)):this.Ui(i).next(()=>n(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Ui(e){return iZ(e).get("owner").next(e=>{if(null!==e&&this.Oi(e.leaseTimestampMs,5e3)&&!this.Bi(e.ownerId)&&!this.Fi(e)&&!(this.Pi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new S(x.FAILED_PRECONDITION,iY)})}Ci(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return iZ(e).put("owner",t)}static p(){return ea.p()}vi(e){let t=iZ(e);return t.get("owner").next(e=>this.Fi(e)?(I("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ei.resolve())}Oi(e,t){let n=Date.now();return!(e<n-t)&&(!(e>n)||(_(`Detected an update time that is in the future: ${e} > ${n}`),!1))}pi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ei=()=>{this.li.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.gi()))},this.document.addEventListener("visibilitychange",this.Ei),this.inForeground="visible"===this.document.visibilityState)}qi(){this.Ei&&(this.document.removeEventListener("visibilitychange",this.Ei),this.Ei=null)}yi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Ii=()=>{this.ki();let e=/(?:Version|Mobile)\/1[456]/;(0,h.nr)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.li.enterRestrictedMode(!0),this.li.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ii))}Qi(){this.Ii&&(this.window.removeEventListener("pagehide",this.Ii),this.Ii=null)}Bi(e){var t;try{let n=null!==(null===(t=this.fi)||void 0===t?void 0:t.getItem(this.Li(e)));return I("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return _("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}ki(){if(this.fi)try{this.fi.setItem(this.Li(this.clientId),String(Date.now()))}catch(e){_("Failed to set zombie client id.",e)}}Ki(){if(this.fi)try{this.fi.removeItem(this.Li(this.clientId))}catch(e){}}Li(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function iZ(e){return eG(e,"owner")}function i0(e){return eG(e,"clientMetadata")}function i1(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class i2{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Wi=n,this.Gi=r}static zi(e,t){let n=nd(),r=nd();for(let e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new i2(e,t.fromCache,n,r)}}class i5{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class i4{constructor(){this.ji=!1,this.Hi=!1,this.Ji=100,this.Yi=(0,h.nr)()?8:eo((0,h.ZQ)())>0?6:4}initialize(e,t){this.Zi=e,this.indexManager=t,this.ji=!0}getDocumentsMatchingQuery(e,t,n,r){let i={result:null};return this.Xi(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.es(e,t,r,n).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let n=new i5;return this.ts(e,t,n).next(r=>{if(i.result=r,this.Hi)return this.ns(e,t,n,r.size)})}).next(()=>i.result)}ns(e,t,n,r){return n.documentReadCount<this.Ji?(v()<=u.$b.DEBUG&&I("QueryEngine","SDK will not create cache indexes for query:",ne(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ji,"documents"),ei.resolve()):(v()<=u.$b.DEBUG&&I("QueryEngine","Query:",ne(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Yi*r?(v()<=u.$b.DEBUG&&I("QueryEngine","The SDK decides to create cache indexes for query:",ne(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,t8(t))):ei.resolve())}Xi(e,t){if(t2(t))return ei.resolve(null);let n=t8(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=t8(t=t6(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let i=nd(...r);return this.Zi.getDocuments(e,i).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{let s=this.rs(t,r);return this.ss(t,s,i,n.readTime)?this.Xi(e,t6(t,null,"F")):this.os(e,s,t,n)}))})))}es(e,t,n,r){return t2(t)||r.isEqual(q.min())?ei.resolve(null):this.Zi.getDocuments(e,n).next(i=>{let s=this.rs(t,i);return this.ss(t,s,n,r)?ei.resolve(null):(v()<=u.$b.DEBUG&&I("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),ne(t)),this.os(e,s,t,Y(r,-1)).next(e=>e))})}rs(e,t){let n=new eX(nr(e));return t.forEach((t,r)=>{nt(e,r)&&(n=n.add(r))}),n}ss(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;let i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}ts(e,t,n){return v()<=u.$b.DEBUG&&I("QueryEngine","Using full collection scan to execute query:",ne(t)),this.Zi.getDocumentsMatchingQuery(e,t,Z.min(),n)}os(e,t,n,r){return this.Zi.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}class i8{constructor(e,t,n,r){this.persistence=e,this._s=t,this.serializer=r,this.us=new eH(F),this.cs=new ni(e=>tW(e),tH),this.ls=new Map,this.hs=e.getRemoteDocumentCache(),this.Gr=e.getTargetCache(),this.jr=e.getBundleCache(),this.Ps(n)}Ps(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new iM(this.hs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.hs.setIndexManager(this.indexManager),this._s.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.us))}}async function i3(e,t){return await e.persistence.runTransaction("Handle user change","readonly",n=>{let r;return e.mutationQueue.getAllMutationBatches(n).next(i=>(r=i,e.Ps(t),e.mutationQueue.getAllMutationBatches(n))).next(t=>{let i=[],s=[],a=nd();for(let e of r)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(n,a).next(e=>({Ts:e,removedBatchIds:i,addedBatchIds:s}))})})}function i6(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Gr.getLastRemoteSnapshotVersion(t))}function i9(e,t,n){let r=nd(),i=nd();return n.forEach(e=>r=r.add(e)),t.getEntries(e,r).next(e=>{let r=ns;return n.forEach((n,s)=>{let a=e.get(n);s.isFoundDocument()!==a.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(q.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!a.isValidDocument()||s.version.compareTo(a.version)>0||0===s.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):I("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",s.version)}),{Is:r,Es:i}})}function i7(e,t){return e.persistence.runTransaction("Allocate target","readwrite",n=>{let r;return e.Gr.getTargetData(n,t).next(i=>i?(r=i,ei.resolve(r)):e.Gr.allocateTargetId(n).next(i=>(r=new rb(t,i,"TargetPurposeListen",n.currentSequenceNumber),e.Gr.addTargetData(n,r).next(()=>r))))}).then(n=>{let r=e.us.get(n.targetId);return(null===r||n.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(e.us=e.us.insert(n.targetId,n),e.cs.set(t,n.targetId)),n})}async function se(e,t,n){let r=e.us.get(t);try{n||await e.persistence.runTransaction("Release target",n?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,r))}catch(e){if(!eh(e))throw e;I("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}e.us=e.us.remove(t),e.cs.delete(r.target)}function st(e,t,n){let r=q.min(),i=nd();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,n){let r=e.cs.get(n);return void 0!==r?ei.resolve(e.us.get(r)):e.Gr.getTargetData(t,n)})(e,s,t8(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,e.Gr.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e._s.getDocumentsMatchingQuery(s,t,n?r:q.min(),n?i:nd())).next(n=>(si(e,nn(t),n),{documents:n,ds:i})))}function sn(e,t){let n=e.Gr,r=e.us.get(t);return r?Promise.resolve(r.target):e.persistence.runTransaction("Get target data","readonly",e=>n.ut(e,t).next(e=>e?e.target:null))}function sr(e,t){let n=e.ls.get(t)||q.min();return e.persistence.runTransaction("Get new document changes","readonly",r=>e.hs.getAllFromCollectionGroup(r,t,Y(n,-1),Number.MAX_SAFE_INTEGER)).then(n=>(si(e,t,n),n))}function si(e,t,n){let r=e.ls.get(t)||q.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.ls.set(t,r)}function ss(e,t){return`firestore_clients_${e}_${t}`}function sa(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function so(e,t){return`firestore_targets_${e}_${t}`}class sl{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static fs(e,t,n){let r=JSON.parse(n),i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(i=new S(r.error.code,r.error.message)),s?new sl(e,t,r.state,i):(_("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}gs(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class su{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static fs(e,t){let n=JSON.parse(t),r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(r=new S(n.error.code,n.error.message)),i?new su(e,n.state,r):(_("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}gs(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class sh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static fs(e,t){let n=JSON.parse(t),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=nf;for(let e=0;r&&e<n.activeTargetIds.length;++e)r=eI(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new sh(e,i):(_("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class sc{constructor(e,t){this.clientId=e,this.onlineState=t}static fs(e){let t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new sc(t.clientId,t.onlineState):(_("SharedClientState",`Failed to parse online state: ${e}`),null)}}class sd{constructor(){this.activeTargetIds=nf}ps(e){this.activeTargetIds=this.activeTargetIds.add(e)}ys(e){this.activeTargetIds=this.activeTargetIds.delete(e)}gs(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class sf{constructor(e,t,n,r,i){var s,a,o;this.window=e,this.li=t,this.persistenceKey=n,this.ws=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Ss=this.bs.bind(this),this.Ds=new eH(F),this.started=!1,this.vs=[];let l=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Cs=ss(this.persistenceKey,this.ws),this.Fs=(s=this.persistenceKey,`firestore_sequence_number_${s}`),this.Ds=this.Ds.insert(this.ws,new sd),this.Ms=RegExp(`^firestore_clients_${l}_([^_]*)$`),this.xs=RegExp(`^firestore_mutations_${l}_(\\d+)(?:_(.*))?$`),this.Os=RegExp(`^firestore_targets_${l}_(\\d+)$`),this.Ns=(a=this.persistenceKey,`firestore_online_state_${a}`),this.Ls=(o=this.persistenceKey,`firestore_bundle_loaded_v2_${o}`),this.window.addEventListener("storage",this.Ss)}static p(e){return!(!e||!e.localStorage)}async start(){for(let e of(await this.syncEngine.$i())){if(e===this.ws)continue;let t=this.getItem(ss(this.persistenceKey,e));if(t){let n=sh.fs(e,t);n&&(this.Ds=this.Ds.insert(n.clientId,n))}}this.Bs();let e=this.storage.getItem(this.Ns);if(e){let t=this.ks(e);t&&this.qs(t)}for(let e of this.vs)this.bs(e);this.vs=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Fs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Qs(this.Ds)}isActiveQueryTarget(e){let t=!1;return this.Ds.forEach((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.Ks(e,"pending")}updateMutationState(e,t,n){this.Ks(e,t,n),this.$s(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){let t=this.storage.getItem(so(this.persistenceKey,e));if(t){let r=su.fs(e,t);r&&(n=r.state)}}return t&&this.Us.ps(e),this.Bs(),n}removeLocalQueryTarget(e){this.Us.ys(e),this.Bs()}isLocalQueryTarget(e){return this.Us.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(so(this.persistenceKey,e))}updateQueryState(e,t,n){this.Ws(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.$s(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Gs(e)}notifyBundleLoaded(e){this.zs(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Ss),this.removeItem(this.Cs),this.started=!1)}getItem(e){let t=this.storage.getItem(e);return I("SharedClientState","READ",e,t),t}setItem(e,t){I("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){I("SharedClientState","REMOVE",e),this.storage.removeItem(e)}bs(e){if(e.storageArea===this.storage){if(I("SharedClientState","EVENT",e.key,e.newValue),e.key===this.Cs)return void _("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.li.enqueueRetryable(async()=>{if(this.started){if(null!==e.key){if(this.Ms.test(e.key)){if(null==e.newValue){let t=this.js(e.key);return this.Hs(t,null)}{let t=this.Js(e.key,e.newValue);if(t)return this.Hs(t.clientId,t)}}else if(this.xs.test(e.key)){if(null!==e.newValue){let t=this.Ys(e.key,e.newValue);if(t)return this.Zs(t)}}else if(this.Os.test(e.key)){if(null!==e.newValue){let t=this.Xs(e.key,e.newValue);if(t)return this.eo(t)}}else if(e.key===this.Ns){if(null!==e.newValue){let t=this.ks(e.newValue);if(t)return this.qs(t)}}else if(e.key===this.Fs){let t=function(e){let t=ey.oe;if(null!=e)try{let n=JSON.parse(e);"number"==typeof n||b(),t=n}catch(e){_("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(e.newValue);t!==ey.oe&&this.sequenceNumberHandler(t)}else if(e.key===this.Ls){let t=this.no(e.newValue);await Promise.all(t.map(e=>this.syncEngine.ro(e)))}}}else this.vs.push(e)})}}get Us(){return this.Ds.get(this.ws)}Bs(){this.setItem(this.Cs,this.Us.gs())}Ks(e,t,n){let r=new sl(this.currentUser,e,t,n),i=sa(this.persistenceKey,this.currentUser,e);this.setItem(i,r.gs())}$s(e){let t=sa(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Gs(e){let t={clientId:this.ws,onlineState:e};this.storage.setItem(this.Ns,JSON.stringify(t))}Ws(e,t,n){let r=so(this.persistenceKey,e),i=new su(e,t,n);this.setItem(r,i.gs())}zs(e){let t=JSON.stringify(Array.from(e));this.setItem(this.Ls,t)}js(e){let t=this.Ms.exec(e);return t?t[1]:null}Js(e,t){let n=this.js(e);return sh.fs(n,t)}Ys(e,t){let n=this.xs.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return sl.fs(new p(i),r,t)}Xs(e,t){let n=Number(this.Os.exec(e)[1]);return su.fs(n,t)}ks(e){return sc.fs(e)}no(e){return JSON.parse(e)}async Zs(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.io(e.batchId,e.state,e.error);I("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}eo(e){return this.syncEngine.so(e.targetId,e.state,e.error)}Hs(e,t){let n=t?this.Ds.insert(e,t):this.Ds.remove(e),r=this.Qs(this.Ds),i=this.Qs(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.oo(s,a).then(()=>{this.Ds=n})}qs(e){this.Ds.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Qs(e){let t=nf;return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class sm{constructor(){this._o=new sd,this.ao={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this._o.ps(e),this.ao[e]||"not-current"}updateQueryState(e,t,n){this.ao[e]=t}removeLocalQueryTarget(e){this._o.ys(e)}isLocalQueryTarget(e){return this._o.activeTargetIds.has(e)}clearQueryState(e){delete this.ao[e]}getAllActiveQueryTargets(){return this._o.activeTargetIds}isActiveQueryTarget(e){return this._o.activeTargetIds.has(e)}start(){return this._o=new sd,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class sg{uo(e){}shutdown(){}}class sp{constructor(){this.co=()=>this.lo(),this.ho=()=>this.Po(),this.To=[],this.Io()}uo(e){this.To.push(e)}shutdown(){window.removeEventListener("online",this.co),window.removeEventListener("offline",this.ho)}Io(){window.addEventListener("online",this.co),window.addEventListener("offline",this.ho)}lo(){for(let e of(I("ConnectivityMonitor","Network connectivity changed: AVAILABLE"),this.To))e(0)}Po(){for(let e of(I("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE"),this.To))e(1)}static p(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let sy=null;function sw(){return null===sy?sy=0x10000000+Math.round(0x80000000*Math.random()):sy++,"0x"+sy.toString(16)}let sv={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class sI{constructor(e){this.Eo=e.Eo,this.Ao=e.Ao}Ro(e){this.Vo=e}mo(e){this.fo=e}po(e){this.yo=e}onMessage(e){this.wo=e}close(){this.Ao()}send(e){this.Eo(e)}So(){this.Vo()}bo(){this.fo()}Do(e){this.yo(e)}vo(e){this.wo(e)}}let s_="WebChannelConnection";class sT extends class{get Co(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Fo=t+"://"+e.host,this.Mo=`projects/${n}/databases/${r}`,this.xo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Oo(e,t,n,r,i){let s=sw(),a=this.No(e,t.toUriEncodedString());I("RestConnection",`Sending RPC '${e}' ${s}:`,a,n);let o={"google-cloud-resource-prefix":this.Mo,"x-goog-request-params":this.xo};return this.Lo(o,r,i),this.Bo(e,a,o,n).then(t=>(I("RestConnection",`Received RPC '${e}' ${s}: `,t),t),t=>{throw T("RestConnection",`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",n),t})}ko(e,t,n,r,i,s){return this.Oo(e,t,n,r,i)}Lo(e,t,n){e["X-Goog-Api-Client"]=function(){return"gl-js/ fire/"+y}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,n)=>e[n]=t),n&&n.headers.forEach((t,n)=>e[n]=t)}No(e,t){let n=sv[e];return`${this.Fo}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Bo(e,t,n,r){let i=sw();return new Promise((s,a)=>{let o=new d.ZS;o.setWithCredentials(!0),o.listenOnce(d.Bx.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case d.O4.NO_ERROR:let t=o.getResponseJson();I(s_,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case d.O4.TIMEOUT:I(s_,`RPC '${e}' ${i} timed out`),a(new S(x.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(I(s_,`RPC '${e}' ${i} failed with status:`,n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);let t=null==e?void 0:e.error;if(t&&t.status&&t.message){let e=function(e){let t=e.toLowerCase().replace(/_/g,"-");return Object.values(x).indexOf(t)>=0?t:x.UNKNOWN}(t.status);a(new S(e,t.message))}else a(new S(x.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new S(x.UNAVAILABLE,"Connection failed."));break;default:b()}}finally{I(s_,`RPC '${e}' ${i} completed.`)}});let l=JSON.stringify(r);I(s_,`RPC '${e}' ${i} sending request:`,r),o.send(t,"POST",l,n,15)})}qo(e,t,n){let i=sw(),s=[this.Fo,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=(0,d.fF)(),o=(0,d.Ao)(),l={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(l.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(l.useFetchStreams=!0),this.Lo(l.initMessageHeaders,t,n),l.encodeInitMessageHeaders=!0;let h=s.join("");I(s_,`Creating RPC '${e}' stream ${i}: ${h}`,l);let c=a.createWebChannel(h,l),f=!1,m=!1,g=new sI({Eo:t=>{m?I(s_,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(f||(I(s_,`Opening RPC '${e}' stream ${i} transport.`),c.open(),f=!0),I(s_,`RPC '${e}' stream ${i} sending:`,t),c.send(t))},Ao:()=>c.close()}),p=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return p(c,d.iO.EventType.OPEN,()=>{m||(I(s_,`RPC '${e}' stream ${i} transport opened.`),g.So())}),p(c,d.iO.EventType.CLOSE,()=>{m||(m=!0,I(s_,`RPC '${e}' stream ${i} transport closed`),g.Do())}),p(c,d.iO.EventType.ERROR,t=>{m||(m=!0,T(s_,`RPC '${e}' stream ${i} transport errored:`,t),g.Do(new S(x.UNAVAILABLE,"The operation could not be completed")))}),p(c,d.iO.EventType.MESSAGE,t=>{var n;if(!m){let s=t.data[0];s||b();let a=(null==s?void 0:s.error)||(null===(n=s[0])||void 0===n?void 0:n.error);if(a){I(s_,`RPC '${e}' stream ${i} received error:`,a);let t=a.status,n=function(e){let t=r[e];if(void 0!==t)return nj(t)}(t),s=a.message;void 0===n&&(n=x.INTERNAL,s="Unknown error status: "+t+" with message "+a.message),m=!0,g.Do(new S(n,s)),c.close()}else I(s_,`RPC '${e}' stream ${i} received:`,s),g.vo(s)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?I(s_,`RPC '${e}' stream ${i} detected buffering proxy`):t.stat===d.ro.NOPROXY&&I(s_,`RPC '${e}' stream ${i} detected no buffering proxy`)}),setTimeout(()=>{g.bo()},0),g}}function sE(){return"undefined"!=typeof window?window:null}function sb(){return"undefined"!=typeof document?document:null}function sx(e){return new re(e,!0)}class sS{constructor(e,t,n=1e3,r=1.5,i=6e4){this.li=e,this.timerId=t,this.Qo=n,this.Ko=r,this.$o=i,this.Uo=0,this.Wo=null,this.Go=Date.now(),this.reset()}reset(){this.Uo=0}zo(){this.Uo=this.$o}jo(e){this.cancel();let t=Math.floor(this.Uo+this.Ho()),n=Math.max(0,Date.now()-this.Go),r=Math.max(0,t-n);r>0&&I("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Uo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Wo=this.li.enqueueAfterDelay(this.timerId,r,()=>(this.Go=Date.now(),e())),this.Uo*=this.Ko,this.Uo<this.Qo&&(this.Uo=this.Qo),this.Uo>this.$o&&(this.Uo=this.$o)}Jo(){null!==this.Wo&&(this.Wo.skipDelay(),this.Wo=null)}cancel(){null!==this.Wo&&(this.Wo.cancel(),this.Wo=null)}Ho(){return(Math.random()-.5)*this.Uo}}class sD{constructor(e,t,n,r,i,s,a,o){this.li=e,this.Yo=n,this.Zo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Xo=0,this.e_=null,this.t_=null,this.stream=null,this.n_=0,this.r_=new sS(e,t)}i_(){return 1===this.state||5===this.state||this.s_()}s_(){return 2===this.state||3===this.state}start(){this.n_=0,4!==this.state?this.auth():this.o_()}async stop(){this.i_()&&await this.close(0)}__(){this.state=0,this.r_.reset()}a_(){this.s_()&&null===this.e_&&(this.e_=this.li.enqueueAfterDelay(this.Yo,6e4,()=>this.u_()))}c_(e){this.l_(),this.stream.send(e)}async u_(){if(this.s_())return this.close(0)}l_(){this.e_&&(this.e_.cancel(),this.e_=null)}h_(){this.t_&&(this.t_.cancel(),this.t_=null)}async close(e,t){this.l_(),this.h_(),this.r_.cancel(),this.Xo++,4!==e?this.r_.reset():t&&t.code===x.RESOURCE_EXHAUSTED?(_(t.toString()),_("Using maximum backoff delay to prevent overloading the backend."),this.r_.zo()):t&&t.code===x.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.P_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.po(t)}P_(){}auth(){this.state=1;let e=this.T_(this.Xo),t=this.Xo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.Xo===t&&this.I_(e,n)},t=>{e(()=>{let e=new S(x.UNKNOWN,"Fetching auth token failed: "+t.message);return this.E_(e)})})}I_(e,t){let n=this.T_(this.Xo);this.stream=this.d_(e,t),this.stream.Ro(()=>{n(()=>this.listener.Ro())}),this.stream.mo(()=>{n(()=>(this.state=2,this.t_=this.li.enqueueAfterDelay(this.Zo,1e4,()=>(this.s_()&&(this.state=3),Promise.resolve())),this.listener.mo()))}),this.stream.po(e=>{n(()=>this.E_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.n_?this.A_(e):this.onNext(e))})}o_(){this.state=5,this.r_.jo(async()=>{this.state=0,this.start()})}E_(e){return I("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}T_(e){return t=>{this.li.enqueueAndForget(()=>this.Xo===e?t():(I("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class sC extends sD{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}d_(e,t){return this.connection.qo("Listen",e,t)}A_(e){return this.onNext(e)}onNext(e){this.r_.reset();let t=function(e,t){let n;if("targetChange"in t){var r,i;t.targetChange;let s="NO_CHANGE"===(r=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===r?1:"REMOVE"===r?2:"CURRENT"===r?3:"RESET"===r?4:b(),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(void 0===i||"string"==typeof i||b(),e5.fromBase64String(i||"")):(void 0===i||i instanceof m||i instanceof Uint8Array||b(),e5.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;n=new n2(s,a,o,l&&new S(void 0===l.code?x.UNKNOWN:nj(l.code),l.message||"")||null)}else if("documentChange"in t){t.documentChange;let r=t.documentChange;r.document,r.document.name,r.document.updateTime;let i=ru(e,r.document.name),s=ri(r.document.updateTime),a=r.document.createTime?ri(r.document.createTime):q.min(),o=new tb({mapValue:{fields:r.document.fields}}),l=tx.newFoundDocument(i,s,a,o);n=new n0(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let i=ru(e,r.document),s=r.readTime?ri(r.readTime):q.min(),a=tx.newNoDocument(i,s);n=new n0([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let i=ru(e,r.document);n=new n0([],r.removedTargetIds||[],i,null)}else{if(!("filter"in t))return b();{t.filter;let e=t.filter;e.targetId;let{count:r=0,unchangedNames:i}=e,s=new nG(r,i);n=new n1(e.targetId,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return q.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?q.min():t.readTime?ri(t.readTime):q.min()}(e);return this.listener.R_(t,n)}V_(e){let t={};t.database=rd(this.serializer),t.addTarget=function(e,t){let n;let r=t.target;if((n=tJ(r)?{documents:rw(e,r)}:{query:rv(e,r).ct}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=rr(e,t.resumeToken);let r=rt(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(q.min())>0){n.readTime=rn(e,t.snapshotVersion.toTimestamp());let r=rt(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);let n=function(e,t){let n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return b()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.c_(t)}m_(e){let t={};t.database=rd(this.serializer),t.removeTarget=e,this.c_(t)}}class sN extends sD{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}get f_(){return this.n_>0}start(){this.lastStreamToken=void 0,super.start()}P_(){this.f_&&this.g_([])}d_(e,t){return this.connection.qo("Write",e,t)}A_(e){return e.streamToken||b(),this.lastStreamToken=e.streamToken,e.writeResults&&0!==e.writeResults.length&&b(),this.listener.p_()}onNext(e){var t,n;e.streamToken||b(),this.lastStreamToken=e.streamToken,this.r_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(void 0!==n||b(),t.map(e=>{let t;return(t=e.updateTime?ri(e.updateTime):ri(n)).isEqual(q.min())&&(t=ri(n)),new nC(t,e.transformResults||[])})):[]),i=ri(e.commitTime);return this.listener.y_(i,r)}w_(){let e={};e.database=rd(this.serializer),this.c_(e)}g_(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>rp(this.serializer,e))};this.c_(t)}}class sk extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.S_=!1}b_(){if(this.S_)throw new S(x.FAILED_PRECONDITION,"The client has already been terminated.")}Oo(e,t,n,r){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.Oo(e,ra(t,n),r,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===x.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new S(x.UNKNOWN,e.toString())})}ko(e,t,n,r,i){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.ko(e,ra(t,n),r,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===x.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new S(x.UNKNOWN,e.toString())})}terminate(){this.S_=!0,this.connection.terminate()}}class sA{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.D_=0,this.v_=null,this.C_=!0}F_(){0===this.D_&&(this.M_("Unknown"),this.v_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.v_=null,this.x_("Backend didn't respond within 10 seconds."),this.M_("Offline"),Promise.resolve())))}O_(e){"Online"===this.state?this.M_("Unknown"):(this.D_++,this.D_>=1&&(this.N_(),this.x_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.M_("Offline")))}set(e){this.N_(),this.D_=0,"Online"===e&&(this.C_=!1),this.M_(e)}M_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}x_(e){let t=`Could not reach Cloud Firestore backend. ${e}
This 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.C_?(_(t),this.C_=!1):I("OnlineStateTracker",t)}N_(){null!==this.v_&&(this.v_.cancel(),this.v_=null)}}class sR{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.L_=[],this.B_=new Map,this.k_=new Set,this.q_=[],this.Q_=i,this.Q_.uo(e=>{n.enqueueAndForget(async()=>{sB(this)&&(I("RemoteStore","Restarting streams for network reachability change."),await async function(e){e.k_.add(4),await sL(e),e.K_.set("Unknown"),e.k_.delete(4),await sV(e)}(this))})}),this.K_=new sA(n,r)}}async function sV(e){if(sB(e))for(let t of e.q_)await t(!0)}async function sL(e){for(let t of e.q_)await t(!1)}function sM(e,t){e.B_.has(t.targetId)||(e.B_.set(t.targetId,t),sq(e)?sU(e):s5(e).s_()&&sF(e,t))}function sO(e,t){let n=s5(e);e.B_.delete(t),n.s_()&&sP(e,t),0===e.B_.size&&(n.s_()?n.a_():sB(e)&&e.K_.set("Unknown"))}function sF(e,t){if(e.U_.xe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(q.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}s5(e).V_(t)}function sP(e,t){e.U_.xe(t),s5(e).m_(t)}function sU(e){e.U_=new n4({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),ut:t=>e.B_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),s5(e).start(),e.K_.F_()}function sq(e){return sB(e)&&!s5(e).i_()&&e.B_.size>0}function sB(e){return 0===e.k_.size}async function sK(e){e.K_.set("Online")}async function sz(e){e.B_.forEach((t,n)=>{sF(e,t)})}async function s$(e,t){e.U_=void 0,sq(e)?(e.K_.O_(t),sU(e)):e.K_.set("Unknown")}async function sG(e,t,n){if(e.K_.set("Online"),t instanceof n2&&2===t.state&&t.cause)try{await async function(e,t){let n=t.cause;for(let r of t.targetIds)e.B_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.B_.delete(r),e.U_.removeTarget(r))}(e,t)}catch(n){I("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await sj(e,n)}else if(t instanceof n0?e.U_.$e(t):t instanceof n1?e.U_.Je(t):e.U_.Ge(t),!n.isEqual(q.min()))try{let t=await i6(e.localStore);n.compareTo(t)>=0&&await function(e,t){let n=e.U_.it(t);return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){let i=e.B_.get(r);i&&e.B_.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{let r=e.B_.get(t);if(!r)return;e.B_.set(t,r.withResumeToken(e5.EMPTY_BYTE_STRING,r.snapshotVersion)),sP(e,t);let i=new rb(r.target,t,n,r.sequenceNumber);sF(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){I("RemoteStore","Failed to raise snapshot:",t),await sj(e,t)}}async function sj(e,t,n){if(!eh(t))throw t;e.k_.add(1),await sL(e),e.K_.set("Offline"),n||(n=()=>i6(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{I("RemoteStore","Retrying IndexedDB access"),await n(),e.k_.delete(1),await sV(e)})}function sQ(e,t){return t().catch(n=>sj(e,n,t))}async function sW(e){let t=s4(e),n=e.L_.length>0?e.L_[e.L_.length-1].batchId:-1;for(;sB(e)&&e.L_.length<10;)try{let r=await function(e,t){return e.persistence.runTransaction("Get next mutation batch","readonly",n=>(void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)))}(e.localStore,n);if(null===r){0===e.L_.length&&t.a_();break}n=r.batchId,function(e,t){e.L_.push(t);let n=s4(e);n.s_()&&n.f_&&n.g_(t.mutations)}(e,r)}catch(t){await sj(e,t)}sH(e)&&sJ(e)}function sH(e){return sB(e)&&!s4(e).i_()&&e.L_.length>0}function sJ(e){s4(e).start()}async function sY(e){s4(e).w_()}async function sX(e){let t=s4(e);for(let n of e.L_)t.g_(n.mutations)}async function sZ(e,t,n){let r=e.L_.shift(),i=nz.from(r,t,n);await sQ(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await sW(e)}async function s0(e,t){t&&s4(e).f_&&await async function(e,t){var n;if(function(e){switch(e){default:return b();case x.CANCELLED:case x.UNKNOWN:case x.DEADLINE_EXCEEDED:case x.RESOURCE_EXHAUSTED:case x.INTERNAL:case x.UNAVAILABLE:case x.UNAUTHENTICATED:return!1;case x.INVALID_ARGUMENT:case x.NOT_FOUND:case x.ALREADY_EXISTS:case x.PERMISSION_DENIED:case x.FAILED_PRECONDITION:case x.ABORTED:case x.OUT_OF_RANGE:case x.UNIMPLEMENTED:case x.DATA_LOSS:return!0}}(n=t.code)&&n!==x.ABORTED){let n=e.L_.shift();s4(e).__(),await sQ(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await sW(e)}}(e,t),sH(e)&&sJ(e)}async function s1(e,t){e.asyncQueue.verifyOperationInProgress(),I("RemoteStore","RemoteStore received new credentials");let n=sB(e);e.k_.add(3),await sL(e),n&&e.K_.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.k_.delete(3),await sV(e)}async function s2(e,t){t?(e.k_.delete(2),await sV(e)):t||(e.k_.add(2),await sL(e),e.K_.set("Unknown"))}function s5(e){var t,n,r;return e.W_||(e.W_=(t=e.datastore,n=e.asyncQueue,r={Ro:sK.bind(null,e),mo:sz.bind(null,e),po:s$.bind(null,e),R_:sG.bind(null,e)},t.b_(),new sC(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r)),e.q_.push(async t=>{t?(e.W_.__(),sq(e)?sU(e):e.K_.set("Unknown")):(await e.W_.stop(),e.U_=void 0)})),e.W_}function s4(e){var t,n,r;return e.G_||(e.G_=(t=e.datastore,n=e.asyncQueue,r={Ro:()=>Promise.resolve(),mo:sY.bind(null,e),po:s0.bind(null,e),p_:sX.bind(null,e),y_:sZ.bind(null,e)},t.b_(),new sN(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r)),e.q_.push(async t=>{t?(e.G_.__(),await sW(e)):(await e.G_.stop(),e.L_.length>0&&(I("RemoteStore",`Stopping write stream with ${e.L_.length} pending writes`),e.L_=[]))})),e.G_}class s8{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new D,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){let s=new s8(e,t,Date.now()+n,r,i);return s.start(n),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new S(x.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function s3(e,t){if(_("AsyncQueue",`${t}: ${e}`),eh(e))return new S(x.UNAVAILABLE,`${t}: ${e}`);throw e}class s6{static emptySet(e){return new s6(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||G.comparator(t.key,n.key):(e,t)=>G.comparator(e.key,t.key),this.keyedMap=no(),this.sortedSet=new eH(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof s6)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"}copy(e,t){let n=new s6;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class s9{constructor(){this.z_=new eH(G.comparator)}track(e){let t=e.doc.key,n=this.z_.get(t);n?0!==e.type&&3===n.type?this.z_=this.z_.insert(t,e):3===e.type&&1!==n.type?this.z_=this.z_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.z_=this.z_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.z_=this.z_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.z_=this.z_.remove(t):1===e.type&&2===n.type?this.z_=this.z_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.z_=this.z_.insert(t,{type:2,doc:e.doc}):b():this.z_=this.z_.insert(t,e)}j_(){let e=[];return this.z_.inorderTraversal((t,n)=>{e.push(n)}),e}}class s7{constructor(e,t,n,r,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,i){let s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new s7(e,t,s6.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&t9(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class ae{constructor(){this.H_=void 0,this.J_=[]}Y_(){return this.J_.some(e=>e.Z_())}}class at{constructor(){this.queries=an(),this.onlineState="Unknown",this.X_=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=an(),n.forEach((e,n)=>{for(let e of n.J_)e.onError(t)})}(this,new S(x.ABORTED,"Firestore shutting down"))}}function an(){return new ni(e=>t7(e),t9)}async function ar(e,t){let n=3,r=t.query,i=e.queries.get(r);i?!i.Y_()&&t.Z_()&&(n=2):(i=new ae,n=t.Z_()?0:1);try{switch(n){case 0:i.H_=await e.onListen(r,!0);break;case 1:i.H_=await e.onListen(r,!1);break;case 2:await e.onFirstRemoteStoreListen(r)}}catch(n){let e=s3(n,`Initialization of query '${ne(t.query)}' failed`);return void t.onError(e)}e.queries.set(r,i),i.J_.push(t),t.ea(e.onlineState),i.H_&&t.ta(i.H_)&&ao(e)}async function ai(e,t){let n=t.query,r=3,i=e.queries.get(n);if(i){let e=i.J_.indexOf(t);e>=0&&(i.J_.splice(e,1),0===i.J_.length?r=t.Z_()?0:1:!i.Y_()&&t.Z_()&&(r=2))}switch(r){case 0:return e.queries.delete(n),e.onUnlisten(n,!0);case 1:return e.queries.delete(n),e.onUnlisten(n,!1);case 2:return e.onLastRemoteStoreUnlisten(n);default:return}}function as(e,t){let n=!1;for(let r of t){let t=r.query,i=e.queries.get(t);if(i){for(let e of i.J_)e.ta(r)&&(n=!0);i.H_=r}}n&&ao(e)}function aa(e,t,n){let r=e.queries.get(t);if(r)for(let e of r.J_)e.onError(n);e.queries.delete(t)}function ao(e){e.X_.forEach(e=>{e.next()})}(a=s||(s={})).na="default",a.Cache="cache";class al{constructor(e,t,n){this.query=e,this.ra=t,this.ia=!1,this.sa=null,this.onlineState="Unknown",this.options=n||{}}ta(e){if(!this.options.includeMetadataChanges){let t=[];for(let n of e.docChanges)3!==n.type&&t.push(n);e=new s7(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.ia?this.oa(e)&&(this.ra.next(e),t=!0):this._a(e,this.onlineState)&&(this.aa(e),t=!0),this.sa=e,t}onError(e){this.ra.error(e)}ea(e){this.onlineState=e;let t=!1;return this.sa&&!this.ia&&this._a(this.sa,e)&&(this.aa(this.sa),t=!0),t}_a(e,t){return!(e.fromCache&&this.Z_())||(!this.options.ua||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}oa(e){if(e.docChanges.length>0)return!0;let t=this.sa&&this.sa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}aa(e){e=s7.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ia=!0,this.ra.next(e)}Z_(){return this.options.source!==s.Cache}}class au{constructor(e){this.key=e}}class ah{constructor(e){this.key=e}}class ac{constructor(e,t){this.query=e,this.da=t,this.Aa=null,this.hasCachedResults=!1,this.current=!1,this.Ra=nd(),this.mutatedKeys=nd(),this.Va=nr(e),this.ma=new s6(this.Va)}get fa(){return this.da}ga(e,t){let n=t?t.pa:new s9,r=t?t.ma:this.ma,i=t?t.mutatedKeys:this.mutatedKeys,s=r,a=!1,o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal((e,t)=>{let u=r.get(e),h=nt(this.query,t)?t:null,c=!!u&&this.mutatedKeys.has(u.key),d=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations),f=!1;u&&h?u.data.isEqual(h.data)?c!==d&&(n.track({type:3,doc:h}),f=!0):this.ya(u,h)||(n.track({type:2,doc:h}),f=!0,(o&&this.Va(h,o)>0||l&&0>this.Va(h,l))&&(a=!0)):!u&&h?(n.track({type:0,doc:h}),f=!0):u&&!h&&(n.track({type:1,doc:u}),f=!0,(o||l)&&(a=!0)),f&&(h?(s=s.add(h),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;){let e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{ma:s,pa:n,ss:a,mutatedKeys:i}}ya(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){let i=this.ma;this.ma=e.ma,this.mutatedKeys=e.mutatedKeys;let s=e.pa.j_();s.sort((e,t)=>(function(e,t){let n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return b()}};return n(e)-n(t)})(e.type,t.type)||this.Va(e.doc,t.doc)),this.wa(n),r=null!=r&&r;let a=t&&!r?this.Sa():[],o=0===this.Ra.size&&this.current&&!r?1:0,l=o!==this.Aa;return(this.Aa=o,0!==s.length||l)?{snapshot:new s7(this.query,e.ma,i,s,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),ba:a}:{ba:a}}ea(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ma:this.ma,pa:new s9,mutatedKeys:this.mutatedKeys,ss:!1},!1)):{ba:[]}}Da(e){return!this.da.has(e)&&!!this.ma.has(e)&&!this.ma.get(e).hasLocalMutations}wa(e){e&&(e.addedDocuments.forEach(e=>this.da=this.da.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.da=this.da.delete(e)),this.current=e.current)}Sa(){if(!this.current)return[];let e=this.Ra;this.Ra=nd(),this.ma.forEach(e=>{this.Da(e.key)&&(this.Ra=this.Ra.add(e.key))});let t=[];return e.forEach(e=>{this.Ra.has(e)||t.push(new ah(e))}),this.Ra.forEach(n=>{e.has(n)||t.push(new au(n))}),t}va(e){this.da=e.ds,this.Ra=nd();let t=this.ga(e.documents);return this.applyChanges(t,!0)}Ca(){return s7.fromInitialDocuments(this.query,this.ma,this.mutatedKeys,0===this.Aa,this.hasCachedResults)}}class ad{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class af{constructor(e){this.key=e,this.Fa=!1}}class am{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Ma={},this.xa=new ni(e=>t7(e),t9),this.Oa=new Map,this.Na=new Set,this.La=new eH(G.comparator),this.Ba=new Map,this.ka=new iU,this.qa={},this.Qa=new Map,this.Ka=ig.Qn(),this.onlineState="Unknown",this.$a=void 0}get isPrimaryClient(){return!0===this.$a}}async function ag(e,t,n=!0){let r;let i=aG(e),s=i.xa.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),r=s.view.Ca()):r=await ay(i,t,n,!0),r}async function ap(e,t){let n=aG(e);await ay(n,t,!0,!1)}async function ay(e,t,n,r){let i;let s=await i7(e.localStore,t8(t)),a=s.targetId,o=e.sharedClientState.addLocalQueryTarget(a,n);return r&&(i=await aw(e,t,a,"current"===o,s.resumeToken)),e.isPrimaryClient&&n&&sM(e.remoteStore,s),i}async function aw(e,t,n,r,i){e.Ua=(t,n,r)=>(async function(e,t,n,r){let i=t.view.ga(n);i.ss&&(i=await st(e.localStore,t.query,!1).then(({documents:e})=>t.view.ga(e,i)));let s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s,a);return aA(e,t.targetId,o.ba),o.snapshot})(e,t,n,r);let s=await st(e.localStore,t,!0),a=new ac(t,s.ds),o=a.ga(s.documents),l=nZ.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);aA(e,n,u.ba);let h=new ad(t,n,a);return e.xa.set(t,h),e.Oa.has(n)?e.Oa.get(n).push(t):e.Oa.set(n,[t]),u.snapshot}async function av(e,t,n){let r=e.xa.get(t),i=e.Oa.get(r.targetId);if(i.length>1)return e.Oa.set(r.targetId,i.filter(e=>!t9(e,t))),void e.xa.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(r.targetId),e.sharedClientState.isActiveQueryTarget(r.targetId)||await se(e.localStore,r.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(r.targetId),n&&sO(e.remoteStore,r.targetId),aN(e,r.targetId)}).catch(er)):(aN(e,r.targetId),await se(e.localStore,r.targetId,!0))}async function aI(e,t){let n=e.xa.get(t),r=e.Oa.get(n.targetId);e.isPrimaryClient&&1===r.length&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),sO(e.remoteStore,n.targetId))}async function a_(e,t,n){let r=aj(e);try{var i;let e;let s=await function(e,t){let n,r;let i=U.now(),s=t.reduce((e,t)=>e.add(t.key),nd());return e.persistence.runTransaction("Locally write mutations","readwrite",a=>{let o=ns,l=nd();return e.hs.getEntries(a,s).next(e=>{(o=e).forEach((e,t)=>{t.isValidDocument()||(l=l.add(e))})}).next(()=>e.localDocuments.getOverlayedDocuments(a,o)).next(r=>{n=r;let s=[];for(let e of t){let t=function(e,t){let n=null;for(let r of e.fieldTransforms){let e=t.data.field(r.field),i=nw(r.transform,e||null);null!=i&&(null===n&&(n=tb.empty()),n.set(r.field,i))}return n||null}(e,n.get(e.key).overlayedDocument);null!=t&&s.push(new nO(e.key,t,function e(t){let n=[];return eQ(t.fields,(t,r)=>{let i=new $([t]);if(ty(r)){let t=e(r.mapValue).fields;if(0===t.length)n.push(i);else for(let e of t)n.push(i.child(e))}else n.push(i)}),new e1(n)}(t.value.mapValue),nN.exists(!0)))}return e.mutationQueue.addMutationBatch(a,i,s,t)}).next(t=>{r=t;let i=t.applyToLocalDocumentSet(n,l);return e.documentOverlayCache.saveOverlays(a,t.batchId,i)})}).then(()=>({batchId:r.batchId,changes:nl(n)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(s.batchId),i=s.batchId,(e=r.qa[r.currentUser.toKey()])||(e=new eH(F)),e=e.insert(i,n),r.qa[r.currentUser.toKey()]=e,await aV(r,s.changes),await sW(r.remoteStore)}catch(t){let e=s3(t,"Failed to persist write");n.reject(e)}}async function aT(e,t){try{let n=await function(e,t){let n=t.snapshotVersion,r=e.us;return e.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{let s=e.hs.newChangeBuffer({trackRemovals:!0});r=e.us;let a=[];t.targetChanges.forEach((s,o)=>{var l;let u=r.get(o);if(!u)return;a.push(e.Gr.removeMatchingKeys(i,s.removedDocuments,o).next(()=>e.Gr.addMatchingKeys(i,s.addedDocuments,o)));let h=u.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(o)?h=h.withResumeToken(e5.EMPTY_BYTE_STRING,q.min()).withLastLimboFreeSnapshotVersion(q.min()):s.resumeToken.approximateByteSize()>0&&(h=h.withResumeToken(s.resumeToken,n)),r=r.insert(o,h),l=h,(0===u.resumeToken.approximateByteSize()||l.snapshotVersion.toMicroseconds()-u.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&a.push(e.Gr.updateTargetData(i,h))});let o=ns,l=nd();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&a.push(e.persistence.referenceDelegate.updateLimboDocument(i,n))}),a.push(i9(i,s,t.documentUpdates).next(e=>{o=e.Is,l=e.Es})),!n.isEqual(q.min())){let t=e.Gr.getLastRemoteSnapshotVersion(i).next(t=>e.Gr.setTargetsMetadata(i,i.currentSequenceNumber,n));a.push(t)}return ei.waitFor(a).next(()=>s.apply(i)).next(()=>e.localDocuments.getLocalViewOfDocuments(i,o,l)).next(()=>o)}).then(t=>(e.us=r,t))}(e.localStore,t);t.targetChanges.forEach((t,n)=>{let r=e.Ba.get(n);r&&(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1||b(),t.addedDocuments.size>0?r.Fa=!0:t.modifiedDocuments.size>0?r.Fa||b():t.removedDocuments.size>0&&(r.Fa||b(),r.Fa=!1))}),await aV(e,n,t)}catch(e){await er(e)}}function aE(e,t,n){var r;if(e.isPrimaryClient&&0===n||!e.isPrimaryClient&&1===n){let n;let i=[];e.xa.forEach((e,n)=>{let r=n.view.ea(t);r.snapshot&&i.push(r.snapshot)}),(r=e.eventManager).onlineState=t,n=!1,r.queries.forEach((e,r)=>{for(let e of r.J_)e.ea(t)&&(n=!0)}),n&&ao(r),i.length&&e.Ma.R_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function ab(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Ba.get(t),i=r&&r.key;if(i){let n=new eH(G.comparator);n=n.insert(i,tx.newNoDocument(i,q.min()));let r=nd().add(i),s=new nX(q.min(),new Map,new eH(F),n,r);await aT(e,s),e.La=e.La.remove(i),e.Ba.delete(t),aR(e)}else await se(e.localStore,t,!1).then(()=>aN(e,t,n)).catch(er)}async function ax(e,t){var n;let r=t.batch.batchId;try{let i=await (n=e.localStore).persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),i=n.hs.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let i=n.batch,s=i.keys(),a=ei.resolve();return s.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let s=n.docVersions.get(e);null!==s||b(),0>t.version.compareTo(s)&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))})(n,e,t,i).next(()=>i.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=nd();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))).next(()=>n.localDocuments.getDocuments(e,r))});aC(e,r,null),aD(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await aV(e,i)}catch(e){await er(e)}}async function aS(e,t,n){var r;try{let i=await (r=e.localStore).persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(null!==t||b(),n=t.keys(),r.mutationQueue.removeMutationBatch(e,t))).next(()=>r.mutationQueue.performConsistencyCheck(e)).next(()=>r.documentOverlayCache.removeOverlaysForBatchId(e,n,t)).next(()=>r.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,n)).next(()=>r.localDocuments.getDocuments(e,n))});aC(e,t,n),aD(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await aV(e,i)}catch(e){await er(e)}}function aD(e,t){(e.Qa.get(t)||[]).forEach(e=>{e.resolve()}),e.Qa.delete(t)}function aC(e,t,n){let r=e.qa[e.currentUser.toKey()];if(r){let i=r.get(t);i&&(n?i.reject(n):i.resolve(),r=r.remove(t)),e.qa[e.currentUser.toKey()]=r}}function aN(e,t,n=null){for(let r of(e.sharedClientState.removeLocalQueryTarget(t),e.Oa.get(t)))e.xa.delete(r),n&&e.Ma.Wa(r,n);e.Oa.delete(t),e.isPrimaryClient&&e.ka.yr(t).forEach(t=>{e.ka.containsKey(t)||ak(e,t)})}function ak(e,t){e.Na.delete(t.path.canonicalString());let n=e.La.get(t);null!==n&&(sO(e.remoteStore,n),e.La=e.La.remove(t),e.Ba.delete(n),aR(e))}function aA(e,t,n){for(let r of n)r instanceof au?(e.ka.addReference(r.key,t),function(e,t){let n=t.key,r=n.path.canonicalString();e.La.get(n)||e.Na.has(r)||(I("SyncEngine","New document in limbo: "+n),e.Na.add(r),aR(e))}(e,r)):r instanceof ah?(I("SyncEngine","Document no longer in limbo: "+r.key),e.ka.removeReference(r.key,t),e.ka.containsKey(r.key)||ak(e,r.key)):b()}function aR(e){for(;e.Na.size>0&&e.La.size<e.maxConcurrentLimboResolutions;){let t=e.Na.values().next().value;e.Na.delete(t);let n=new G(K.fromString(t)),r=e.Ka.next();e.Ba.set(r,new af(n)),e.La=e.La.insert(n,r),sM(e.remoteStore,new rb(t8(t1(n.path)),r,"TargetPurposeLimboResolution",ey.oe))}}async function aV(e,t,n){let r=[],i=[],s=[];e.xa.isEmpty()||(e.xa.forEach((a,o)=>{s.push(e.Ua(o,t,n).then(t=>{var s;if((t||n)&&e.isPrimaryClient){let r=t?!t.fromCache:null===(s=null==n?void 0:n.targetChanges.get(o.targetId))||void 0===s?void 0:s.current;e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=i2.zi(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.Ma.R_(r),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>ei.forEach(t,t=>ei.forEach(t.Wi,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>ei.forEach(t.Gi,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!eh(e))throw e;I("LocalStore","Failed to update sequence numbers: "+e)}for(let n of t){let t=n.targetId;if(!n.fromCache){let n=e.us.get(t),r=n.snapshotVersion,i=n.withLastLimboFreeSnapshotVersion(r);e.us=e.us.insert(t,i)}}}(e.localStore,i))}async function aL(e,t){var n;if(!e.currentUser.isEqual(t)){I("SyncEngine","User change. New user:",t.toKey());let r=await i3(e.localStore,t);e.currentUser=t,n="'waitForPendingWrites' promise is rejected due to a user change.",e.Qa.forEach(e=>{e.forEach(e=>{e.reject(new S(x.CANCELLED,n))})}),e.Qa.clear(),e.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await aV(e,r.Ts)}}function aM(e,t){let n=e.Ba.get(t);if(n&&n.Fa)return nd().add(n.key);{let n=nd(),r=e.Oa.get(t);if(!r)return n;for(let t of r){let r=e.xa.get(t);n=n.unionWith(r.view.fa)}return n}}async function aO(e,t){let n=await st(e.localStore,t.query,!0),r=t.view.va(n);return e.isPrimaryClient&&aA(e,t.targetId,r.ba),r}async function aF(e,t){return sr(e.localStore,t).then(t=>aV(e,t))}async function aP(e,t,n,r){let i=await function(e,t){let n=e.mutationQueue;return e.persistence.runTransaction("Lookup mutation documents","readonly",r=>n.On(r,t).next(t=>t?e.localDocuments.getDocuments(r,t):ei.resolve(null)))}(e.localStore,t);null!==i?("pending"===n?await sW(e.remoteStore):"acknowledged"===n||"rejected"===n?(aC(e,t,r||null),aD(e,t),function(e,t){e.mutationQueue.Ln(t)}(e.localStore,t)):b(),await aV(e,i)):I("SyncEngine","Cannot apply mutation batch with id: "+t)}async function aU(e,t){if(aG(e),aj(e),!0===t&&!0!==e.$a){let t=e.sharedClientState.getAllActiveQueryTargets(),n=await aq(e,t.toArray());for(let t of(e.$a=!0,await s2(e.remoteStore,!0),n))sM(e.remoteStore,t)}else if(!1===t&&!1!==e.$a){let t=[],n=Promise.resolve();e.Oa.forEach((r,i)=>{e.sharedClientState.isLocalQueryTarget(i)?t.push(i):n=n.then(()=>(aN(e,i),se(e.localStore,i,!0))),sO(e.remoteStore,i)}),await n,await aq(e,t),e.Ba.forEach((t,n)=>{sO(e.remoteStore,n)}),e.ka.wr(),e.Ba=new Map,e.La=new eH(G.comparator),e.$a=!1,await s2(e.remoteStore,!1)}}async function aq(e,t,n){let r=[],i=[];for(let n of t){let t;let s=e.Oa.get(n);if(s&&0!==s.length)for(let n of(t=await i7(e.localStore,t8(s[0])),s)){let t=e.xa.get(n),r=await aO(e,t);r.snapshot&&i.push(r.snapshot)}else{let r=await sn(e.localStore,n);t=await i7(e.localStore,r),await aw(e,aB(r),n,!1,t.resumeToken)}r.push(t)}return e.Ma.R_(i),r}function aB(e){var t,n,r,i;return t=e.path,n=e.collectionGroup,r=e.orderBy,i=e.filters,new t0(t,n,r,i,e.limit,"F",e.startAt,e.endAt)}function aK(e){return e.localStore.persistence.$i()}async function az(e,t,n,r){if(e.$a)return void I("SyncEngine","Ignoring unexpected query state notification.");let i=e.Oa.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{let r=await sr(e.localStore,nn(i[0])),s=nX.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,e5.EMPTY_BYTE_STRING);await aV(e,r,s);break}case"rejected":await se(e.localStore,t,!0),aN(e,t,r);break;default:b()}}async function a$(e,t,n){let r=aG(e);if(r.$a){for(let e of t){if(r.Oa.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){I("SyncEngine","Adding an already active target "+e);continue}let t=await sn(r.localStore,e),n=await i7(r.localStore,t);await aw(r,aB(t),n.targetId,!1,n.resumeToken),sM(r.remoteStore,n)}for(let e of n)r.Oa.has(e)&&await se(r.localStore,e,!1).then(()=>{sO(r.remoteStore,e),aN(r,e)}).catch(er)}}function aG(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=aT.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=aM.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=ab.bind(null,e),e.Ma.R_=as.bind(null,e.eventManager),e.Ma.Wa=aa.bind(null,e.eventManager),e}function aj(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=ax.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=aS.bind(null,e),e}class aQ{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=sx(e.databaseInfo.databaseId),this.sharedClientState=this.za(e),this.persistence=this.ja(e),await this.persistence.start(),this.localStore=this.Ha(e),this.gcScheduler=this.Ja(e,this.localStore),this.indexBackfillerScheduler=this.Ya(e,this.localStore)}Ja(e,t){return null}Ya(e,t){return null}Ha(e){var t;return t=this.persistence,new i8(t,new i4,e.initialUser,this.serializer)}ja(e){return new iG(iQ.ei,this.serializer)}za(e){return new sm}async terminate(){var e,t;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(t=this.indexBackfillerScheduler)||void 0===t||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}aQ.provider={build:()=>new aQ};class aW extends aQ{constructor(e){super(),this.cacheSizeBytes=e}Ja(e,t){return this.persistence.referenceDelegate instanceof iW||b(),new iT(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}ja(e){let t=void 0!==this.cacheSizeBytes?ia.withCacheSize(this.cacheSizeBytes):ia.DEFAULT;return new iG(e=>iW.ei(e,t),this.serializer)}}class aH extends aQ{constructor(e,t,n){super(),this.Za=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Za.initialize(this,e),await aj(this.Za.syncEngine),await sW(this.Za.remoteStore),await this.persistence.Si(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Ha(e){var t;return t=this.persistence,new i8(t,new i4,e.initialUser,this.serializer)}Ja(e,t){return new iT(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Ya(e,t){let n=new ep(t,this.persistence);return new eg(e.asyncQueue,n)}ja(e){let t=i1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?ia.withCacheSize(this.cacheSizeBytes):ia.DEFAULT;return new iX(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,sE(),sb(),this.serializer,this.sharedClientState,!!this.forceOwnership)}za(e){return new sm}}class aJ{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>aE(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=aL.bind(null,this.syncEngine),await s2(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new at}createDatastore(e){let t=sx(e.databaseInfo.databaseId),n=new sT(e.databaseInfo);return new sk(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){var t;return t=this.localStore,new sR(t,this.datastore,e.asyncQueue,e=>aE(this.syncEngine,e,0),sp.p()?new sp:new sg)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){let o=new am(e,t,n,r,i,s);return a&&(o.$a=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){I("RemoteStore","RemoteStore shutting down."),e.k_.add(5),await sL(e),e.Q_.shutdown(),e.K_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(t=this.eventManager)||void 0===t||t.terminate()}}aJ.provider={build:()=>new aJ};class aY{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Xa(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Xa(this.observer.error,e):_("Uncaught Error in snapshot listener:",e.toString()))}eu(){this.muted=!0}Xa(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class aX{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=p.UNAUTHENTICATED,this.clientId=O.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async e=>{I("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(I("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new D;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(n){let t=s3(n,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function aZ(e,t){e.asyncQueue.verifyOperationInProgress(),I("FirestoreClient","Initializing OfflineComponentProvider");let n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await i3(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function a0(e,t){e.asyncQueue.verifyOperationInProgress();let n=await a1(e);I("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>s1(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>s1(t.remoteStore,n)),e._onlineComponents=t}async function a1(e){if(!e._offlineComponents){if(e._uninitializedComponentsProvider){I("FirestoreClient","Using user provided OfflineComponentProvider");try{await aZ(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===x.FAILED_PRECONDITION||t.code===x.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;T("Error using user provided cache. Falling back to memory cache: "+t),await aZ(e,new aQ)}}else I("FirestoreClient","Using default OfflineComponentProvider"),await aZ(e,new aW(void 0))}return e._offlineComponents}async function a2(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(I("FirestoreClient","Using user provided OnlineComponentProvider"),await a0(e,e._uninitializedComponentsProvider._online)):(I("FirestoreClient","Using default OnlineComponentProvider"),await a0(e,new aJ))),e._onlineComponents}async function a5(e){let t=await a2(e),n=t.eventManager;return n.onListen=ag.bind(null,t.syncEngine),n.onUnlisten=av.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=ap.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=aI.bind(null,t.syncEngine),n}function a4(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let a8=new Map;function a3(e,t,n){if(!n)throw new S(x.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function a6(e){if(!G.isDocumentKey(e))throw new S(x.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function a9(e){if(G.isDocumentKey(e))throw new S(x.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function a7(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var t;let n=(t=e).constructor?t.constructor.name:null;return n?`a custom ${n} object`:"an object"}}return"function"==typeof e?"a function":b()}function oe(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new S(x.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=a7(e);throw new S(x.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}class ot{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new S(x.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new S(x.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new S(x.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=a4(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new S(x.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new S(x.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new S(x.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var t,n;return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class on{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new ot({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new S(x.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new S(x.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new ot(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new N;switch(e.type){case"firstParty":return new V(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new S(x.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){let t=a8.get(e);t&&(I("ComponentProvider","Removing Datastore"),a8.delete(e),t.terminate())}(this),Promise.resolve()}}class or{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new or(this.firestore,e,this._query)}}class oi{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new os(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new oi(this.firestore,e,this._key)}}class os extends or{constructor(e,t,n){super(e,t,t1(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new oi(this.firestore,null,new G(e))}withConverter(e){return new os(this.firestore,e,this._path)}}function oa(e,t,...n){if(e=(0,h.Ku)(e),a3("collection","path",t),e instanceof on){let r=K.fromString(t,...n);return a9(r),new os(e,null,r)}{if(!(e instanceof oi||e instanceof os))throw new S(x.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(K.fromString(t,...n));return a9(r),new os(e.firestore,null,r)}}function oo(e,t,...n){if(e=(0,h.Ku)(e),1==arguments.length&&(t=O.newId()),a3("doc","path",t),e instanceof on){let r=K.fromString(t,...n);return a6(r),new oi(e,null,new G(r))}{if(!(e instanceof oi||e instanceof os))throw new S(x.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(K.fromString(t,...n));return a6(r),new oi(e.firestore,e instanceof os?e.converter:null,new G(r))}}class ol{constructor(e=Promise.resolve()){this.Iu=[],this.Eu=!1,this.du=[],this.Au=null,this.Ru=!1,this.Vu=!1,this.mu=[],this.r_=new sS(this,"async_queue_retry"),this.fu=()=>{let e=sb();e&&I("AsyncQueue","Visibility state changed to "+e.visibilityState),this.r_.Jo()},this.gu=e;let t=sb();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.fu)}get isShuttingDown(){return this.Eu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.pu(),this.yu(e)}enterRestrictedMode(e){if(!this.Eu){this.Eu=!0,this.Vu=e||!1;let t=sb();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.fu)}}enqueue(e){if(this.pu(),this.Eu)return new Promise(()=>{});let t=new D;return this.yu(()=>this.Eu&&this.Vu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Iu.push(e),this.wu()))}async wu(){if(0!==this.Iu.length){try{await this.Iu[0](),this.Iu.shift(),this.r_.reset()}catch(e){if(!eh(e))throw e;I("AsyncQueue","Operation failed with retryable error: "+e)}this.Iu.length>0&&this.r_.jo(()=>this.wu())}}yu(e){let t=this.gu.then(()=>(this.Ru=!0,e().catch(e=>{let t;throw this.Au=e,this.Ru=!1,_("INTERNAL UNHANDLED ERROR: ",(t=e.message||"",e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t)),e}).then(e=>(this.Ru=!1,e))));return this.gu=t,t}enqueueAfterDelay(e,t,n){this.pu(),this.mu.indexOf(e)>-1&&(t=0);let r=s8.createAndSchedule(this,e,t,n,e=>this.Su(e));return this.du.push(r),r}pu(){this.Au&&b()}verifyOperationInProgress(){}async bu(){let e;do e=this.gu,await e;while(e!==this.gu)}Du(e){for(let t of this.du)if(t.timerId===e)return!0;return!1}vu(e){return this.bu().then(()=>{for(let t of(this.du.sort((e,t)=>e.targetTimeMs-t.targetTimeMs),this.du))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.bu()})}Cu(e){this.mu.push(e)}Su(e){let t=this.du.indexOf(e);this.du.splice(t,1)}}function ou(e){return function(e,t){if("object"!=typeof e||null===e)return!1;for(let n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])}class oh extends on{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ol,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new ol(e),this._firestoreClient=void 0,await e}}}function oc(e,t){let n="object"==typeof e?e:(0,o.Sx)(),r=(0,o.j6)(n,"firestore").getImmediate({identifier:"string"==typeof e?e:t||"(default)"});if(!r._initialized){let e=(0,h.yU)("firestore");e&&function(e,t,n,r={}){var i;let s=(e=oe(e,on))._getSettings(),a=`${t}:${n}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&T("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=p.MOCK_USER;else{t=(0,h.Fy)(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);let s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new S(x.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new p(s)}e._authCredentials=new k(new C(t,n))}}(r,...e)}return r}function od(e){if(e._terminated)throw new S(x.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||function(e){var t,n,r,i;let s=e._freezeSettings(),a=(i=e._databaseId,new tt(i,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,a4(s.experimentalLongPollingOptions),s.useFetchStreams));e._componentsProvider||(null===(n=s.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=s.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider}),e._firestoreClient=new aX(e._authCredentials,e._appCheckCredentials,e._queue,a,e._componentsProvider&&function(e){let t=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(t),_online:t}}(e._componentsProvider))}(e),e._firestoreClient}class of{constructor(e){this._byteString=e}static fromBase64String(e){try{return new of(e5.fromBase64String(e))}catch(e){throw new S(x.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new of(e5.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class om{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new S(x.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new $(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class og{constructor(e){this._methodName=e}}class op{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new S(x.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new S(x.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return F(this._lat,e._lat)||F(this._long,e._long)}}class oy{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}}let ow=/^__.*__$/;class ov{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new nO(e,this.data,this.fieldMask,t,this.fieldTransforms):new nM(e,this.data,t,this.fieldTransforms)}}class oI{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new nO(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function o_(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw b()}}class oT{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Fu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Mu(){return this.settings.Mu}xu(e){return new oT(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Ou(e){var t;let n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.xu({path:n,Nu:!1});return r.Lu(e),r}Bu(e){var t;let n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.xu({path:n,Nu:!1});return r.Fu(),r}ku(e){return this.xu({path:void 0,Nu:!0})}qu(e){return oU(e,this.settings.methodName,this.settings.Qu||!1,this.path,this.settings.Ku)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}Fu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Lu(this.path.get(e))}Lu(e){if(0===e.length)throw this.qu("Document fields must not be empty");if(o_(this.Mu)&&ow.test(e))throw this.qu('Document fields cannot begin and end with "__"')}}class oE{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||sx(e)}$u(e,t,n,r=!1){return new oT({Mu:e,methodName:t,Ku:n,path:$.emptyPath(),Nu:!1,Qu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ob(e){let t=e._freezeSettings(),n=sx(e._databaseId);return new oE(e._databaseId,!!t.ignoreUndefinedProperties,n)}class ox extends og{_toFieldTransform(e){if(2!==e.Mu)throw 1===e.Mu?e.qu(`${this._methodName}() can only appear at the top level of your update data`):e.qu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof ox}}function oS(e,t,n){return new oT({Mu:3,Ku:t.settings.Ku,methodName:e._methodName,Nu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class oD extends null{_toFieldTransform(e){return new nD(e.path,new nv)}isEqual(e){return e instanceof oD}}class oC extends og{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){let t=oS(this,e,!0),n=new nI(this.Uu.map(e=>oR(e,t)));return new nD(e.path,n)}isEqual(e){return e instanceof oC&&(0,h.bD)(this.Uu,e.Uu)}}class oN extends og{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){let t=oS(this,e,!0),n=new nT(this.Uu.map(e=>oR(e,t)));return new nD(e.path,n)}isEqual(e){return e instanceof oN&&(0,h.bD)(this.Uu,e.Uu)}}class ok extends og{constructor(e,t){super(e),this.Wu=t}_toFieldTransform(e){let t=new nb(e.serializer,np(e.serializer,this.Wu));return new nD(e.path,t)}isEqual(e){return e instanceof ok&&this.Wu===e.Wu}}function oA(e,t,n,r=!1){return oR(n,e.$u(r?4:3,t))}function oR(e,t){if(oL(e=(0,h.Ku)(e)))return oM("Unsupported field value:",t,e),oV(e,t);if(e instanceof og)return function(e,t){if(!o_(t.Mu))throw t.qu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.qu(`${e._methodName}() is not currently supported inside arrays`);let n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Nu&&4!==t.Mu)throw t.qu("Nested arrays are not supported");return function(e,t){let n=[],r=0;for(let i of e){let e=oR(i,t.ku(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=(0,h.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return np(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let n=U.fromDate(e);return{timestampValue:rn(t.serializer,n)}}if(e instanceof U){let n=new U(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:rn(t.serializer,n)}}if(e instanceof op)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof of)return{bytesValue:rr(t.serializer,e._byteString)};if(e instanceof oi){let n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.qu(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:rs(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof oy)return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw t.qu("VectorValues must only contain numeric values.");return nm(t.serializer,e)})}}}}};throw t.qu(`Unsupported field value: ${a7(e)}`)}(e,t)}function oV(e,t){let n={};return eW(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):eQ(e,(e,r)=>{let i=oR(r,t.Ou(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function oL(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof U||e instanceof op||e instanceof of||e instanceof oi||e instanceof og||e instanceof oy)}function oM(e,t,n){if(!oL(n)||!("object"==typeof n&&null!==n&&(Object.getPrototypeOf(n)===Object.prototype||null===Object.getPrototypeOf(n)))){let r=a7(n);throw"an object"===r?t.qu(e+" a custom object"):t.qu(e+" "+r)}}function oO(e,t,n){if((t=(0,h.Ku)(t))instanceof om)return t._internalPath;if("string"==typeof t)return oP(e,t);throw oU("Field path arguments must be of type string or ",e,!1,void 0,n)}let oF=RegExp("[~\\*/\\[\\]]");function oP(e,t,n){if(t.search(oF)>=0)throw oU(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new om(...t.split("."))._internalPath}catch(r){throw oU(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function oU(e,t,n,r,i){let s=r&&!r.isEmpty(),a=void 0!==i,o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${r}`),a&&(l+=` in document ${i}`),l+=")"),new S(x.INVALID_ARGUMENT,o+e+l)}function oq(e,t){return e.some(e=>e.isEqual(t))}class oB{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new oi(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new oK(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let t=this._document.data.field(oz("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class oK extends oB{data(){return super.data()}}function oz(e,t){return"string"==typeof t?oP(e,t):t instanceof om?t._internalPath:t._delegate._internalPath}class o${}class oG extends o${}function oj(e,t,...n){let r=[];for(let i of(t instanceof o$&&r.push(t),function(e){let t=e.filter(e=>e instanceof oH).length,n=e.filter(e=>e instanceof oQ).length;if(t>1||t>0&&n>0)throw new S(x.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r=r.concat(n)),r))e=i._apply(e);return e}class oQ extends oG{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new oQ(e,t,n)}_apply(e){let t=this._parse(e);return o5(e._query,t),new or(e.firestore,e.converter,t3(e._query,t))}_parse(e){let t=ob(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new S(x.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){o2(a,s);let t=[];for(let n of a)t.push(o1(r,e,n));o={arrayValue:{values:t}}}else o=o1(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||o2(a,s),o=oA(n,t,a,"in"===s||"not-in"===s);return tA.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function oW(e,t,n){let r=oz("where",e);return oQ._create(r,t,n)}class oH extends o${constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new oH(e,t)}_parse(e){let t=this._queryConstraints.map(t=>t._parse(e)).filter(e=>e.getFilters().length>0);return 1===t.length?t[0]:tR.create(t,this._getOperator())}_apply(e){let t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(let e of t.getFlattenedFilters())o5(n,e),n=t3(n,e)}(e._query,t),new or(e.firestore,e.converter,t3(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class oJ extends oG{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new oJ(e,t)}_apply(e){let t=function(e,t,n){if(null!==e.startAt)throw new S(x.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new S(x.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new tN(t,n)}(e._query,this._field,this._direction);return new or(e.firestore,e.converter,function(e,t){let n=e.explicitOrderBy.concat([t]);return new t0(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class oY extends oG{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new oY(e,t,n)}_apply(e){return new or(e.firestore,e.converter,t6(e._query,this._limit,this._limitType))}}class oX extends oG{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new oX(e,t,n)}_apply(e){var t;let n=o0(e,this.type,this._docOrFields,this._inclusive);return new or(e.firestore,e.converter,new t0((t=e._query).path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,n,t.endAt))}}class oZ extends oG{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new oZ(e,t,n)}_apply(e){var t;let n=o0(e,this.type,this._docOrFields,this._inclusive);return new or(e.firestore,e.converter,new t0((t=e._query).path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,n))}}function o0(e,t,n,r){if(n[0]=(0,h.Ku)(n[0]),n[0]instanceof oB)return function(e,t,n,r,i){if(!r)throw new S(x.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);let s=[];for(let n of t4(e))if(n.field.isKeyField())s.push(td(t,r.key));else{let e=r.data.field(n.field);if(e9(e))throw new S(x.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){let e=n.field.canonicalString();throw new S(x.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new tS(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{let i=ob(e.firestore);return function(e,t,n,r,i,s){let a=e.explicitOrderBy;if(i.length>a.length)throw new S(x.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let o=[];for(let s=0;s<i.length;s++){let l=i[s];if(a[s].field.isKeyField()){if("string"!=typeof l)throw new S(x.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!t5(e)&&-1!==l.indexOf("/"))throw new S(x.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);let n=e.path.child(K.fromString(l));if(!G.isDocumentKey(n))throw new S(x.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);let i=new G(n);o.push(td(t,i))}else{let e=oA(n,r,l);o.push(e)}}return new tS(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function o1(e,t,n){if("string"==typeof(n=(0,h.Ku)(n))){if(""===n)throw new S(x.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!t5(t)&&-1!==n.indexOf("/"))throw new S(x.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let r=t.path.child(K.fromString(n));if(!G.isDocumentKey(r))throw new S(x.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return td(e,new G(r))}if(n instanceof oi)return td(e,n._key);throw new S(x.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${a7(n)}.`)}function o2(e,t){if(!Array.isArray(e)||0===e.length)throw new S(x.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function o5(e,t){let n=function(e,t){for(let n of e)for(let e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new S(x.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new S(x.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class o4{convertValue(e,t="none"){switch(ts(e)){case 0:return null;case 1:return e.booleanValue;case 2:return e3(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(e6(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw b()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return eQ(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertVectorValue(e){var t,n,r;return new oy(null===(r=null===(n=null===(t=e.fields)||void 0===t?void 0:t.value.arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.map(e=>e3(e.doubleValue)))}convertGeoPoint(e){return new op(e3(e.latitude),e3(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=e7(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(te(e));default:return null}}convertTimestamp(e){let t=e8(e);return new U(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=K.fromString(e);rE(n)||b();let r=new tn(n.get(1),n.get(3)),i=new G(n.popFirst(5));return r.isEqual(t)||_(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}class o8{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class o3 extends oB{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new o6(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let n=this._document.data.field(oz("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class o6 extends o3{data(e={}){return super.data(e)}}class o9{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new o8(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){let e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach(n=>{e.call(t,new o6(this._firestore,this._userDataWriter,n.key,n,new o8(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new S(x.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(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map(n=>{let r=new o6(e._firestore,e._userDataWriter,n.doc.key,n.doc,new o8(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}})}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>t||3!==e.type).map(t=>{let r=new o6(e._firestore,e._userDataWriter,t.doc.key,t.doc,new o8(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(s=(n=n.add(t.doc)).indexOf(t.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return b()}}(t.type),doc:r,oldIndex:i,newIndex:s}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function o7(e){e=oe(e,oi);let t=oe(e.firestore,oh);return(function(e,t,n={}){let r=new D;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new aY({next:o=>{s.eu(),t.enqueueAndForget(()=>ai(e,a));let l=o.docs.has(n);!l&&o.fromCache?i.reject(new S(x.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&o.fromCache&&r&&"server"===r.source?i.reject(new S(x.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.)')):i.resolve(o)},error:e=>i.reject(e)}),a=new al(t1(n.path),s,{includeMetadataChanges:!0,ua:!0});return ar(e,a)})(await a5(e),e.asyncQueue,t,n,r)),r.promise})(od(t),e._key).then(n=>lr(t,e,n))}class le extends o4{constructor(e){super(),this.firestore=e}convertBytes(e){return new of(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new oi(this.firestore,null,t)}}function lt(e,t,n){var r,i,s,a,o;e=oe(e,oi);let l=oe(e.firestore,oh),u=(r=e.converter,i=t,s=n,r?s&&(s.merge||s.mergeFields)?r.toFirestore(i,s):r.toFirestore(i):i);return a=l,o=[(function(e,t,n,r,i,s={}){let a,o;let l=e.$u(s.merge||s.mergeFields?2:0,t,n,i);oM("Data must be an object, but it was:",l,r);let u=oV(r,l);if(s.merge)a=new e1(l.fieldMask),o=l.fieldTransforms;else if(s.mergeFields){let e=[];for(let r of s.mergeFields){let i=oO(t,r,n);if(!l.contains(i))throw new S(x.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);oq(e,i)||e.push(i)}a=new e1(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new ov(new tb(u),a,o)})(ob(l),"setDoc",e._key,u,null!==e.converter,n).toMutation(e._key,nN.none())],function(e,t){let n=new D;return e.asyncQueue.enqueueAndForget(async()=>a_(await a2(e).then(e=>e.syncEngine),t,n)),n.promise}(od(a),o)}function ln(e,...t){var n,r,i;let s,a,o;e=(0,h.Ku)(e);let l={includeMetadataChanges:!1,source:"default"},u=0;"object"!=typeof t[0]||ou(t[u])||(l=t[u],u++);let c={includeMetadataChanges:l.includeMetadataChanges,source:l.source};if(ou(t[u])){let e=t[u];t[u]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[u+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[u+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}if(e instanceof oi)a=oe(e.firestore,oh),o=t1(e._key.path),s={next:n=>{t[u]&&t[u](lr(a,e,n))},error:t[u+1],complete:t[u+2]};else{let n=oe(e,or);a=oe(n.firestore,oh),o=n._query;let r=new le(a);s={next:e=>{t[u]&&t[u](new o9(a,r,n,e))},error:t[u+1],complete:t[u+2]},function(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new S(x.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query)}return function(e,t,n,r){let i=new aY(r),s=new al(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>ar(await a5(e),s)),()=>{i.eu(),e.asyncQueue.enqueueAndForget(async()=>ai(await a5(e),s))}}(od(a),o,c,s)}function lr(e,t,n){let r=n.docs.get(t._key),i=new le(e);return new o3(e,i,t._key,r,new o8(n.hasPendingWrites,n.fromCache),t.converter)}new WeakMap,function(e=!0){y=o.MF,(0,o.om)(new l.uA("firestore",(t,{instanceIdentifier:n,options:r})=>{let i=t.getProvider("app").getImmediate(),s=new oh(new A(t.getProvider("auth-internal")),new M(t.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new S(x.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new tn(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:e},r),s._setSettings(r),s},"PUBLIC").setMultipleInstances(!0)),(0,o.KO)(g,"4.7.5",void 0),(0,o.KO)(g,"4.7.5","esm2017")}()}}]);