1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2992],{6596:(e,t,n)=>{n.d(t,{AB:()=>i$,GG:()=>iJ,H9:()=>is,P:()=>iF,_M:()=>iM,aU:()=>iu,mZ:()=>iZ,rJ:()=>ir,x7:()=>iX});var r,s,i,a,o=n(9820),l=n(2396),u=n(5969),h=n(7176),c=n(916),d=n(4052);n(7358);var f=n(1029).hp;let m="@firebase/firestore",g="4.8.0";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.10.0",v=new u.Vy("@firebase/firestore");function w(){return v.logLevel}function _(e,...t){if(v.logLevel<=u.$b.DEBUG){let n=t.map(I);v.debug(`Firestore (${y}): ${e}`,...n)}}function E(e,...t){if(v.logLevel<=u.$b.ERROR){let n=t.map(I);v.error(`Firestore (${y}): ${e}`,...n)}}function T(e,...t){if(v.logLevel<=u.$b.WARN){let n=t.map(I);v.warn(`Firestore (${y}): ${e}`,...n)}}function I(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function S(e,t,n){let r="Unexpected state";"string"==typeof t?r=t:n=t,C(e,r,n)}function C(e,t,n){let r=`FIRESTORE (${y}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==n)try{r+=" CONTEXT: "+JSON.stringify(n)}catch(e){r+=" CONTEXT: "+n}throw E(r),Error(r)}function b(e,t,n,r){let s="Unexpected state";"string"==typeof n?s=n:r=n,e||C(t,s,r)}let A={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 N 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 k{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class x{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(p.UNAUTHENTICATED))}shutdown(){}}class R{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class V{constructor(e){this.t=e,this.currentUser=p.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){b(void 0===this.o,42304);let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),s=new D;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new D,e.enqueueRetryable(()=>r(this.currentUser))};let i=()=>{let t=s;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},a=e=>{_("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),i())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(_("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new D)}},0),i()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(_("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(b("string"==typeof t.accessToken,31837,{l:t}),new k(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 b(null===e||"string"==typeof e,2055,{h:e}),new p(e)}}class O{constructor(e,t,n){this.P=e,this.T=t,this.I=n,this.type="FirstParty",this.user=p.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set("X-Goog-AuthUser",this.P);let e=this.R();return e&&this.A.set("Authorization",e),this.T&&this.A.set("X-Goog-Iam-Authorization-Token",this.T),this.A}}class L{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new O(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(p.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class F{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 P{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,o.xZ)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){b(void 0===this.o,3512);let n=e=>{null!=e.error&&_("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let n=e.token!==this.m;return this.m=e.token,_("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>{_("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?r(e):_("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new F(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(b("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new F(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function M(){return new TextEncoder}class U{static newId(){let e=62*Math.floor(256/62),t="";for(;t.length<20;){let n=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;
1e++)n[e]=Math.floor(256*Math.random());return n}(40);for(let r=0;r<n.length;++r)t.length<20&&n[r]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[r]%62))}return t}}function q(e,t){return e<t?-1:+(e>t)}function $(e,t){let n=0;for(;n<e.length&&n<t.length;){let r=e.codePointAt(n),s=t.codePointAt(n);if(r!==s){if(r<128&&s<128)return q(r,s);{let i=M(),a=function(e,t){for(let n=0;n<e.length&&n<t.length;++n)if(e[n]!==t[n])return q(e[n],t[n]);return q(e.length,t.length)}(i.encode(z(e,n)),i.encode(z(t,n)));return 0!==a?a:q(r,s)}}n+=r>65535?2:1}return q(e.length,t.length)}function z(e,t){return e.codePointAt(t)>65535?e.substring(t,t+2):e.substring(t,t+1)}function B(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}let j="__name__";class G{constructor(e,t,n){void 0===t?t=0:t>e.length&&S(637,{offset:t,range:e.length}),void 0===n?n=e.length-t:n>e.length-t&&S(1746,{length:n,range:e.length-t}),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===G.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof G?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=G.compareSegments(e.get(r),t.get(r));if(0!==n)return n}return q(e.length,t.length)}static compareSegments(e,t){let n=G.isNumericId(e),r=G.isNumericId(t);return n&&!r?-1:!n&&r?1:n&&r?G.extractNumericId(e).compare(G.extractNumericId(t)):$(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return c.jz.fromString(e.substring(4,e.length-2))}}class K extends G{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 N(A.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 Q=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class W extends G{construct(e,t,n){return new W(e,t,n)}static isValidIdentifier(e){return Q.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),W.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===j}static keyField(){return new W([j])}static fromServerFormat(e){let t=[],n="",r=0,s=()=>{if(0===n.length)throw new N(A.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},i=!1;for(;r<e.length;){let t=e[r];if("\\"===t){if(r+1===e.length)throw new N(A.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new N(A.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?i=!i:"."!==t||i?n+=t:s(),r++}if(s(),i)throw new N(A.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new W(t)}static emptyPath(){return new W([])}}class H{constructor(e){this.path=e}static fromPath(e){return new H(K.fromString(e))}static fromName(e){return new H(K.fromString(e).popFirst(5))}static empty(){return new H(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 H(new K(e.slice()))}}
1function X(e,t,n){if(!n)throw new N(A.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Y(e){if(!H.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function J(e){if(H.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Z(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function ee(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":S(12329,{type:typeof e})}function et(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new N(A.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=ee(e);throw new N(A.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function en(e,t){let n={typeString:e};return t&&(n.value=t),n}function er(e,t){let n;if(!Z(e))throw new N(A.INVALID_ARGUMENT,"JSON must be an object");for(let r in t)if(t[r]){let s=t[r].typeString,i="value"in t[r]?{value:t[r].value}:void 0;if(!(r in e)){n=`JSON missing required field: '${r}'`;break}let a=e[r];if(s&&typeof a!==s){n=`JSON field '${r}' must be a ${s}.`;break}if(void 0!==i&&a!==i.value){n=`Expected '${r}' field to equal '${i.value}'`;break}}if(n)throw new N(A.INVALID_ARGUMENT,n);return!0}class es{static now(){return es.fromMillis(Date.now())}static fromDate(e){return es.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*1e6);return new es(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new N(A.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?q(this.nanoseconds,e.nanoseconds):q(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{type:es._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(er(e,es._jsonSchema))return new es(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}es._jsonSchemaVersion="firestore/timestamp/1.0",es._jsonSchema={type:en("string",es._jsonSchemaVersion),seconds:en("number"),nanoseconds:en("number")};class ei{static fromTimestamp(e){return new ei(e)}static min(){return new ei(new es(0,0))}static max(){return new ei(new es(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 ea{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}ea.UNKNOWN_ID=-1;class eo{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new eo(ei.min(),H.empty(),-1)}static max(){return new eo(ei.max(),H.empty(),-1)}}class el{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}
1raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function eu(e){if(e.code!==A.FAILED_PRECONDITION||"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."!==e.message)throw e;_("LocalStore","Unexpectedly lost primary lease")}class eh{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&&S(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new eh((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 eh?t:eh.resolve(t)}catch(e){return eh.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):eh.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):eh.reject(t)}static resolve(e){return new eh((t,n)=>{t(e)})}static reject(e){return new eh((t,n)=>{n(e)})}static waitFor(e){return new eh((t,n)=>{let r=0,s=0,i=!1;e.forEach(e=>{++r,e.next(()=>{++s,i&&s===r&&t()},e=>n(e))}),i=!0,s===r&&t()})}static or(e){let t=eh.resolve(!1);for(let n of e)t=t.next(e=>e?eh.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 eh((n,r)=>{let s=e.length,i=Array(s),a=0;for(let o=0;o<s;o++){let l=o;t(e[l]).next(e=>{i[l]=e,++a===s&&n(i)},e=>r(e))}})}static doWhile(e,t){return new eh((n,r)=>{let s=()=>{!0===e()?t().next(()=>{s()},r):n()};s()})}}function ec(e){return"IndexedDbTransactionError"===e.name}class ed{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this._e(e),this.ae=e=>t.writeSequenceNumber(e))}_e(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ae&&this.ae(e),e}}ed.ue=-1;function ef(e){return 0===e&&1/e==-1/0}function em(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function eg(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ep(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ey{constructor(e,t){this.comparator=e,this.root=t||ew.EMPTY}insert(e,t){return new ey(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ew.BLACK,null,null))}remove(e){return new ey(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ew.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 ev(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ev(this.root,e,this.comparator,!1)}getReverseIterator(){return new ev(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ev(this.root,e,this.comparator,!0)}}class ev{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){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}}}
1class ew{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:ew.RED,this.left=null!=r?r:ew.EMPTY,this.right=null!=s?s:ew.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new ew(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s: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,s=n(e,r.key);return(r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?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 ew.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 ew.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,ew.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,ew.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())throw S(43730,{key:this.key,value:this.value});if(this.right.isRed())throw S(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw S(27949);return e+ +!this.isRed()}}ew.EMPTY=null,ew.RED=!0,ew.BLACK=!1,ew.EMPTY=new class{constructor(){this.size=0}get key(){throw S(57766)}get value(){throw S(16141)}get color(){throw S(16727)}get left(){throw S(29726)}get right(){throw S(36894)}copy(e,t,n,r,s){return this}insert(e,t,n){return new ew(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 e_{constructor(e){this.comparator=e,this.data=new ey(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 eE(this.data.getIterator())}getIteratorFrom(e){return new eE(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;
1return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof e_)||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 e_(this.comparator);return t.data=e,t}}class eE{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class eT{constructor(e){this.fields=e,e.sort(W.comparator)}static empty(){return new eT([])}unionWith(e){let t=new e_(W.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new eT(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return B(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class eI extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class eS{constructor(e){this.binaryString=e}static fromBase64String(e){return new eS(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new eI("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new eS(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(){var e=this.binaryString;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return q(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}eS.EMPTY_BYTE_STRING=new eS("");let eC=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function eb(e){if(b(!!e,39018),"string"==typeof e){let t=0,n=eC.exec(e);if(b(!!n,46558,{timestamp:e}),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:eA(e.seconds),nanos:eA(e.nanos)}}function eA(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function eN(e){return"string"==typeof e?eS.fromBase64String(e):eS.fromUint8Array(e)}let eD="server_timestamp",ek="__type__",ex="__previous_value__",eR="__local_write_time__";function eV(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[ek])?void 0:n.stringValue)===eD}function eO(e){let t=e.mapValue.fields[ex];return eV(t)?eO(t):t}function eL(e){let t=eb(e.mapValue.fields[eR].timestampValue);return new es(t.seconds,t.nanos)}class eF{constructor(e,t,n,r,s,i,a,o,l,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u}}let eP="(default)";class eM{constructor(e,t){this.projectId=e,this.database=t||eP}static empty(){return new eM("","")}get isDefaultDatabase(){return this.database===eP}isEqual(e){return e instanceof eM&&e.projectId===this.projectId&&e.database===this.database}}let eU="__type__",eq="__max__",e$={mapValue:{fields:{__type__:{stringValue:eq}}}},ez="__vector__",eB="value";function ej(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?eV(e)?4:e6(e)?0x1fffffffffffff:e3(e)?10:11:S(28295,{value:e})}function eG(e,t){if(e===t)return!0;let n=ej(e);if(n!==ej(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return eL(e).isEqual(eL(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let r=eb(e.timestampValue),s=eb(t.timestampValue);return r.seconds===s.seconds&&r.nanos===s.nanos;case 5:return e.stringValue===t.stringValue;case 6:return eN(e.bytesValue).isEqual(eN(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return eA(e.geoPointValue.latitude)===eA(t.geoPointValue.latitude)&&eA(e.geoPointValue.longitude)===eA(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return eA(e.integerValue)===eA(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=eA(e.doubleValue),r=eA(t.doubleValue);return n===r?ef(n)===ef(r):isNaN(n)&&isNaN(r)}return!1;case 9:return B(e.arrayValue.values||[],t.arrayValue.values||[],eG);case 10:case 11:let i=e.mapValue.fields||{},a=t.mapValue.fields||{};if(em(i)!==em(a))return!1;for(let e in i)if(i.hasOwnProperty(e)&&(void 0===a[e]||!eG(i[e],a[e])))return!1;return!0;default:return S(52216,{left:e})}}function eK(e,t){return void 0!==(e.values||[]).find(e=>eG(e,t))}function eQ(e,t){if(e===t)return 0;let n=ej(e),r=ej(t);if(n!==r)return q(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return q(e.booleanValue,t.booleanValue);case 2:let s=eA(e.integerValue||e.doubleValue),i=eA(t.integerValue||t.doubleValue);return s<i?-1:s>i?1:s===i?0:isNaN(s)?isNaN(i)?0:-1:1;case 3:return eW(e.timestampValue,t.timestampValue);case 4:return eW(eL(e),eL(t));case 5:return $(e.stringValue,t.stringValue);case 6:return function(e,t){let n=eN(e),r=eN(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=q(n[e],r[e]);if(0!==t)return t}return q(n.length,r.length)}(e.referenceValue,t.referenceValue);
1case 8:return function(e,t){let n=q(eA(e.latitude),eA(t.latitude));return 0!==n?n:q(eA(e.longitude),eA(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return eH(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,s,i;let a=e.fields||{},o=t.fields||{},l=null==(n=a[eB])?void 0:n.arrayValue,u=null==(r=o[eB])?void 0:r.arrayValue,h=q((null==(s=null==l?void 0:l.values)?void 0:s.length)||0,(null==(i=null==u?void 0:u.values)?void 0:i.length)||0);return 0!==h?h:eH(l,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===e$.mapValue&&t===e$.mapValue)return 0;if(e===e$.mapValue)return 1;if(t===e$.mapValue)return -1;let n=e.fields||{},r=Object.keys(n),s=t.fields||{},i=Object.keys(s);r.sort(),i.sort();for(let e=0;e<r.length&&e<i.length;++e){let t=$(r[e],i[e]);if(0!==t)return t;let a=eQ(n[r[e]],s[i[e]]);if(0!==a)return a}return q(r.length,i.length)}(e.mapValue,t.mapValue);default:throw S(23264,{le:n})}}function eW(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return q(e,t);let n=eb(e),r=eb(t),s=q(n.seconds,r.seconds);return 0!==s?s:q(n.nanos,r.nanos)}function eH(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=eQ(n[e],r[e]);if(t)return t}return q(n.length,r.length)}function eX(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=eb(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?eN(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,H.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+=eX(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),n="{",r=!0;for(let s of t)r?r=!1:n+=",",n+=`${s}:${eX(e.fields[s])}`;return n+"}"}(e.mapValue):S(61005,{value:e})}function eY(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function eJ(e){return!!e&&"integerValue"in e}function eZ(e){return!!e&&"arrayValue"in e}function e0(e){return!!e&&"nullValue"in e}function e1(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function e2(e){return!!e&&"mapValue"in e}function e3(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[eU])?void 0:n.stringValue)===ez}function e4(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 eg(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=e4(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=e4(e.arrayValue.values[n]);return t}return Object.assign({},e)}function e6(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===eq}class e5{constructor(e){this.value=e}static empty(){return new e5({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!e2(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()]=e4(t)}setAll(e){let t=W.emptyPath(),n={},r=[];e.forEach((e,s)=>{if(!t.isImmediateParentOf(s)){let e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=s.popLast()}e?n[s.lastSegment()]=e4(e):r.push(s.lastSegment())});let s=this.getFieldsMap(t);this.applyChanges(s,n,r)}delete(e){let t=this.field(e.popLast());e2(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return eG(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)];e2(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}
1applyChanges(e,t,n){for(let r of(eg(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new e5(e4(this.value))}}class e8{constructor(e,t,n,r,s,i,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=s,this.data=i,this.documentState=a}static newInvalidDocument(e){return new e8(e,0,ei.min(),ei.min(),ei.min(),e5.empty(),0)}static newFoundDocument(e,t,n,r){return new e8(e,1,t,ei.min(),n,r,0)}static newNoDocument(e,t){return new e8(e,2,t,ei.min(),ei.min(),e5.empty(),0)}static newUnknownDocument(e,t){return new e8(e,3,t,ei.min(),ei.min(),e5.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(ei.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=e5.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=e5.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ei.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 e8&&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 e8(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 e9{constructor(e,t){this.position=e,this.inclusive=t}}function e7(e,t,n){let r=0;for(let s=0;s<e.position.length;s++){let i=t[s],a=e.position[s];if(r=i.field.isKeyField()?H.comparator(H.fromName(a.referenceValue),n.key):eQ(a,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return r}function te(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(!eG(e.position[n],t.position[n]))return!1;return!0}class tt{constructor(e,t="asc"){this.field=e,this.dir=t}}class tn{}class tr extends tn{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 to(e,t,n):"array-contains"===t?new tc(e,n
1):"in"===t?new td(e,n):"not-in"===t?new tf(e,n):"array-contains-any"===t?new tm(e,n):new tr(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new tl(e,n):new tu(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(eQ(t,this.value)):null!==t&&ej(this.value)===ej(t)&&this.matchesComparison(eQ(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 S(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class ts extends tn{constructor(e,t){super(),this.filters=e,this.op=t,this.he=null}static create(e,t){return new ts(e,t)}matches(e){return ti(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.he||(this.he=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.he}getFilters(){return Object.assign([],this.filters)}}function ti(e){return"and"===e.op}function ta(e){for(let t of e.filters)if(t instanceof ts)return!1;return!0}class to extends tr{constructor(e,t,n){super(e,t,n),this.key=H.fromName(n.referenceValue)}matches(e){let t=H.comparator(e.key,this.key);return this.matchesComparison(t)}}class tl extends tr{constructor(e,t){super(e,"in",t),this.keys=th("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class tu extends tr{constructor(e,t){super(e,"not-in",t),this.keys=th("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function th(e,t){var n;return((null==(n=t.arrayValue)?void 0:n.values)||[]).map(e=>H.fromName(e.referenceValue))}class tc extends tr{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return eZ(t)&&eK(t.arrayValue,this.value)}}class td extends tr{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&eK(this.value.arrayValue,t)}}class tf extends tr{constructor(e,t){super(e,"not-in",t)}matches(e){if(eK(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!eK(this.value.arrayValue,t)}}class tm extends tr{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!eZ(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>eK(this.value.arrayValue,e))}}class tg{constructor(e,t=null,n=[],r=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=a,this.Pe=null}}function tp(e,t=null,n=[],r=[],s=null,i=null,a=null){return new tg(e,t,n,r,s,i,a)}function ty(e){if(null===e.Pe){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 tr)return t.field.canonicalString()+t.op.toString()+eX(t.value);if(ta(t)&&ti(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=>eX(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>eX(e)).join(",")),e.Pe=t}return e.Pe}function tv(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let s=0;s<e.orderBy.length;s++){var n,r;if(n=e.orderBy[s],r=t.orderBy[s],!(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 tr?n instanceof tr&&t.op===n.op&&t.field.isEqual(n.field)&&eG(t.value,n.value):t instanceof ts?n instanceof ts&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,s)=>t&&e(r,n.filters[s]),!0):void S(19439)}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!te(e.startAt,t.startAt)&&te(e.endAt,t.endAt)}function tw(e){return H.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class t_{constructor(e,t=null,n=[],r=[],s=null,i="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=a,this.endAt=o,this.Te=null,this.Ie=null,this.de=null,this.startAt,this.endAt}}function tE(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 tT(e){return null!==e.collectionGroup}function tI(e){if(null===e.Te){let t;e.Te=[];let n=new Set;for(let t of e.explicitOrderBy)e.Te.push(t),n.add(t.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";
1(t=new e_(W.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.Te.push(new tt(t,r))}),n.has(W.keyField().canonicalString())||e.Te.push(new tt(W.keyField(),r))}return e.Te}function tS(e){return e.Ie||(e.Ie=function(e,t){if("F"===e.limitType)return tp(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 tt(e.field,t)});let n=e.endAt?new e9(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new e9(e.startAt.position,e.startAt.inclusive):null;return tp(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(e,tI(e))),e.Ie}function tC(e,t){let n=e.filters.concat([t]);return new t_(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function tb(e,t,n){return new t_(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function tA(e,t){return tv(tS(e),tS(t))&&e.limitType===t.limitType}function tN(e){return`${ty(tS(e))}|lt:${e.limitType}`}function tD(e){var t;let n;return`Query(target=${n=(t=tS(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 tr?`${t.field.canonicalString()} ${t.op} ${eX(t.value)}`:t instanceof ts?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=>eX(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>eX(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function tk(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):H.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(let n of tI(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=e7(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,tI(e),t))&&(!e.endAt||!!function(e,t,n){let r=e7(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,tI(e),t))}function tx(e){return(t,n)=>{let r=!1;for(let s of tI(e)){let e=function(e,t,n){let r=e.field.isKeyField()?H.comparator(t.key,n.key):function(e,t,n){let r=t.data.field(e),s=n.data.field(e);return null!==r&&null!==s?eQ(r,s):S(42886)}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return S(19790,{direction:e.dir})}}(s,t,n);if(0!==e)return e;r=r||s.field.isKeyField()}return 0}}class tR{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){eg(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){return ep(this.inner)}size(){return this.innerSize}}let tV=new ey(H.comparator),tO=new ey(H.comparator);function tL(...e){let t=tO;for(let n of e)t=t.insert(n.key,n);return t}function tF(e){let t=tO;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function tP(){return new tR(e=>e.toString(),(e,t)=>e.isEqual(t))}let tM=new ey(H.comparator),tU=new e_(H.comparator);function tq(...e){let t=tU;for(let n of e)t=t.add(n);return t}let t$=new e_(q);function tz(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:ef(t)?"-0":t}}function tB(e){return{integerValue:""+e}}class tj{constructor(){this._=void 0}}function tG(e,t){return e instanceof tY?eJ(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}class tK extends tj{}class tQ extends tj{constructor(e){super(),this.elements=e}}function tW(e,t){let n=tZ(t);for(let t of e.elements)n.some(e=>eG(e,t))||n.push(t);return{arrayValue:{values:n}}}class tH extends tj{constructor(e){super(),this.elements=e}}function tX(e,t){let n=tZ(t);for(let t of e.elements)n=n.filter(e=>!eG(e,t));return{arrayValue:{values:n}}}
1class tY extends tj{constructor(e,t){super(),this.serializer=e,this.Ee=t}}function tJ(e){return eA(e.integerValue||e.doubleValue)}function tZ(e){return eZ(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class t0{constructor(e,t){this.version=e,this.transformResults=t}}class t1{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new t1}static exists(e){return new t1(void 0,e)}static updateTime(e){return new t1(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 t2(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class t3{}function t4(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new nn(e.key,t1.none()):new t8(e.key,e.data,t1.none());{let n=e.data,r=e5.empty(),s=new e_(W.comparator);for(let e of t.fields)if(!s.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),s=s.add(e)}return new t9(e.key,r,new eT(s.toArray()),t1.none())}}function t6(e,t,n,r){return e instanceof t8?function(e,t,n,r){if(!t2(e.precondition,t))return n;let s=e.value.clone(),i=nt(e.fieldTransforms,r,t);return s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null}(e,t,n,r):e instanceof t9?function(e,t,n,r){if(!t2(e.precondition,t))return n;let s=nt(e.fieldTransforms,r,t),i=t.data;return(i.setAll(t7(e)),i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===n)?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):t2(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function t5(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)&&B(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof tQ&&r instanceof tQ||n instanceof tH&&r instanceof tH?B(n.elements,r.elements,eG):n instanceof tY&&r instanceof tY?eG(n.Ee,r.Ee):n instanceof tK&&r instanceof tK)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class t8 extends t3{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 t9 extends t3{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function t7(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 ne(e,t,n){let r=new Map;b(e.length===n.length,32656,{Ae:n.length,Re:e.length});for(let i=0;i<n.length;i++){var s;let a=e[i],o=a.transform,l=t.data.field(a.field);r.set(a.field,(s=n[i],o instanceof tQ?tW(o,l):o instanceof tH?tX(o,l):s))}return r}function nt(e,t,n){let r=new Map;for(let s of e){let e=s.transform,i=n.data.field(s.field);r.set(s.field,e instanceof tK?function(e,t){let n={fields:{[ek]:{stringValue:eD},[eR]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&eV(t)&&(t=eO(t)),t&&(n.fields[ex]=t),{mapValue:n}}(t,i):e instanceof tQ?tW(e,i):e instanceof tH?tX(e,i):function(e,t){let n=tG(e,t),r=tJ(n)+tJ(e.Ee);return eJ(n)&&eJ(e.Ee)?tB(r):tz(e.serializer,r)}(e,i))}return r}class nn extends t3{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class nr extends t3{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class ns{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 r=this.mutations[t];r.key.isEqual(e.key)&&function(e,t,n){e instanceof t8?function(e,t,n){let r=e.value.clone(),s=ne(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}
1(e,t,n):e instanceof t9?function(e,t,n){if(!t2(e.precondition,t))return t.convertToUnknownDocument(n.version);let r=ne(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(t7(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}(r,e,n[t])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=t6(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=t6(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=tP();return this.mutations.forEach(r=>{let s=e.get(r.key),i=s.overlayedDocument,a=this.applyToLocalView(i,s.mutatedFields),o=t4(i,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),i.isValidDocument()||i.convertToNoDocument(ei.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),tq())}isEqual(e){return this.batchId===e.batchId&&B(this.mutations,e.mutations,(e,t)=>t5(e,t))&&B(this.baseMutations,e.baseMutations,(e,t)=>t5(e,t))}}class ni{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){b(e.mutations.length===n.length,58842,{Ve:e.mutations.length,me:n.length});let r=tM,s=e.mutations;for(let e=0;e<s.length;e++)r=r.insert(s[e].key,n[e].version);return new ni(e,t,n,r)}}class na{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{ 2 largestBatchId: ${this.largestBatchId}, 3 mutation: ${this.mutation.toString()} 4 }`}}class no{constructor(e,t){this.count=e,this.unchangedNames=t}}function nl(e){if(void 0===e)return E("GRPC error has no .code"),A.UNKNOWN;switch(e){case r.OK:return A.OK;case r.CANCELLED:return A.CANCELLED;case r.UNKNOWN:return A.UNKNOWN;case r.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case r.INTERNAL:return A.INTERNAL;case r.UNAVAILABLE:return A.UNAVAILABLE;case r.UNAUTHENTICATED:return A.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case r.NOT_FOUND:return A.NOT_FOUND;case r.ALREADY_EXISTS:return A.ALREADY_EXISTS;case r.PERMISSION_DENIED:return A.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case r.ABORTED:return A.ABORTED;case r.OUT_OF_RANGE:return A.OUT_OF_RANGE;case r.UNIMPLEMENTED:return A.UNIMPLEMENTED;case r.DATA_LOSS:return A.DATA_LOSS;default:return S(39323,{code:e})}}(s=r||(r={}))[s.OK=0]="OK",s[s.CANCELLED=1]="CANCELLED",s[s.UNKNOWN=2]="UNKNOWN",s[s.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",s[s.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",s[s.NOT_FOUND=5]="NOT_FOUND",s[s.ALREADY_EXISTS=6]="ALREADY_EXISTS",s[s.PERMISSION_DENIED=7]="PERMISSION_DENIED",s[s.UNAUTHENTICATED=16]="UNAUTHENTICATED",s[s.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",s[s.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",s[s.ABORTED=10]="ABORTED",s[s.OUT_OF_RANGE=11]="OUT_OF_RANGE",s[s.UNIMPLEMENTED=12]="UNIMPLEMENTED",s[s.INTERNAL=13]="INTERNAL",s[s.UNAVAILABLE=14]="UNAVAILABLE",s[s.DATA_LOSS=15]="DATA_LOSS";let nu=new c.jz([0xffffffff,0xffffffff],0);function nh(e){let t=M().encode(e),n=new c.VV;return n.update(t),new Uint8Array(n.digest())}function nc(e){let t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),s=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new c.jz([n,r],0),new c.jz([s,i],0)]}class nd{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new nf(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new nf(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new nf(`Invalid padding when bitmap length is 0: ${t}`);this.fe=8*e.length-t,this.ge=c.jz.fromNumber(this.fe)}pe(e,t,n){let r=e.add(t.multiply(c.jz.fromNumber(n)));return 1===r.compare(nu)&&(r=new c.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.ge).toNumber()}ye(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.fe)return!1;let[t,n]=nc(nh(e));for(let e=0;e<this.hashCount;e++){let r=this.pe(t,n,e);if(!this.ye(r))return!1}return!0}static create(e,t,n){let r=new nd(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);
4return n.forEach(e=>r.insert(e)),r}insert(e){if(0===this.fe)return;let[t,n]=nc(nh(e));for(let e=0;e<this.hashCount;e++){let r=this.pe(t,n,e);this.we(r)}}we(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class nf extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class nm{constructor(e,t,n,r,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let r=new Map;return r.set(e,ng.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new nm(ei.min(),r,new ey(q),tV,tq())}}class ng{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new ng(n,t,tq(),tq(),tq())}}class np{constructor(e,t,n,r){this.Se=e,this.removedTargetIds=t,this.key=n,this.be=r}}class ny{constructor(e,t){this.targetId=e,this.De=t}}class nv{constructor(e,t,n=eS.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class nw{constructor(){this.ve=0,this.Ce=nT(),this.Fe=eS.EMPTY_BYTE_STRING,this.Me=!1,this.xe=!0}get current(){return this.Me}get resumeToken(){return this.Fe}get Oe(){return 0!==this.ve}get Ne(){return this.xe}Be(e){e.approximateByteSize()>0&&(this.xe=!0,this.Fe=e)}Le(){let e=tq(),t=tq(),n=tq();return this.Ce.forEach((r,s)=>{switch(s){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:S(38017,{changeType:s})}}),new ng(this.Fe,this.Me,e,t,n)}ke(){this.xe=!1,this.Ce=nT()}qe(e,t){this.xe=!0,this.Ce=this.Ce.insert(e,t)}Qe(e){this.xe=!0,this.Ce=this.Ce.remove(e)}$e(){this.ve+=1}Ue(){this.ve-=1,b(this.ve>=0,3241,{ve:this.ve})}Ke(){this.xe=!0,this.Me=!0}}class n_{constructor(e){this.We=e,this.Ge=new Map,this.ze=tV,this.je=nE(),this.Je=nE(),this.He=new ey(q)}Ye(e){for(let t of e.Se)e.be&&e.be.isFoundDocument()?this.Ze(t,e.be):this.Xe(t,e.key,e.be);for(let t of e.removedTargetIds)this.Xe(t,e.key,e.be)}et(e){this.forEachTarget(e,t=>{let n=this.tt(t);switch(e.state){case 0:this.nt(t)&&n.Be(e.resumeToken);break;case 1:n.Ue(),n.Oe||n.ke(),n.Be(e.resumeToken);break;case 2:n.Ue(),n.Oe||this.removeTarget(t);break;case 3:this.nt(t)&&(n.Ke(),n.Be(e.resumeToken));break;case 4:this.nt(t)&&(this.rt(t),n.Be(e.resumeToken));break;default:S(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Ge.forEach((e,n)=>{this.nt(n)&&t(n)})}it(e){let t=e.targetId,n=e.De.count,r=this.st(t);if(r){let s=r.target;if(tw(s))if(0===n){let e=new H(s.path);this.Xe(t,e,e8.newNoDocument(e,ei.min()))}else b(1===n,20013,{expectedCount:n});else{let r=this.ot(t);if(r!==n){let n=this._t(e),s=n?this.ut(n,e,r):1;0!==s&&(this.rt(t),this.He=this.He.insert(t,2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}_t(e){let t,n,r=e.De.unchangedNames;if(!r||!r.bits)return null;let{bits:{bitmap:s="",padding:i=0},hashCount:a=0}=r;try{t=eN(s).toUint8Array()}catch(e){if(e instanceof eI)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 nd(t,i,a)}catch(e){return T(e instanceof nf?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===n.fe?null:n}ut(e,t,n){return 2*(t.De.count!==n-this.ht(e,t.targetId))}ht(e,t){let n=this.We.getRemoteKeysForTarget(t),r=0;return n.forEach(n=>{let s=this.We.lt(),i=`projects/${s.projectId}/databases/${s.database}/documents/${n.path.canonicalString()}`;e.mightContain(i)||(this.Xe(t,n,null),r++)}),r}Pt(e){let t=new Map;this.Ge.forEach((n,r)=>{let s=this.st(r);if(s){if(n.current&&tw(s.target)){let t=new H(s.target.path);this.Tt(t).has(r)||this.It(r,t)||this.Xe(r,t,e8.newNoDocument(t,e))}n.Ne&&(t.set(r,n.Le()),n.ke())}});let n=tq();this.Je.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{let t=this.st(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.ze.forEach((t,n)=>n.setReadTime(e));let r=new nm(e,t,this.He,this.ze,n);return this.ze=tV,this.je=nE(),this.Je=nE(),this.He=new ey(q),r}Ze(e,t){if(!this.nt(e))return;
4let n=2*!!this.It(e,t.key);this.tt(e).qe(t.key,n),this.ze=this.ze.insert(t.key,t),this.je=this.je.insert(t.key,this.Tt(t.key).add(e)),this.Je=this.Je.insert(t.key,this.dt(t.key).add(e))}Xe(e,t,n){if(!this.nt(e))return;let r=this.tt(e);this.It(e,t)?r.qe(t,1):r.Qe(t),this.Je=this.Je.insert(t,this.dt(t).delete(e)),this.Je=this.Je.insert(t,this.dt(t).add(e)),n&&(this.ze=this.ze.insert(t,n))}removeTarget(e){this.Ge.delete(e)}ot(e){let t=this.tt(e).Le();return this.We.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.tt(e).$e()}tt(e){let t=this.Ge.get(e);return t||(t=new nw,this.Ge.set(e,t)),t}dt(e){let t=this.Je.get(e);return t||(t=new e_(q),this.Je=this.Je.insert(e,t)),t}Tt(e){let t=this.je.get(e);return t||(t=new e_(q),this.je=this.je.insert(e,t)),t}nt(e){let t=null!==this.st(e);return t||_("WatchChangeAggregator","Detected inactive target",e),t}st(e){let t=this.Ge.get(e);return t&&t.Oe?null:this.We.Et(e)}rt(e){this.Ge.set(e,new nw),this.We.getRemoteKeysForTarget(e).forEach(t=>{this.Xe(e,t,null)})}It(e,t){return this.We.getRemoteKeysForTarget(e).has(t)}}function nE(){return new ey(H.comparator)}function nT(){return new ey(H.comparator)}let nI={asc:"ASCENDING",desc:"DESCENDING"},nS={"<":"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"},nC={and:"AND",or:"OR"};class nb{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function nA(e,t){return e.useProto3Json||null==t?t:{value:t}}function nN(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 nD(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function nk(e){return b(!!e,49232),ei.fromTimestamp(function(e){let t=eb(e);return new es(t.seconds,t.nanos)}(e))}function nx(e,t){return nR(e,t).canonicalString()}function nR(e,t){let n=new K(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function nV(e){let t=K.fromString(e);return b(nz(t),10190,{key:t.toString()}),t}function nO(e,t){return nx(e.databaseId,t.path)}function nL(e,t){let n=nV(t);if(n.get(1)!==e.databaseId.projectId)throw new N(A.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 N(A.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new H(nM(n))}function nF(e,t){return nx(e.databaseId,t)}function nP(e){return new K(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function nM(e){return b(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function nU(e,t,n){return{name:nO(e,t),fields:n.value.mapValue.fields}}function nq(e){return{fieldPath:e.canonicalString()}}function n$(e){return W.fromServerFormat(e.fieldPath)}function nz(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class nB{constructor(e,t,n,r,s=ei.min(),i=ei.min(),a=eS.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new nB(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new nB(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new nB(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new nB(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class nj{constructor(e){this.gt=e}}class nG{constructor(){}bt(e,t){this.Dt(e,t),t.vt()}Dt(e,t){if("nullValue"in e)this.Ct(t,5);else if("booleanValue"in e)this.Ct(t,10),t.Ft(+!!e.booleanValue);else if("integerValue"in e)this.Ct(t,15),t.Ft(eA(e.integerValue));else if("doubleValue"in e){let n=eA(e.doubleValue);isNaN(n)?this.Ct(t,13):(this.Ct(t,15),ef(n)?t.Ft(0):t.Ft(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Ct(t,20),"string"==typeof n&&(n=eb(n)),t.Mt(`${n.seconds||""}`),t.Ft(n.nanos||0)}else if("stringValue"in e)this.xt(e.stringValue,t),this.Ot(t);else if("bytesValue"in e)this.Ct(t,30),t.Nt(eN(e.bytesValue)),this.Ot(t);else if("referenceValue"in e)this.Bt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Ct(t,45),t.Ft(n.latitude||0),t.Ft(n.longitude||0)}else"mapValue"in e?e6(e)?this.Ct(t,Number.MAX_SAFE_INTEGER):e3(e)?this.Lt(e.mapValue,t):(this.kt(e.mapValue,t),this.Ot(t)):"arrayValue"in e?(this.qt(e.arrayValue,t),this.Ot(t)):S(19022,{Qt:e})}xt(e,t){this.Ct(t,25),this.$t(e,t)}$t(e,t){t.Mt(e)}kt(e,t){let n=e.fields||{};for(let e of(this.Ct(t,55),Object.keys(n)))this.xt(e,t),this.Dt(n[e],t)}Lt(e,t){var n,r;let s=e.fields||{};this.Ct(t,53);let i=(null==(r=null==(n=s[eB].arrayValue)?void 0:n.values)?void 0:r.length)||0;this.Ct(t,15),t.Ft(eA(i)),this.xt(eB,t),this.Dt(s[eB],t)}qt(e,t){let n=e.values||[];for(let e of(this.Ct(t,50),n))this.Dt(e,t)}
4Bt(e,t){this.Ct(t,37),H.fromName(e).path.forEach(e=>{this.Ct(t,60),this.$t(e,t)})}Ct(e,t){e.Ft(t)}Ot(e){e.Ft(2)}}nG.Ut=new nG;class nK{constructor(){this.Dn=new nQ}addToCollectionParentIndex(e,t){return this.Dn.add(t),eh.resolve()}getCollectionParents(e,t){return eh.resolve(this.Dn.getEntries(t))}addFieldIndex(e,t){return eh.resolve()}deleteFieldIndex(e,t){return eh.resolve()}deleteAllFieldIndexes(e){return eh.resolve()}createTargetIndexes(e,t){return eh.resolve()}getDocumentsMatchingTarget(e,t){return eh.resolve(null)}getIndexType(e,t){return eh.resolve(0)}getFieldIndexes(e,t){return eh.resolve([])}getNextCollectionGroupToUpdate(e){return eh.resolve(null)}getMinOffset(e,t){return eh.resolve(eo.min())}getMinOffsetFromCollectionGroup(e,t){return eh.resolve(eo.min())}updateCollectionGroup(e,t,n){return eh.resolve()}updateIndexEntries(e,t){return eh.resolve()}}class nQ{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new e_(K.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}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 e_(K.comparator)).toArray()}}new Uint8Array(0);let nW={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class nH{static withCacheSize(e){return new nH(e,nH.DEFAULT_COLLECTION_PERCENTILE,nH.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}nH.DEFAULT_COLLECTION_PERCENTILE=10,nH.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,nH.DEFAULT=new nH(0x2800000,nH.DEFAULT_COLLECTION_PERCENTILE,nH.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),nH.DISABLED=new nH(-1,0,0);class nX{constructor(e){this._r=e}next(){return this._r+=2,this._r}static ar(){return new nX(0)}static ur(){return new nX(-1)}}let nY="LruGarbageCollector";function nJ([e,t],[n,r]){let s=q(e,n);return 0===s?q(t,r):s}class nZ{constructor(e){this.Tr=e,this.buffer=new e_(nJ),this.Ir=0}dr(){return++this.Ir}Er(e){let t=[e,this.dr()];if(this.buffer.size<this.Tr)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>nJ(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class n0{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Ar=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Rr(6e4)}stop(){this.Ar&&(this.Ar.cancel(),this.Ar=null)}get started(){return null!==this.Ar}Rr(e){_(nY,`Garbage collection scheduled in ${e}ms`),this.Ar=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Ar=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){ec(e)?_(nY,"Ignoring IndexedDB error during garbage collection: ",e):await eu(e)}await this.Rr(3e5)})}}class n1{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.mr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return eh.resolve(ed.ue);let n=new nZ(t);return this.Vr.forEachTarget(e,e=>n.Er(e.sequenceNumber)).next(()=>this.Vr.gr(e,e=>n.Er(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Vr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(_("LruGarbageCollector","Garbage collection skipped; disabled"),eh.resolve(nW)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(_("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),nW):this.pr(e,t))}getCacheSize(e){return this.Vr.getCacheSize(e)}pr(e,t){let n,r,s,i,a,o,l,h=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(_("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,i=Date.now(),this.nthSequenceNumber(e,r))).next(r=>(n=r,a=Date.now(),this.removeTargets(e,n,t))).next(t=>(s=t,o=Date.now(),this.removeOrphanedDocuments(e,n))).next(e=>(l=Date.now(),w()<=u.$b.DEBUG&&_("LruGarbageCollector",`LRU Garbage Collection 5 Counted targets in ${i-h}ms 6 Determined least recently used ${r} in `+(a-i)+"ms\n"+` Removed ${s} targets in `+(o-a)+"ms\n"+` Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-h}ms`),eh.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:s,documentsRemoved:e})))}}class n2{constructor(){this.changes=new tR(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,e8.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?eh.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)}
6assertNotApplied(){}}class n3{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class n4{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&&t6(n.mutation,e,eT.empty(),es.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,tq()).next(()=>t))}getLocalViewOfDocuments(e,t,n=tq()){let r=tP();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=tL();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=tP();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,tq()))}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 s=tV,i=tP(),a=tP();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof t9)?s=s.insert(t.key,t):void 0!==a?(i.set(t.key,a.mutation.getFieldMask()),t6(a.mutation,t,a.mutation.getFieldMask(),es.now())):i.set(t.key,eT.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>i.set(e,t)),t.forEach((e,t)=>{var n;return a.set(e,new n3(t,null!=(n=i.get(e))?n:null))}),a))}recalculateAndSaveOverlays(e,t){let n=tP(),r=new ey((e,t)=>e-t),s=tq();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let s of e)s.keys().forEach(e=>{let i=t.get(e);if(null===i)return;let a=n.get(e)||eT.empty();a=s.applyToLocalView(i,a),n.set(e,a);let o=(r.get(s.batchId)||tq()).add(e);r=r.insert(s.batchId,o)})}).next(()=>{let i=[],a=r.getReverseIterator();for(;a.hasNext();){let r=a.getNext(),o=r.key,l=r.value,u=tP();l.forEach(e=>{if(!s.has(e)){let r=t4(t.get(e),n.get(e));null!==r&&u.set(e,r),s=s.add(e)}}),i.push(this.documentOverlayCache.saveOverlays(e,o,u))}return eh.waitFor(i)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,n,r){return H.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):tT(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(s=>{let i=r-s.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-s.size):eh.resolve(tP()),a=-1,o=s;return i.next(t=>eh.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),s.get(t)?eh.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,s)).next(()=>this.computeViews(e,o,t,tq())).next(e=>({batchId:a,changes:tF(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new H(t)).next(e=>{let t=tL();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let s=t.collectionGroup,i=tL();return this.indexManager.getCollectionParents(e,s).next(a=>eh.forEach(a,a=>{let o=new t_(a.child(s),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)=>{i=i.insert(e,t)})})}).next(()=>i))}getDocumentsMatchingCollectionQuery(e,t,n,r){let s;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(i=>(s=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,s,r))).next(e=>{s.forEach((t,n)=>{let r=n.getKey();null===e.get(r)&&(e=e.insert(r,e8.newInvalidDocument(r)))});let n=tL();return e.forEach((e,r)=>{let i=s.get(e);void 0!==i&&t6(i.mutation,r,eT.empty(),es.now()),tk(t,r)&&(n=n.insert(e,r))}),n})}}class n6{constructor(e){this.serializer=e,this.Br=new Map,this.Lr=new Map}
6getBundleMetadata(e,t){return eh.resolve(this.Br.get(t))}saveBundleMetadata(e,t){return this.Br.set(t.id,{id:t.id,version:t.version,createTime:nk(t.createTime)}),eh.resolve()}getNamedQuery(e,t){return eh.resolve(this.Lr.get(t))}saveNamedQuery(e,t){return this.Lr.set(t.name,{name:t.name,query:function(e){let t=function(e){var t;let n,r=function(e){let t=nV(e);return 4===t.length?K.emptyPath():nM(t)}(e.parent),s=e.structuredQuery,i=s.from?s.from.length:0,a=null;if(i>0){b(1===i,65062);let e=s.from[0];e.allDescendants?a=e.collectionId:r=r.child(e.collectionId)}let o=[];s.where&&(o=function(e){var t;let n=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=n$(e.unaryFilter.field);return tr.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=n$(e.unaryFilter.field);return tr.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=n$(e.unaryFilter.field);return tr.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let s=n$(e.unaryFilter.field);return tr.create(s,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return S(61313);default:return S(60726)}}(t):void 0!==t.fieldFilter?tr.create(n$(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";case"OPERATOR_UNSPECIFIED":return S(58110);default:return S(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?ts.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return S(1026)}}(t.compositeFilter.op)):S(30097,{filter:t})}(e);return n instanceof ts&&ta(t=n)&&ti(t)?n.getFilters():[n]}(s.where));let l=[];s.orderBy&&(l=s.orderBy.map(e=>new tt(n$(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;s.limit&&(u=null==(n="object"==typeof(t=s.limit)?t.value:t)?null:n);let h=null;s.startAt&&(h=function(e){let t=!!e.before;return new e9(e.values||[],t)}(s.startAt));let c=null;return s.endAt&&(c=function(e){let t=!e.before;return new e9(e.values||[],t)}(s.endAt)),new t_(r,a,l,o,u,"F",h,c)}({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?tb(t,t.limit,"L"):t}(t.bundledQuery),readTime:nk(t.readTime)}),eh.resolve()}}class n5{constructor(){this.overlays=new ey(H.comparator),this.kr=new Map}getOverlay(e,t){return eh.resolve(this.overlays.get(t))}getOverlays(e,t){let n=tP();return eh.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.wt(e,t,r)}),eh.resolve()}removeOverlaysForBatchId(e,t,n){let r=this.kr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.kr.delete(n)),eh.resolve()}getOverlaysForCollection(e,t,n){let r=tP(),s=t.length+1,i=new H(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){let e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return eh.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let s=new ey((e,t)=>e-t),i=this.overlays.getIterator();for(;i.hasNext();){let e=i.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=s.get(e.largestBatchId);null===t&&(t=tP(),s=s.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=tP(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return eh.resolve(a)}wt(e,t,n){let r=this.overlays.get(n.key);if(null!==r){let e=this.kr.get(r.largestBatchId).delete(n.key);this.kr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new na(t,n));let s=this.kr.get(t);void 0===s&&(s=tq(),this.kr.set(t,s)),this.kr.set(t,s.add(n.key))}}class n8{constructor(){this.sessionToken=eS.EMPTY_BYTE_STRING}getSessionToken(e){return eh.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,eh.resolve()}}class n9{constructor(){this.qr=new e_(n7.Qr),this.$r=new e_(n7.Ur)}isEmpty(){return this.qr.isEmpty()}addReference(e,t){let n=new n7(e,t);this.qr=this.qr.add(n),this.$r=this.$r.add(n)}
6Kr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Wr(new n7(e,t))}Gr(e,t){e.forEach(e=>this.removeReference(e,t))}zr(e){let t=new H(new K([])),n=new n7(t,e),r=new n7(t,e+1),s=[];return this.$r.forEachInRange([n,r],e=>{this.Wr(e),s.push(e.key)}),s}jr(){this.qr.forEach(e=>this.Wr(e))}Wr(e){this.qr=this.qr.delete(e),this.$r=this.$r.delete(e)}Jr(e){let t=new H(new K([])),n=new n7(t,e),r=new n7(t,e+1),s=tq();return this.$r.forEachInRange([n,r],e=>{s=s.add(e.key)}),s}containsKey(e){let t=new n7(e,0),n=this.qr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class n7{constructor(e,t){this.key=e,this.Hr=t}static Qr(e,t){return H.comparator(e.key,t.key)||q(e.Hr,t.Hr)}static Ur(e,t){return q(e.Hr,t.Hr)||H.comparator(e.key,t.key)}}class re{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.er=1,this.Yr=new e_(n7.Qr)}checkEmpty(e){return eh.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let s=this.er;this.er++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let i=new ns(s,t,n,r);for(let t of(this.mutationQueue.push(i),r))this.Yr=this.Yr.add(new n7(t.key,s)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return eh.resolve(i)}lookupMutationBatch(e,t){return eh.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.Xr(t+1),r=n<0?0:n;return eh.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return eh.resolve(0===this.mutationQueue.length?-1:this.er-1)}getAllMutationBatches(e){return eh.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new n7(t,0),r=new n7(t,1/0),s=[];return this.Yr.forEachInRange([n,r],e=>{let t=this.Zr(e.Hr);s.push(t)}),eh.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new e_(q);return t.forEach(e=>{let t=new n7(e,0),r=new n7(e,1/0);this.Yr.forEachInRange([t,r],e=>{n=n.add(e.Hr)})}),eh.resolve(this.ei(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,s=n;H.isDocumentKey(s)||(s=s.child(""));let i=new n7(new H(s),0),a=new e_(q);return this.Yr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Hr)),!0)},i),eh.resolve(this.ei(a))}ei(e){let t=[];return e.forEach(e=>{let n=this.Zr(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){b(0===this.ti(t.batchId,"removed"),55003),this.mutationQueue.shift();let n=this.Yr;return eh.forEach(t.mutations,r=>{let s=new n7(r.key,t.batchId);return n=n.delete(s),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.Yr=n})}rr(e){}containsKey(e,t){let n=new n7(t,0),r=this.Yr.firstAfterOrEqual(n);return eh.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,eh.resolve()}ti(e,t){return this.Xr(e)}Xr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Zr(e){let t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class rt{constructor(e){this.ni=e,this.docs=new ey(H.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.ni(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,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 eh.resolve(n?n.document.mutableCopy():e8.newInvalidDocument(t))}getEntries(e,t){let n=tV;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():e8.newInvalidDocument(e))}),eh.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let s=tV,i=t.path,a=new H(i.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){let{key:e,value:{document:a}}=o.getNext();if(!i.isPrefixOf(e.path))break;e.path.length>i.length+1||0>=function(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n||0!==(n=H.comparator(e.documentKey,t.documentKey))?n:q(e.largestBatchId,t.largestBatchId)}(new eo(a.readTime,a.key,-1),n)||(r.has(a.key)||tk(t,a))&&(s=s.insert(a.key,a.mutableCopy()))}return eh.resolve(s)}getAllFromCollectionGroup(e,t,n,r){S(9500)}ri(e,t){return eh.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new rn(this)}getSize(e){return eh.resolve(this.size)}}class rn extends n2{constructor(e){super(),this.Or=e}applyChanges(e){let t=[];
vendor: 5,010 bytes, line 6
6return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.Or.addEntry(e,r)):this.Or.removeEntry(n)}),eh.waitFor(t)}getFromCache(e,t){return this.Or.getEntry(e,t)}getAllFromCache(e,t){return this.Or.getEntries(e,t)}}class rr{constructor(e){this.persistence=e,this.ii=new tR(e=>ty(e),tv),this.lastRemoteSnapshotVersion=ei.min(),this.highestTargetId=0,this.si=0,this.oi=new n9,this.targetCount=0,this._i=nX.ar()}forEachTarget(e,t){return this.ii.forEach((e,n)=>t(n)),eh.resolve()}getLastRemoteSnapshotVersion(e){return eh.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return eh.resolve(this.si)}allocateTargetId(e){return this.highestTargetId=this._i.next(),eh.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.si&&(this.si=t),eh.resolve()}hr(e){this.ii.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this._i=new nX(t),this.highestTargetId=t),e.sequenceNumber>this.si&&(this.si=e.sequenceNumber)}addTargetData(e,t){return this.hr(t),this.targetCount+=1,eh.resolve()}updateTargetData(e,t){return this.hr(t),eh.resolve()}removeTargetData(e,t){return this.ii.delete(t.target),this.oi.zr(t.targetId),this.targetCount-=1,eh.resolve()}removeTargets(e,t,n){let r=0,s=[];return this.ii.forEach((i,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.ii.delete(i),s.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)}),eh.waitFor(s).next(()=>r)}getTargetCount(e){return eh.resolve(this.targetCount)}getTargetData(e,t){let n=this.ii.get(t)||null;return eh.resolve(n)}addMatchingKeys(e,t,n){return this.oi.Kr(t,n),eh.resolve()}removeMatchingKeys(e,t,n){this.oi.Gr(t,n);let r=this.persistence.referenceDelegate,s=[];return r&&t.forEach(t=>{s.push(r.markPotentiallyOrphaned(e,t))}),eh.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.oi.zr(t),eh.resolve()}getMatchingKeysForTargetId(e,t){let n=this.oi.Jr(t);return eh.resolve(n)}containsKey(e,t){return eh.resolve(this.oi.containsKey(t))}}class rs{constructor(e,t){this.ai={},this.overlays={},this.ui=new ed(0),this.ci=!1,this.ci=!0,this.li=new n8,this.referenceDelegate=e(this),this.hi=new rr(this),this.indexManager=new nK,this.remoteDocumentCache=new rt(e=>this.referenceDelegate.Pi(e)),this.serializer=new nj(t),this.Ti=new n6(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ci=!1,Promise.resolve()}get started(){return this.ci}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new n5,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ai[e.toKey()];return n||(n=new re(t,this.referenceDelegate),this.ai[e.toKey()]=n),n}getGlobalsCache(){return this.li}getTargetCache(){return this.hi}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ti}runTransaction(e,t,n){_("MemoryPersistence","Starting transaction:",e);let r=new ri(this.ui.next());return this.referenceDelegate.Ii(),n(r).next(e=>this.referenceDelegate.di(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ei(e,t){return eh.or(Object.values(this.ai).map(n=>()=>n.containsKey(e,t)))}}class ri extends el{constructor(e){super(),this.currentSequenceNumber=e}}class ra{constructor(e){this.persistence=e,this.Ai=new n9,this.Ri=null}static Vi(e){return new ra(e)}get mi(){if(this.Ri)return this.Ri;throw S(60996)}addReference(e,t,n){return this.Ai.addReference(n,t),this.mi.delete(n.toString()),eh.resolve()}removeReference(e,t,n){return this.Ai.removeReference(n,t),this.mi.add(n.toString()),eh.resolve()}markPotentiallyOrphaned(e,t){return this.mi.add(t.toString()),eh.resolve()}removeTarget(e,t){this.Ai.zr(t.targetId).forEach(e=>this.mi.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.mi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ii(){this.Ri=new Set}di(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return eh.forEach(this.mi,n=>{let r=H.fromPath(n);return this.fi(e,r).next(e=>{e||t.removeEntry(r,ei.min())})}).next(()=>(this.Ri=null,t.apply(e)))}updateLimboDocument(e,t){return this.fi(e,t).next(e=>{e?this.mi.delete(t.toString()):this.mi.add(t.toString())})}Pi(e){return 0}fi(e,t){return eh.or([()=>eh.resolve(this.Ai.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}}class ro{constructor(e,t){this.persistence=e,this.gi=new tR(e=>(function(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"})(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new n1(this,t)}static Vi(e,t){return new ro(e,t)}Ii(){}di(e){return eh.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEac
6hTarget(e,t)}mr(e){let t=this.yr(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}yr(e){let t=0;return this.gr(e,e=>{t++}).next(()=>t)}gr(e,t){return eh.forEach(this.gi,(n,r)=>this.Sr(e,n,r).next(e=>e?eh.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(),s=r.newChangeBuffer();return r.ri(e,r=>this.Sr(e,r,t).next(e=>{e||(n++,s.removeEntry(r,ei.min()))})).next(()=>s.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.gi.set(t,e.currentSequenceNumber),eh.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),eh.resolve()}removeReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),eh.resolve()}updateLimboDocument(e,t){return this.gi.set(t,e.currentSequenceNumber),eh.resolve()}Pi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(ej(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let n=eO(t);return n?16+e(n):16;case 5:return 2*t.stringValue.length;case 6:return eN(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 s;return r=t.mapValue,s=0,eg(r.fields,(t,n)=>{s+=t.length+e(n)}),s;default:throw S(13486,{value:t})}}(e.data.value)),t}Sr(e,t,n){return eh.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.gi.get(t);return eh.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class rl{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Is=n,this.ds=r}static Es(e,t){let n=tq(),r=tq();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 rl(e,t.fromCache,n,r)}}class ru{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class rh{constructor(){this.As=!1,this.Rs=!1,this.Vs=100,this.fs=(0,h.nr)()?8:function(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}((0,h.ZQ)())>0?6:4}initialize(e,t){this.gs=e,this.indexManager=t,this.As=!0}getDocumentsMatchingQuery(e,t,n,r){let s={result:null};return this.ps(e,t).next(e=>{s.result=e}).next(()=>{if(!s.result)return this.ys(e,t,r,n).next(e=>{s.result=e})}).next(()=>{if(s.result)return;let n=new ru;return this.ws(e,t,n).next(r=>{if(s.result=r,this.Rs)return this.Ss(e,t,n,r.size)})}).next(()=>s.result)}Ss(e,t,n,r){return n.documentReadCount<this.Vs?(w()<=u.$b.DEBUG&&_("QueryEngine","SDK will not create cache indexes for query:",tD(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),eh.resolve()):(w()<=u.$b.DEBUG&&_("QueryEngine","Query:",tD(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.fs*r?(w()<=u.$b.DEBUG&&_("QueryEngine","The SDK decides to create cache indexes for query:",tD(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,tS(t))):eh.resolve())}ps(e,t){if(tE(t))return eh.resolve(null);let n=tS(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=tS(t=tb(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let s=tq(...r);return this.gs.getDocuments(e,s).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{let i=this.bs(t,r);return this.Ds(t,i,s,n.readTime)?this.ps(e,tb(t,null,"F")):this.vs(e,i,t,n)}))})))}ys(e,t,n,r){return tE(t)||r.isEqual(ei.min())?eh.resolve(null):this.gs.getDocuments(e,n).next(s=>{let i=this.bs(t,s);return this.Ds(t,i,n,r)?eh.resolve(null):(w()<=u.$b.DEBUG&&_("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),tD(t)),this.vs(e,i,t,function(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;
6return new eo(ei.fromTimestamp(1e9===r?new es(n+1,0):new es(n,r)),H.empty(),-1)}(r,0)).next(e=>e))})}bs(e,t){let n=new e_(tx(e));return t.forEach((t,r)=>{tk(e,r)&&(n=n.add(r))}),n}Ds(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;let s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||s.version.compareTo(r)>0)}ws(e,t,n){return w()<=u.$b.DEBUG&&_("QueryEngine","Using full collection scan to execute query:",tD(t)),this.gs.getDocumentsMatchingQuery(e,t,eo.min(),n)}vs(e,t,n,r){return this.gs.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let rc="LocalStore";class rd{constructor(e,t,n,r){this.persistence=e,this.Cs=t,this.serializer=r,this.Fs=new ey(q),this.Ms=new tR(e=>ty(e),tv),this.xs=new Map,this.Os=e.getRemoteDocumentCache(),this.hi=e.getTargetCache(),this.Ti=e.getBundleCache(),this.Ns(n)}Ns(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new n4(this.Os,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Os.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Fs))}}async function rf(e,t){return await e.persistence.runTransaction("Handle user change","readonly",n=>{let r;return e.mutationQueue.getAllMutationBatches(n).next(s=>(r=s,e.Ns(t),e.mutationQueue.getAllMutationBatches(n))).next(t=>{let s=[],i=[],a=tq();for(let e of r)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(n,a).next(e=>({Bs:e,removedBatchIds:s,addedBatchIds:i}))})})}function rm(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.hi.getLastRemoteSnapshotVersion(t))}async function rg(e,t,n){let r=e.Fs.get(t);try{n||await e.persistence.runTransaction("Release target",n?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,r))}catch(e){if(!ec(e))throw e;_(rc,`Failed to update sequence numbers for target ${t}: ${e}`)}e.Fs=e.Fs.remove(t),e.Ms.delete(r.target)}function rp(e,t,n){let r=ei.min(),s=tq();return e.persistence.runTransaction("Execute query","readwrite",i=>(function(e,t,n){let r=e.Ms.get(n);return void 0!==r?eh.resolve(e.Fs.get(r)):e.hi.getTargetData(t,n)})(e,i,tS(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,e.hi.getMatchingKeysForTargetId(i,t.targetId).next(e=>{s=e})}).next(()=>e.Cs.getDocumentsMatchingQuery(i,t,n?r:ei.min(),n?s:tq())).next(n=>{var r,i,a;let o;return r=e,i=t.collectionGroup||(t.path.length%2==1?t.path.lastSegment():t.path.get(t.path.length-2)),a=n,o=r.xs.get(i)||ei.min(),a.forEach((e,t)=>{t.readTime.compareTo(o)>0&&(o=t.readTime)}),r.xs.set(i,o),{documents:n,qs:s}}))}class ry{constructor(){this.activeTargetIds=t$}Gs(e){this.activeTargetIds=this.activeTargetIds.add(e)}zs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class rv{constructor(){this.Fo=new ry,this.Mo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.Fo.Gs(e),this.Mo[e]||"not-current"}updateQueryState(e,t,n){this.Mo[e]=t}removeLocalQueryTarget(e){this.Fo.zs(e)}isLocalQueryTarget(e){return this.Fo.activeTargetIds.has(e)}clearQueryState(e){delete this.Mo[e]}getAllActiveQueryTargets(){return this.Fo.activeTargetIds}isActiveQueryTarget(e){return this.Fo.activeTargetIds.has(e)}start(){return this.Fo=new ry,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class rw{xo(e){}shutdown(){}}let r_="ConnectivityMonitor";class rE{constructor(){this.Oo=()=>this.No(),this.Bo=()=>this.Lo(),this.ko=[],this.qo()}xo(e){this.ko.push(e)}shutdown(){window.removeEventListener("online",this.Oo),window.removeEventListener("offline",this.Bo)}qo(){window.addEventListener("online",this.Oo),window.addEventListener("offline",this.Bo)}No(){for(let e of(_(r_,"Network connectivity changed: AVAILABLE"),this.ko))e(0)}Lo(){for(let e of(_(r_,"Network connectivity changed: UNAVAILABLE"),this.ko))e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let rT=null;function rI(){return null===rT?rT=0x10000000+Math.round(0x80000000*Math.random()):rT++,"0x"+rT.toString(16)}let rS="RestConnection",rC={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
6Query:"runAggregationQuery"};class rb{get Qo(){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.$o=t+"://"+e.host,this.Uo=`projects/${n}/databases/${r}`,this.Ko=this.databaseId.database===eP?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Wo(e,t,n,r,s){let i=rI(),a=this.Go(e,t.toUriEncodedString());_(rS,`Sending RPC '${e}' ${i}:`,a,n);let o={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.Ko};this.zo(o,r,s);let{host:l}=new URL(a),u=(0,h.zJ)(l);return this.jo(e,a,o,n,u).then(t=>(_(rS,`Received RPC '${e}' ${i}: `,t),t),t=>{throw T(rS,`RPC '${e}' ${i} failed with error: `,t,"url: ",a,"request:",n),t})}Jo(e,t,n,r,s,i){return this.Wo(e,t,n,r,s)}zo(e,t,n){e["X-Goog-Api-Client"]="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)}Go(e,t){let n=rC[e];return`${this.$o}/v1/${t}:${n}`}terminate(){}}class rA{constructor(e){this.Ho=e.Ho,this.Yo=e.Yo}Zo(e){this.Xo=e}e_(e){this.t_=e}n_(e){this.r_=e}onMessage(e){this.i_=e}close(){this.Yo()}send(e){this.Ho(e)}s_(){this.Xo()}o_(){this.t_()}__(e){this.r_(e)}a_(e){this.i_(e)}}let rN="WebChannelConnection";class rD extends rb{constructor(e){super(e),this.u_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}jo(e,t,n,r,s){let i=rI();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();_(rN,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case d.O4.TIMEOUT:_(rN,`RPC '${e}' ${i} timed out`),a(new N(A.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(_(rN,`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(A).indexOf(t)>=0?t:A.UNKNOWN}(t.status);a(new N(e,t.message))}else a(new N(A.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new N(A.UNAVAILABLE,"Connection failed."));break;default:S(9055,{c_:e,streamId:i,l_:o.getLastErrorCode(),h_:o.getLastError()})}}finally{_(rN,`RPC '${e}' ${i} completed.`)}});let l=JSON.stringify(r);_(rN,`RPC '${e}' ${i} sending request:`,r),o.send(t,"POST",l,n,15)})}P_(e,t,n){let s=rI(),i=[this.$o,"/","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.zo(l.initMessageHeaders,t,n),l.encodeInitMessageHeaders=!0;let h=i.join("");_(rN,`Creating RPC '${e}' stream ${s}: ${h}`,l);let c=a.createWebChannel(h,l);this.T_(c);let f=!1,m=!1,g=new rA({Ho:t=>{m?_(rN,`Not sending because RPC '${e}' stream ${s} is closed:`,t):(f||(_(rN,`Opening RPC '${e}' stream ${s} transport.`),c.open(),f=!0),_(rN,`RPC '${e}' stream ${s} sending:`,t),c.send(t))},Yo:()=>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||(_(rN,`RPC '${e}' stream ${s} transport opened.`),g.s_())}),p(c,d.iO.EventType.CLOSE,()=>{m||(m=!0,_(rN,`RPC '${e}' stream ${s} transport closed`),g.__(),this.I_(c))}),p(c,d.iO.EventType.ERROR,t=>{m||(m=!0,T(rN,`RPC '${e}' stream ${s} transport errored. Name:`,t.name,"Message:",t.message),g.__(new N(A.UNAVAILABLE,"The operation could not be completed")))}),p(c,d.iO.EventType.MESSAGE,t=>{var n;if(!m){let i=t.data[0];b(!!i,16349);let a=(null==i?void 0:i.error)||(null==(n=i[0])?void 0:n.error);if(a){_(rN,`RPC '${e}' stream ${s} received error:`,a);let t=a.status,n=function(e){let t=r[e];if(void 0!==t)return nl(t)}(t),i=a.message;void 0===n&&(n=A.INTERNAL,i="Unknown error status: "+t+" with message "+a.message),m=!0,g.__(new N(n,i)),c.close()}else _(rN,`RPC '${e}' stream ${s} received:`,i),g.a_(i)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?_(rN,`RPC '${e}' stream ${s} detected buffering proxy`):t.stat===d.ro.NOPROXY&&_(rN,`RPC '${e}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{g.o_()},0),g}
6terminate(){this.u_.forEach(e=>e.close()),this.u_=[]}T_(e){this.u_.push(e)}I_(e){this.u_=this.u_.filter(t=>t===e)}}function rk(){return"undefined"!=typeof document?document:null}function rx(e){return new nb(e,!0)}class rR{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Fi=e,this.timerId=t,this.d_=n,this.E_=r,this.A_=s,this.R_=0,this.V_=null,this.m_=Date.now(),this.reset()}reset(){this.R_=0}f_(){this.R_=this.A_}g_(e){this.cancel();let t=Math.floor(this.R_+this.p_()),n=Math.max(0,Date.now()-this.m_),r=Math.max(0,t-n);r>0&&_("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.R_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.V_=this.Fi.enqueueAfterDelay(this.timerId,r,()=>(this.m_=Date.now(),e())),this.R_*=this.E_,this.R_<this.d_&&(this.R_=this.d_),this.R_>this.A_&&(this.R_=this.A_)}y_(){null!==this.V_&&(this.V_.skipDelay(),this.V_=null)}cancel(){null!==this.V_&&(this.V_.cancel(),this.V_=null)}p_(){return(Math.random()-.5)*this.R_}}let rV="PersistentStream";class rO{constructor(e,t,n,r,s,i,a,o){this.Fi=e,this.w_=n,this.S_=r,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.b_=0,this.D_=null,this.v_=null,this.stream=null,this.C_=0,this.F_=new rR(e,t)}M_(){return 1===this.state||5===this.state||this.x_()}x_(){return 2===this.state||3===this.state}start(){this.C_=0,4!==this.state?this.auth():this.O_()}async stop(){this.M_()&&await this.close(0)}N_(){this.state=0,this.F_.reset()}B_(){this.x_()&&null===this.D_&&(this.D_=this.Fi.enqueueAfterDelay(this.w_,6e4,()=>this.L_()))}k_(e){this.q_(),this.stream.send(e)}async L_(){if(this.x_())return this.close(0)}q_(){this.D_&&(this.D_.cancel(),this.D_=null)}Q_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.q_(),this.Q_(),this.F_.cancel(),this.b_++,4!==e?this.F_.reset():t&&t.code===A.RESOURCE_EXHAUSTED?(E(t.toString()),E("Using maximum backoff delay to prevent overloading the backend."),this.F_.f_()):t&&t.code===A.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.U_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.n_(t)}U_(){}auth(){this.state=1;let e=this.K_(this.b_),t=this.b_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.b_===t&&this.W_(e,n)},t=>{e(()=>{let e=new N(A.UNKNOWN,"Fetching auth token failed: "+t.message);return this.G_(e)})})}W_(e,t){let n=this.K_(this.b_);this.stream=this.z_(e,t),this.stream.Zo(()=>{n(()=>this.listener.Zo())}),this.stream.e_(()=>{n(()=>(this.state=2,this.v_=this.Fi.enqueueAfterDelay(this.S_,1e4,()=>(this.x_()&&(this.state=3),Promise.resolve())),this.listener.e_()))}),this.stream.n_(e=>{n(()=>this.G_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.C_?this.j_(e):this.onNext(e))})}O_(){this.state=5,this.F_.g_(async()=>{this.state=0,this.start()})}G_(e){return _(rV,`close with error: ${e}`),this.stream=null,this.close(4,e)}K_(e){return t=>{this.Fi.enqueueAndForget(()=>this.b_===e?t():(_(rV,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class rL extends rO{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.serializer=s}z_(e,t){return this.connection.P_("Listen",e,t)}j_(e){return this.onNext(e)}onNext(e){this.F_.reset();let t=function(e,t){let n;if("targetChange"in t){var r,s;t.targetChange;let i="NO_CHANGE"===(r=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===r?1:"REMOVE"===r?2:"CURRENT"===r?3:"RESET"===r?4:S(39313,{state:r}),a=t.targetChange.targetIds||[],o=(s=t.targetChange.resumeToken,e.useProto3Json?(b(void 0===s||"string"==typeof s,58123),eS.fromBase64String(s||"")):(b(void 0===s||s instanceof f||s instanceof Uint8Array,16193),eS.fromUint8Array(s||new Uint8Array))),l=t.targetChange.cause;n=new nv(i,a,o,l&&new N(void 0===l.code?A.UNKNOWN:nl(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 s=nL(e,r.document.name),i=nk(r.document.updateTime),a=r.document.createTime?nk(r.document.createTime):ei.min(),o=new e5({mapValue:{fields:r.document.fields}}),l=e8.newFoundDocument(s,i,a,o);n=new np(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let s=nL(e,r.document),i=r.readTime?nk(r.readTime):ei.min(),a=e8.newNoDocument(s,i);n=new np([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let s=nL(e,r.document);n=new np([],r.removedTargetIds||[],s,null)}else{if(!("filter"in t))return S(11601,{At:t});{t.filter;let e=t.filter;e.targetId;
6let{count:r=0,unchangedNames:s}=e,i=new no(r,s);n=new ny(e.targetId,i)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ei.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?ei.min():t.readTime?nk(t.readTime):ei.min()}(e);return this.listener.J_(t,n)}H_(e){let t={};t.database=nP(this.serializer),t.addTarget=function(e,t){let n,r=t.target;if((n=tw(r)?{documents:{documents:[nF(e,r.path)]}}:{query:function(e,t){var n,r;let s,i={structuredQuery:{}},a=t.path;null!==t.collectionGroup?(s=a,i.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(s=a.popLast(),i.structuredQuery.from=[{collectionId:a.lastSegment()}]),i.parent=nF(e,s);let o=function(e){if(0!==e.length)return function e(t){return t instanceof tr?function(e){if("=="===e.op){if(e1(e.value))return{unaryFilter:{field:nq(e.field),op:"IS_NAN"}};if(e0(e.value))return{unaryFilter:{field:nq(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(e1(e.value))return{unaryFilter:{field:nq(e.field),op:"IS_NOT_NAN"}};if(e0(e.value))return{unaryFilter:{field:nq(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:nq(e.field),op:nS[e.op],value:e.value}}}(t):t instanceof ts?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:nC[t.op],filters:n}}}(t):S(54877,{filter:t})}(ts.create(e,"and"))}(t.filters);o&&(i.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:nq(e.field),direction:nI[e.dir]}))}(t.orderBy);l&&(i.structuredQuery.orderBy=l);let u=nA(e,t.limit);return null!==u&&(i.structuredQuery.limit=u),t.startAt&&(i.structuredQuery.startAt={before:(n=t.startAt).inclusive,values:n.position}),t.endAt&&(i.structuredQuery.endAt={before:!(r=t.endAt).inclusive,values:r.position}),{Vt:i,parent:s}}(e,r).Vt}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=nD(e,t.resumeToken);let r=nA(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(ei.min())>0){n.readTime=nN(e,t.snapshotVersion.toTimestamp());let r=nA(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 S(28987,{purpose:e})}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.k_(t)}Y_(e){let t={};t.database=nP(this.serializer),t.removeTarget=e,this.k_(t)}}class rF extends rO{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.serializer=s}get Z_(){return this.C_>0}start(){this.lastStreamToken=void 0,super.start()}U_(){this.Z_&&this.X_([])}z_(e,t){return this.connection.P_("Write",e,t)}j_(e){return b(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,b(!e.writeResults||0===e.writeResults.length,55816),this.listener.ea()}onNext(e){var t,n;b(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.F_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(b(void 0!==n,14353),t.map(e=>{let t;return(t=e.updateTime?nk(e.updateTime):nk(n)).isEqual(ei.min())&&(t=nk(n)),new t0(t,e.transformResults||[])})):[]),s=nk(e.commitTime);return this.listener.ta(s,r)}na(){let e={};e.database=nP(this.serializer),this.k_(e)}X_(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>(function(e,t){var n;let r;if(t instanceof t8)r={update:nU(e,t.key,t.value)};else if(t instanceof nn)r={delete:nO(e,t.key)};else if(t instanceof t9)r={update:nU(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 nr))return S(16599,{Rt:t.type});r={verify:nO(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof tK)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof tQ)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof tH)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof tY)return{fieldPath:t.field.canonicalString(),increment:n.Ee};throw S(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:nN(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:S(27497)),r})(this.serializer,e))};this.k_(t)}}class rP{}class rM extends rP{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer
6=r,this.ra=!1}ia(){if(this.ra)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,n,r){return this.ia(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,i])=>this.connection.Wo(e,nR(t,n),r,s,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}Jo(e,t,n,r,s){return this.ia(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,a])=>this.connection.Jo(e,nR(t,n),r,i,a,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}terminate(){this.ra=!0,this.connection.terminate()}}class rU{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.sa=0,this.oa=null,this._a=!0}aa(){0===this.sa&&(this.ua("Unknown"),this.oa=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.oa=null,this.ca("Backend didn't respond within 10 seconds."),this.ua("Offline"),Promise.resolve())))}la(e){"Online"===this.state?this.ua("Unknown"):(this.sa++,this.sa>=1&&(this.ha(),this.ca(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ua("Offline")))}set(e){this.ha(),this.sa=0,"Online"===e&&(this._a=!1),this.ua(e)}ua(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ca(e){let t=`Could not reach Cloud Firestore backend. ${e} 7This 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._a?(E(t),this._a=!1):_("OnlineStateTracker",t)}ha(){null!==this.oa&&(this.oa.cancel(),this.oa=null)}}let rq="RemoteStore";class r${constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Pa=[],this.Ta=new Map,this.Ia=new Set,this.da=[],this.Ea=s,this.Ea.xo(e=>{n.enqueueAndForget(async()=>{rX(this)&&(_(rq,"Restarting streams for network reachability change."),await async function(e){e.Ia.add(4),await rB(e),e.Aa.set("Unknown"),e.Ia.delete(4),await rz(e)}(this))})}),this.Aa=new rU(n,r)}}async function rz(e){if(rX(e))for(let t of e.da)await t(!0)}async function rB(e){for(let t of e.da)await t(!1)}function rj(e,t){e.Ta.has(t.targetId)||(e.Ta.set(t.targetId,t),rH(e)?rW(e):sn(e).x_()&&rK(e,t))}function rG(e,t){let n=sn(e);e.Ta.delete(t),n.x_()&&rQ(e,t),0===e.Ta.size&&(n.x_()?n.B_():rX(e)&&e.Aa.set("Unknown"))}function rK(e,t){if(e.Ra.$e(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(ei.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}sn(e).H_(t)}function rQ(e,t){e.Ra.$e(t),sn(e).Y_(t)}function rW(e){e.Ra=new n_({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Et:t=>e.Ta.get(t)||null,lt:()=>e.datastore.serializer.databaseId}),sn(e).start(),e.Aa.aa()}function rH(e){return rX(e)&&!sn(e).M_()&&e.Ta.size>0}function rX(e){return 0===e.Ia.size}async function rY(e){e.Aa.set("Online")}async function rJ(e){e.Ta.forEach((t,n)=>{rK(e,t)})}async function rZ(e,t){e.Ra=void 0,rH(e)?(e.Aa.la(t),rW(e)):e.Aa.set("Unknown")}async function r0(e,t,n){if(e.Aa.set("Online"),t instanceof nv&&2===t.state&&t.cause)try{await async function(e,t){let n=t.cause;for(let r of t.targetIds)e.Ta.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Ta.delete(r),e.Ra.removeTarget(r))}(e,t)}catch(n){_(rq,"Failed to remove targets %s: %s ",t.targetIds.join(","),n),await r1(e,n)}else if(t instanceof np?e.Ra.Ye(t):t instanceof ny?e.Ra.it(t):e.Ra.et(t),!n.isEqual(ei.min()))try{let t=await rm(e.localStore);n.compareTo(t)>=0&&await function(e,t){let n=e.Ra.Pt(t);
7return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){let s=e.Ta.get(r);s&&e.Ta.set(r,s.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{let r=e.Ta.get(t);if(!r)return;e.Ta.set(t,r.withResumeToken(eS.EMPTY_BYTE_STRING,r.snapshotVersion)),rQ(e,t);let s=new nB(r.target,t,n,r.sequenceNumber);rK(e,s)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){_(rq,"Failed to raise snapshot:",t),await r1(e,t)}}async function r1(e,t,n){if(!ec(t))throw t;e.Ia.add(1),await rB(e),e.Aa.set("Offline"),n||(n=()=>rm(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{_(rq,"Retrying IndexedDB access"),await n(),e.Ia.delete(1),await rz(e)})}function r2(e,t){return t().catch(n=>r1(e,n,t))}async function r3(e){var t;let n=sr(e),r=e.Pa.length>0?e.Pa[e.Pa.length-1].batchId:-1;for(;rX(t=e)&&t.Pa.length<10;)try{let t=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,r);if(null===t){0===e.Pa.length&&n.B_();break}r=t.batchId,function(e,t){e.Pa.push(t);let n=sr(e);n.x_()&&n.Z_&&n.X_(t.mutations)}(e,t)}catch(t){await r1(e,t)}r4(e)&&r6(e)}function r4(e){return rX(e)&&!sr(e).M_()&&e.Pa.length>0}function r6(e){sr(e).start()}async function r5(e){sr(e).na()}async function r8(e){let t=sr(e);for(let n of e.Pa)t.X_(n.mutations)}async function r9(e,t,n){let r=e.Pa.shift(),s=ni.from(r,t,n);await r2(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await r3(e)}async function r7(e,t){t&&sr(e).Z_&&await async function(e,t){var n;if(function(e){switch(e){case A.OK:return S(64938);case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return S(15467,{code:e})}}(n=t.code)&&n!==A.ABORTED){let n=e.Pa.shift();sr(e).N_(),await r2(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await r3(e)}}(e,t),r4(e)&&r6(e)}async function se(e,t){e.asyncQueue.verifyOperationInProgress(),_(rq,"RemoteStore received new credentials");let n=rX(e);e.Ia.add(3),await rB(e),n&&e.Aa.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.Ia.delete(3),await rz(e)}async function st(e,t){t?(e.Ia.delete(2),await rz(e)):t||(e.Ia.add(2),await rB(e),e.Aa.set("Unknown"))}function sn(e){var t,n,r;return e.Va||(t=e.datastore,n=e.asyncQueue,r={Zo:rY.bind(null,e),e_:rJ.bind(null,e),n_:rZ.bind(null,e),J_:r0.bind(null,e)},t.ia(),e.Va=new rL(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.Va.N_(),rH(e)?rW(e):e.Aa.set("Unknown")):(await e.Va.stop(),e.Ra=void 0)})),e.Va}function sr(e){var t,n,r;return e.ma||(t=e.datastore,n=e.asyncQueue,r={Zo:()=>Promise.resolve(),e_:r5.bind(null,e),n_:r7.bind(null,e),ea:r8.bind(null,e),ta:r9.bind(null,e)},t.ia(),e.ma=new rF(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.ma.N_(),await r3(e)):(await e.ma.stop(),e.Pa.length>0&&(_(rq,`Stopping write stream with ${e.Pa.length} pending writes`),e.Pa=[]))})),e.ma}class ss{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,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,s){let i=new ss(e,t,Date.now()+n,r,s);return i.start(n),i}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new N(A.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 si(e,t){if(E("AsyncQueue",`${t}: ${e}`),ec(e))return new N(A.UNAVAILABLE,`${t}: ${e}`);throw e}class sa{static emptySet(e){return new sa(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||H.comparator(t.key,n.key):(e,t)=>H.comparator(e.key,t.key),this.keyedMap=tL(),this.sortedSet=new ey(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 sa)||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 sa;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class so{constructor(){this.fa=new ey(H.comparator)}track(e){let t=e.doc.key,n=this.fa.get(t);n?0!==e.type&&3===n.type?this.fa=this.fa.insert(t,e):3===e.type&&1!==n.type?this.fa=this.fa.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.fa=this.fa.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.fa=this.fa.remove(t):1===e.type&&2===n.type?this.fa=this.fa.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):S(63341,{At:e,ga:n}):this.fa=this.fa.insert(t,e)}pa(){let e=[];return this.fa.inorderTraversal((t,n)=>{e.push(n)}),e}}class sl{constructor(e,t,n,r,s,i,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}
7static fromInitialDocuments(e,t,n,r,s){let i=[];return t.forEach(e=>{i.push({type:0,doc:e})}),new sl(e,t,sa.emptySet(t),i,n,r,!0,!1,s)}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)&&tA(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 su{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(e=>e.ba())}}class sh{constructor(){this.queries=sc(),this.onlineState="Unknown",this.Da=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=sc(),n.forEach((e,n)=>{for(let e of n.wa)e.onError(t)})}(this,new N(A.ABORTED,"Firestore shutting down"))}}function sc(){return new tR(e=>tN(e),tA)}async function sd(e,t){let n=3,r=t.query,s=e.queries.get(r);s?!s.Sa()&&t.ba()&&(n=2):(s=new su,n=+!t.ba());try{switch(n){case 0:s.ya=await e.onListen(r,!0);break;case 1:s.ya=await e.onListen(r,!1);break;case 2:await e.onFirstRemoteStoreListen(r)}}catch(n){let e=si(n,`Initialization of query '${tD(t.query)}' failed`);return void t.onError(e)}e.queries.set(r,s),s.wa.push(t),t.va(e.onlineState),s.ya&&t.Ca(s.ya)&&sp(e)}async function sf(e,t){let n=t.query,r=3,s=e.queries.get(n);if(s){let e=s.wa.indexOf(t);e>=0&&(s.wa.splice(e,1),0===s.wa.length?r=+!t.ba():!s.Sa()&&t.ba()&&(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 sm(e,t){let n=!1;for(let r of t){let t=r.query,s=e.queries.get(t);if(s){for(let e of s.wa)e.Ca(r)&&(n=!0);s.ya=r}}n&&sp(e)}function sg(e,t,n){let r=e.queries.get(t);if(r)for(let e of r.wa)e.onError(n);e.queries.delete(t)}
7function sp(e){e.Da.forEach(e=>{e.next()})}(a=i||(i={})).Fa="default",a.Cache="cache";class sy{constructor(e,t,n){this.query=e,this.Ma=t,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=n||{}}Ca(e){if(!this.options.includeMetadataChanges){let t=[];for(let n of e.docChanges)3!==n.type&&t.push(n);e=new sl(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.xa?this.Na(e)&&(this.Ma.next(e),t=!0):this.Ba(e,this.onlineState)&&(this.La(e),t=!0),this.Oa=e,t}onError(e){this.Ma.error(e)}va(e){this.onlineState=e;let t=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,e)&&(this.La(this.Oa),t=!0),t}Ba(e,t){return!(e.fromCache&&this.ba())||(!this.options.ka||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Na(e){if(e.docChanges.length>0)return!0;let t=this.Oa&&this.Oa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}La(e){e=sl.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.xa=!0,this.Ma.next(e)}ba(){return this.options.source!==i.Cache}}class sv{constructor(e){this.key=e}}class sw{constructor(e){this.key=e}}class s_{constructor(e,t){this.query=e,this.Ha=t,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=tq(),this.mutatedKeys=tq(),this.Xa=tx(e),this.eu=new sa(this.Xa)}get tu(){return this.Ha}nu(e,t){let n=t?t.ru:new so,r=t?t.eu:this.eu,s=t?t.mutatedKeys:this.mutatedKeys,i=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=tk(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.iu(u,h)||(n.track({type:2,doc:h}),f=!0,(o&&this.Xa(h,o)>0||l&&0>this.Xa(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?(i=i.add(h),s=d?s.add(e):s.delete(e)):(i=i.delete(e),s=s.delete(e)))}),null!==this.query.limit)for(;i.size>this.query.limit;){let e="F"===this.query.limitType?i.last():i.first();i=i.delete(e.key),s=s.delete(e.key),n.track({type:1,doc:e})}return{eu:i,ru:n,Ds:a,mutatedKeys:s}}iu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){let s=this.eu;this.eu=e.eu,this.mutatedKeys=e.mutatedKeys;let i=e.ru.pa();i.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 S(20277,{At:e})}};return n(e)-n(t)})(e.type,t.type)||this.Xa(e.doc,t.doc)),this.su(n),r=null!=r&&r;let a=t&&!r?this.ou():[],o=0===this.Za.size&&this.current&&!r?1:0,l=o!==this.Ya;return(this.Ya=o,0!==i.length||l)?{snapshot:new sl(this.query,e.eu,s,i,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),_u:a}:{_u:a}}va(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({eu:this.eu,ru:new so,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(e){return!this.Ha.has(e)&&!!this.eu.has(e)&&!this.eu.get(e).hasLocalMutations}su(e){e&&(e.addedDocuments.forEach(e=>this.Ha=this.Ha.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ha=this.Ha.delete(e)),this.current=e.current)}ou(){if(!this.current)return[];let e=this.Za;this.Za=tq(),this.eu.forEach(e=>{this.au(e.key)&&(this.Za=this.Za.add(e.key))});let t=[];return e.forEach(e=>{this.Za.has(e)||t.push(new sw(e))}
7),this.Za.forEach(n=>{e.has(n)||t.push(new sv(n))}),t}uu(e){this.Ha=e.qs,this.Za=tq();let t=this.nu(e.documents);return this.applyChanges(t,!0)}cu(){return sl.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,0===this.Ya,this.hasCachedResults)}}let sE="SyncEngine";class sT{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class sI{constructor(e){this.key=e,this.lu=!1}}class sS{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.hu={},this.Pu=new tR(e=>tN(e),tA),this.Tu=new Map,this.Iu=new Set,this.du=new ey(H.comparator),this.Eu=new Map,this.Au=new n9,this.Ru={},this.Vu=new Map,this.mu=nX.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return!0===this.fu}}async function sC(e,t,n=!0){let r,s=sK(e),i=s.Pu.get(t);return i?(s.sharedClientState.addLocalQueryTarget(i.targetId),r=i.view.cu()):r=await sA(s,t,n,!0),r}async function sb(e,t){let n=sK(e);await sA(n,t,!0,!1)}async function sA(e,t,n,r){var s,i;let a,o=await (s=e.localStore,i=tS(t),s.persistence.runTransaction("Allocate target","readwrite",e=>{let t;return s.hi.getTargetData(e,i).next(n=>n?(t=n,eh.resolve(t)):s.hi.allocateTargetId(e).next(n=>(t=new nB(i,n,"TargetPurposeListen",e.currentSequenceNumber),s.hi.addTargetData(e,t).next(()=>t))))}).then(e=>{let t=s.Fs.get(e.targetId);return(null===t||e.snapshotVersion.compareTo(t.snapshotVersion)>0)&&(s.Fs=s.Fs.insert(e.targetId,e),s.Ms.set(i,e.targetId)),e})),l=o.targetId,u=e.sharedClientState.addLocalQueryTarget(l,n);return r&&(a=await sN(e,t,l,"current"===u,o.resumeToken)),e.isPrimaryClient&&n&&rj(e.remoteStore,o),a}async function sN(e,t,n,r,s){e.gu=(t,n,r)=>(async function(e,t,n,r){let s=t.view.nu(n);s.Ds&&(s=await rp(e.localStore,t.query,!1).then(({documents:e})=>t.view.nu(e,s)));let i=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),o=t.view.applyChanges(s,e.isPrimaryClient,i,a);return s$(e,t.targetId,o._u),o.snapshot})(e,t,n,r);let i=await rp(e.localStore,t,!0),a=new s_(t,i.qs),o=a.nu(i.documents),l=ng.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,s),u=a.applyChanges(o,e.isPrimaryClient,l);s$(e,n,u._u);let h=new sT(t,n,a);return e.Pu.set(t,h),e.Tu.has(n)?e.Tu.get(n).push(t):e.Tu.set(n,[t]),u.snapshot}async function sD(e,t,n){let r=e.Pu.get(t),s=e.Tu.get(r.targetId);if(s.length>1)return e.Tu.set(r.targetId,s.filter(e=>!tA(e,t))),void e.Pu.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(r.targetId),e.sharedClientState.isActiveQueryTarget(r.targetId)||await rg(e.localStore,r.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(r.targetId),n&&rG(e.remoteStore,r.targetId),sU(e,r.targetId)}).catch(eu)):(sU(e,r.targetId),await rg(e.localStore,r.targetId,!0))}async function sk(e,t){let n=e.Pu.get(t),r=e.Tu.get(n.targetId);e.isPrimaryClient&&1===r.length&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),rG(e.remoteStore,n.targetId))}async function sx(e,t,n){var r,s;let i=((r=e).remoteStore.remoteSyncer.applySuccessfulWrite=sL.bind(null,r),r.remoteStore.remoteSyncer.rejectFailedWrite=sF.bind(null,r),r);try{let e,r=await function(e,t){let n,r,s=es.now(),i=t.reduce((e,t)=>e.add(t.key),tq());return e.persistence.runTransaction("Locally write mutations","readwrite",a=>{let o=tV,l=tq();return e.Os.getEntries(a,i).next(e=>{(o=e).forEach((e,t)=>{t.isValidDocument()||(l=l.add(e))})}).next(()=>e.localDocuments.getOverlayedDocuments(a,o)).next(r=>{n=r;let i=[];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),s=tG(r.transform,e||null);null!=s&&(null===n&&(n=e5.empty()),n.set(r.field,s))}return n||null}(e,n.get(e.key).overlayedDocument);null!=t&&i.push(new t9(e.key,t,function e(t){let n=[];return eg(t.fields,(t,r)=>{let s=new W([t]);if(e2(r)){let t=e(r.mapValue).fields;if(0===t.length)n.push(s);else for(let e of t)n.push(s.child(e))}else n.push(s)}),new eT(n)}(t.value.mapValue),t1.exists(!0)))}return e.mutationQueue.addMutationBatch(a,s,i,t)}).next(t=>{r=t;let s=t.applyToLocalDocumentSet(n,l);return e.documentOverlayCache.saveOverlays(a,t.batchId,s)})}).then(()=>({batchId:r.batchId,changes:tF(n)}))}(i.localStore,t);
7i.sharedClientState.addPendingMutation(r.batchId),s=r.batchId,(e=i.Ru[i.currentUser.toKey()])||(e=new ey(q)),e=e.insert(s,n),i.Ru[i.currentUser.toKey()]=e,await sB(i,r.changes),await r3(i.remoteStore)}catch(t){let e=si(t,"Failed to persist write");n.reject(e)}}async function sR(e,t){try{let n=await function(e,t){let n=t.snapshotVersion,r=e.Fs;return e.persistence.runTransaction("Apply remote event","readwrite-primary",s=>{var i,a,o;let l,u,h=e.Os.newChangeBuffer({trackRemovals:!0});r=e.Fs;let c=[];t.targetChanges.forEach((i,a)=>{var o;let l=r.get(a);if(!l)return;c.push(e.hi.removeMatchingKeys(s,i.removedDocuments,a).next(()=>e.hi.addMatchingKeys(s,i.addedDocuments,a)));let u=l.withSequenceNumber(s.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(eS.EMPTY_BYTE_STRING,ei.min()).withLastLimboFreeSnapshotVersion(ei.min()):i.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(i.resumeToken,n)),r=r.insert(a,u),o=u,(0===l.resumeToken.approximateByteSize()||o.snapshotVersion.toMicroseconds()-l.snapshotVersion.toMicroseconds()>=3e8||i.addedDocuments.size+i.modifiedDocuments.size+i.removedDocuments.size>0)&&c.push(e.hi.updateTargetData(s,u))});let d=tV,f=tq();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&c.push(e.persistence.referenceDelegate.updateLimboDocument(s,n))}),c.push((i=s,a=h,o=t.documentUpdates,l=tq(),u=tq(),o.forEach(e=>l=l.add(e)),a.getEntries(i,l).next(e=>{let t=tV;return o.forEach((n,r)=>{let s=e.get(n);r.isFoundDocument()!==s.isFoundDocument()&&(u=u.add(n)),r.isNoDocument()&&r.version.isEqual(ei.min())?(a.removeEntry(n,r.readTime),t=t.insert(n,r)):!s.isValidDocument()||r.version.compareTo(s.version)>0||0===r.version.compareTo(s.version)&&s.hasPendingWrites?(a.addEntry(r),t=t.insert(n,r)):_(rc,"Ignoring outdated watch update for ",n,". Current version:",s.version," Watch version:",r.version)}),{Ls:t,ks:u}})).next(e=>{d=e.Ls,f=e.ks})),!n.isEqual(ei.min())){let t=e.hi.getLastRemoteSnapshotVersion(s).next(t=>e.hi.setTargetsMetadata(s,s.currentSequenceNumber,n));c.push(t)}return eh.waitFor(c).next(()=>h.apply(s)).next(()=>e.localDocuments.getLocalViewOfDocuments(s,d,f)).next(()=>d)}).then(t=>(e.Fs=r,t))}(e.localStore,t);
7t.targetChanges.forEach((t,n)=>{let r=e.Eu.get(n);r&&(b(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?r.lu=!0:t.modifiedDocuments.size>0?b(r.lu,14607):t.removedDocuments.size>0&&(b(r.lu,42227),r.lu=!1))}),await sB(e,n,t)}catch(e){await eu(e)}}function sV(e,t,n){var r;if(e.isPrimaryClient&&0===n||!e.isPrimaryClient&&1===n){let n,s=[];e.Pu.forEach((e,n)=>{let r=n.view.va(t);r.snapshot&&s.push(r.snapshot)}),(r=e.eventManager).onlineState=t,n=!1,r.queries.forEach((e,r)=>{for(let e of r.wa)e.va(t)&&(n=!0)}),n&&sp(r),s.length&&e.hu.J_(s),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function sO(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Eu.get(t),s=r&&r.key;if(s){let n=new ey(H.comparator);n=n.insert(s,e8.newNoDocument(s,ei.min()));let r=tq().add(s),i=new nm(ei.min(),new Map,new ey(q),n,r);await sR(e,i),e.du=e.du.remove(s),e.Eu.delete(t),sz(e)}else await rg(e.localStore,t,!1).then(()=>sU(e,t,n)).catch(eu)}async function sL(e,t){var n;let r=t.batch.batchId;try{let s=await (n=e.localStore,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),s=n.Os.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let s=n.batch,i=s.keys(),a=eh.resolve();return i.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let i=n.docVersions.get(e);b(null!==i,48541),0>t.version.compareTo(i)&&(s.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))})(n,e,t,s).next(()=>s.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=tq();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))}));sM(e,r,null),sP(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await sB(e,s)}catch(e){await eu(e)}}async function sF(e,t,n){var r;try{let s=await (r=e.localStore,r.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(b(null!==t,37113),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))}));sM(e,t,n),sP(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await sB(e,s)}catch(e){await eu(e)}}function sP(e,t){(e.Vu.get(t)||[]).forEach(e=>{e.resolve()}),e.Vu.delete(t)}function sM(e,t,n){let r=e.Ru[e.currentUser.toKey()];if(r){let s=r.get(t);s&&(n?s.reject(n):s.resolve(),r=r.remove(t)),e.Ru[e.currentUser.toKey()]=r}}function sU(e,t,n=null){for(let r of(e.sharedClientState.removeLocalQueryTarget(t),e.Tu.get(t)))e.Pu.delete(r),n&&e.hu.pu(r,n);e.Tu.delete(t),e.isPrimaryClient&&e.Au.zr(t).forEach(t=>{e.Au.containsKey(t)||sq(e,t)})}function sq(e,t){e.Iu.delete(t.path.canonicalString());let n=e.du.get(t);null!==n&&(rG(e.remoteStore,n),e.du=e.du.remove(t),e.Eu.delete(n),sz(e))}function s$(e,t,n){for(let r of n)r instanceof sv?(e.Au.addReference(r.key,t),function(e,t){let n=t.key,r=n.path.canonicalString();e.du.get(n)||e.Iu.has(r)||(_(sE,"New document in limbo: "+n),e.Iu.add(r),sz(e))}(e,r)):r instanceof sw?(_(sE,"Document no longer in limbo: "+r.key),e.Au.removeReference(r.key,t),e.Au.containsKey(r.key)||sq(e,r.key)):S(19791,{yu:r})}function sz(e){for(;e.Iu.size>0&&e.du.size<e.maxConcurrentLimboResolutions;){let t=e.Iu.values().next().value;e.Iu.delete(t);let n=new H(K.fromString(t)),r=e.mu.next();e.Eu.set(r,new sI(n)),e.du=e.du.insert(n,r),rj(e.remoteStore,new nB(tS(new t_(n.path)),r,"TargetPurposeLimboResolution",ed.ue))}}async function sB(e,t,n){let r=[],s=[],i=[];e.Pu.isEmpty()||(e.Pu.forEach((a,o)=>{i.push(e.gu(o,t,n).then(t=>{var i;if((t||n)&&e.isPrimaryClient){let r=t?!t.fromCache:null==(i=null==n?void 0:n.targetChanges.get(o.targetId))?void 0:i.current;
7e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=rl.Es(o.targetId,t);s.push(e)}}))}),await Promise.all(i),e.hu.J_(r),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>eh.forEach(t,t=>eh.forEach(t.Is,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>eh.forEach(t.ds,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!ec(e))throw e;_(rc,"Failed to update sequence numbers: "+e)}for(let n of t){let t=n.targetId;if(!n.fromCache){let n=e.Fs.get(t),r=n.snapshotVersion,s=n.withLastLimboFreeSnapshotVersion(r);e.Fs=e.Fs.insert(t,s)}}}(e.localStore,s))}async function sj(e,t){if(!e.currentUser.isEqual(t)){_(sE,"User change. New user:",t.toKey());let n=await rf(e.localStore,t);e.currentUser=t,e.Vu.forEach(e=>{e.forEach(e=>{e.reject(new N(A.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Vu.clear(),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await sB(e,n.Bs)}}function sG(e,t){let n=e.Eu.get(t);if(n&&n.lu)return tq().add(n.key);{let n=tq(),r=e.Tu.get(t);if(!r)return n;for(let t of r){let r=e.Pu.get(t);n=n.unionWith(r.view.tu)}return n}}function sK(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=sR.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=sG.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=sO.bind(null,e),e.hu.J_=sm.bind(null,e.eventManager),e.hu.pu=sg.bind(null,e.eventManager),e}class sQ{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=rx(e.databaseInfo.databaseId),this.sharedClientState=this.bu(e),this.persistence=this.Du(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Cu(e,this.localStore),this.indexBackfillerScheduler=this.Fu(e,this.localStore)}Cu(e,t){return null}Fu(e,t){return null}vu(e){var t,n;return t=this.persistence,n=new rh,new rd(t,n,e.initialUser,this.serializer)}Du(e){return new rs(ra.Vi,this.serializer)}bu(e){return new rv}async terminate(){var e,t;null==(e=this.gcScheduler)||e.stop(),null==(t=this.indexBackfillerScheduler)||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}sQ.provider={build:()=>new sQ};class sW extends sQ{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,t){return b(this.persistence.referenceDelegate instanceof ro,46915),new n0(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Du(e){let t=void 0!==this.cacheSizeBytes?nH.withCacheSize(this.cacheSizeBytes):nH.DEFAULT;return new rs(e=>ro.Vi(e,t),this.serializer)}}class sH{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=>sV(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=sj.bind(null,this.syncEngine),await st(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new sh}createDatastore(e){var t;let n=rx(e.databaseInfo.databaseId),r=new rD(e.databaseInfo);return t=e.authCredentials,new rM(t,e.appCheckCredentials,r,n)}createRemoteStore(e){var t,n;return t=this.localStore,n=this.datastore,new r$(t,n,e.asyncQueue,e=>sV(this.syncEngine,e,0),rE.C()?new rE:new rw)}createSyncEngine(e,t){return function(e,t,n,r,s,i,a){let o=new sS(e,t,n,r,s,i);return a&&(o.fu=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){_(rq,"RemoteStore shutting down."),e.Ia.add(5),await rB(e),e.Ea.shutdown(),e.Aa.set("Unknown")}(this.remoteStore),null==(e=this.datastore)||e.terminate(),null==(t=this.eventManager)||t.terminate()}}sH.provider={build:()=>new sH};class sX{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.xu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.xu(this.observer.error,e):E("Uncaught Error in snapshot listener:",e.toString()))}Ou(){this.muted=!0}
7xu(e,t){setTimeout(()=>{this.muted||e(t)},0)}}let sY="FirestoreClient";class sJ{constructor(e,t,n,r,s){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=p.UNAUTHENTICATED,this.clientId=U.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=s,this.authCredentials.start(n,async e=>{_(sY,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(_(sY,"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=si(n,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function sZ(e,t){e.asyncQueue.verifyOperationInProgress(),_(sY,"Initializing OfflineComponentProvider");let n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await rf(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>{T("Terminating Firestore due to IndexedDb database deletion"),e.terminate().then(()=>{_("Terminating Firestore due to IndexedDb database deletion completed successfully")}).catch(e=>{T("Terminating Firestore due to IndexedDb database deletion failed",e)})}),e._offlineComponents=t}async function s0(e,t){e.asyncQueue.verifyOperationInProgress();let n=await s1(e);_(sY,"Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>se(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>se(t.remoteStore,n)),e._onlineComponents=t}async function s1(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){_(sY,"Using user provided OfflineComponentProvider");try{await sZ(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===A.FAILED_PRECONDITION||t.code===A.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 sZ(e,new sQ)}}else _(sY,"Using default OfflineComponentProvider"),await sZ(e,new sW(void 0));return e._offlineComponents}async function s2(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(_(sY,"Using user provided OnlineComponentProvider"),await s0(e,e._uninitializedComponentsProvider._online)):(_(sY,"Using default OnlineComponentProvider"),await s0(e,new sH))),e._onlineComponents}async function s3(e){let t=await s2(e),n=t.eventManager;return n.onListen=sC.bind(null,t.syncEngine),n.onUnlisten=sD.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=sb.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=sk.bind(null,t.syncEngine),n}function s4(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let s6=new Map,s5="firestore.googleapis.com";class s8{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new N(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=s5,this.ssl=!0}else this.host=e.host,this.ssl=null==(t=e.ssl)||t;if(this.isUsingEmulator=void 0!==e.emulatorOptions,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 N(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new N(A.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=s4(null!=(n=e.experimentalLongPollingOptions)?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new N(A.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 s9{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 s8({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new N(A.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 N(A.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 s8(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new x;switch(e.type){case"firstParty":return new L(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new N(A.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
7d credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_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=s6.get(e);t&&(_("ComponentProvider","Removing Datastore"),s6.delete(e),t.terminate())}(this),Promise.resolve()}}class s7{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new s7(this.firestore,e,this._query)}}class ie{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 it(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new ie(this.firestore,e,this._key)}toJSON(){return{type:ie._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,n){if(er(t,ie._jsonSchema))return new ie(e,n||null,new H(K.fromString(t.referencePath)))}}ie._jsonSchemaVersion="firestore/documentReference/1.0",ie._jsonSchema={type:en("string",ie._jsonSchemaVersion),referencePath:en("string")};class it extends s7{constructor(e,t,n){super(e,t,new t_(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 ie(this.firestore,null,new H(e))}withConverter(e){return new it(this.firestore,e,this._path)}}function ir(e,t,...n){if(e=(0,h.Ku)(e),X("collection","path",t),e instanceof s9){let r=K.fromString(t,...n);return J(r),new it(e,null,r)}{if(!(e instanceof ie||e instanceof it))throw new N(A.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 J(r),new it(e.firestore,null,r)}}function is(e,t,...n){if(e=(0,h.Ku)(e),1==arguments.length&&(t=U.newId()),X("doc","path",t),e instanceof s9){let r=K.fromString(t,...n);return Y(r),new ie(e,null,new H(r))}{if(!(e instanceof ie||e instanceof it))throw new N(A.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 Y(r),new ie(e.firestore,e instanceof it?e.converter:null,new H(r))}}let ii="AsyncQueue";class ia{constructor(e=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new rR(this,"async_queue_retry"),this.oc=()=>{let e=rk();e&&_(ii,"Visibility state changed to "+e.visibilityState),this.F_.y_()},this._c=e;let t=rk();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ac(),this.uc(e)}enterRestrictedMode(e){if(!this.Xu){this.Xu=!0,this.rc=e||!1;let t=rk();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise(()=>{});let t=new D;return this.uc(()=>this.Xu&&this.rc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Zu.push(e),this.cc()))}async cc(){if(0!==this.Zu.length){try{await this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(e){if(!ec(e))throw e;_(ii,"Operation failed with retryable error: "+e)}this.Zu.length>0&&this.F_.g_(()=>this.cc())}}uc(e){let t=this._c.then(()=>(this.nc=!0,e().catch(e=>{throw this.tc=e,this.nc=!1,E("INTERNAL UNHANDLED ERROR: ",io(e)),e}).then(e=>(this.nc=!1,e))));return this._c=t,t}enqueueAfterDelay(e,t,n){this.ac(),this.sc.indexOf(e)>-1&&(t=0);let r=ss.createAndSchedule(this,e,t,n,e=>this.lc(e));return this.ec.push(r),r}ac(){this.tc&&S(47125,{hc:io(this.tc)})}verifyOperationInProgress(){}async Pc(){let e;do e=this._c,await e;while(e!==this._c)}Tc(e){for(let t of this.ec)if(t.timerId===e)return!0;return!1}Ic(e){return this.Pc().then(()=>{for(let t of(this.ec.sort((e,t)=>
7e.targetTimeMs-t.targetTimeMs),this.ec))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Pc()})}dc(e){this.sc.push(e)}lc(e){let t=this.ec.indexOf(e);this.ec.splice(t,1)}}function io(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}class il extends s9{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ia,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new ia(e),this._firestoreClient=void 0,await e}}}function iu(e,t){let n="object"==typeof e?e:(0,o.Sx)(),r=(0,o.j6)(n,"firestore").getImmediate({identifier:"string"==typeof e?e:t||eP});if(!r._initialized){let e=(0,h.yU)("firestore");e&&function(e,t,n,r={}){var s;e=et(e,s9);let i=(0,h.zJ)(t),a=e._getSettings(),o=Object.assign(Object.assign({},a),{emulatorOptions:e._getEmulatorOptions()}),l=`${t}:${n}`;i&&((0,h.gE)(`https://${l}`),(0,h.P1)("Firestore",!0)),a.host!==s5&&a.host!==l&&T("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let u=Object.assign(Object.assign({},a),{host:l,ssl:i,emulatorOptions:r});if(!(0,h.bD)(u,o)&&(e._setSettings(u),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==(s=e._app)?void 0:s.options.projectId);let i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new N(A.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new p(i)}
7e._authCredentials=new R(new k(t,n))}}(r,...e)}return r}function ih(e){if(e._terminated)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||function(e){var t,n,r,s,i;let a=e._freezeSettings(),o=(s=e._databaseId,i=(null==(t=e._app)?void 0:t.options.appId)||"",new eF(s,i,e._persistenceKey,a.host,a.ssl,a.experimentalForceLongPolling,a.experimentalAutoDetectLongPolling,s4(a.experimentalLongPollingOptions),a.useFetchStreams,a.isUsingEmulator));e._componentsProvider||(null==(n=a.localCache)?void 0:n._offlineComponentProvider)&&(null==(r=a.localCache)?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider}),e._firestoreClient=new sJ(e._authCredentials,e._appCheckCredentials,e._queue,o,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 ic{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ic(eS.fromBase64String(e))}catch(e){throw new N(A.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new ic(eS.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)}toJSON(){return{type:ic._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(er(e,ic._jsonSchema))return ic.fromBase64String(e.bytes)}}ic._jsonSchemaVersion="firestore/bytes/1.0",ic._jsonSchema={type:en("string",ic._jsonSchemaVersion),bytes:en("string")};class id{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new N(A.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new W(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class im{constructor(e){this._methodName=e}}class ig{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new N(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new N(A.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}_compareTo(e){return q(this._lat,e._lat)||q(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:ig._jsonSchemaVersion}}static fromJSON(e){if(er(e,ig._jsonSchema))return new ig(e.latitude,e.longitude)}}ig._jsonSchemaVersion="firestore/geoPoint/1.0",ig._jsonSchema={type:en("string",ig._jsonSchemaVersion),latitude:en("number"),longitude:en("number")};class ip{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)}toJSON(){return{type:ip._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(er(e,ip._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new ip(e.vectorValues);throw new N(A.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}ip._jsonSchemaVersion="firestore/vectorValue/1.0",ip._jsonSchema={type:en("string",ip._jsonSchemaVersion),vectorValues:en("object")};let iy=/^__.*__$/;class iv{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new t9(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function iw(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw S(40011,{Ec:e})}}class i_{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===s&&this.Ac(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new i_(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var t;let n=null==(t=this.path)?void 0:t.child(e),r=this.Rc({path:n,mc:!1});return r.fc(e),r}gc(e){var t;let n=null==(t=this.path)?void 0:t.child(e),r=this.Rc({path:n,mc:!1});return r.Ac(),r}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return ik(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(0===e.length)throw this.wc("Document fields must not be empty");if(iw(this.Ec)&&iy.test(e))throw this.wc('Document fields cannot begin and end with "__"')}}class iE{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer
7=n||rx(e)}Dc(e,t,n,r=!1){return new i_({Ec:e,methodName:t,bc:n,path:W.emptyPath(),mc:!1,Sc:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function iT(e){let t=e._freezeSettings(),n=rx(e._databaseId);return new iE(e._databaseId,!!t.ignoreUndefinedProperties,n)}class iI extends im{_toFieldTransform(e){if(2!==e.Ec)throw 1===e.Ec?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof iI}}function iS(e,t){if(iC(e=(0,h.Ku)(e)))return ib("Unsupported field value:",t,e),function(e,t){let n={};return ep(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):eg(e,(e,r)=>{let s=iS(r,t.Vc(e));null!=s&&(n[e]=s)}),{mapValue:{fields:n}}}(e,t);if(e instanceof im)return function(e,t){if(!iw(t.Ec))throw t.wc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.wc(`${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.mc&&4!==t.Ec)throw t.wc("Nested arrays are not supported");let n=[],r=0;for(let s of e){let e=iS(s,t.yc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}return function(e,t){var n,r,s;if(null===(e=(0,h.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return n=t.serializer,"number"==typeof(s=r=e)&&Number.isInteger(s)&&!ef(s)&&s<=Number.MAX_SAFE_INTEGER&&s>=Number.MIN_SAFE_INTEGER?tB(r):tz(n,r);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let n=es.fromDate(e);return{timestampValue:nN(t.serializer,n)}}if(e instanceof es){let n=new es(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:nN(t.serializer,n)}}if(e instanceof ig)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof ic)return{bytesValue:nD(t.serializer,e._byteString)};if(e instanceof ie){let n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.wc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:nx(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof ip)return{mapValue:{fields:{[eU]:{stringValue:ez},[eB]:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw t.wc("VectorValues must only contain numeric values.");return tz(t.serializer,e)})}}}}};throw t.wc(`Unsupported field value: ${ee(e)}`)}(e,t)}function iC(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof es||e instanceof ig||e instanceof ic||e instanceof ie||e instanceof im||e instanceof ip)}function ib(e,t,n){if(!iC(n)||!Z(n)){let r=ee(n);throw"an object"===r?t.wc(e+" a custom object"):t.wc(e+" "+r)}}function iA(e,t,n){if((t=(0,h.Ku)(t))instanceof id)return t._internalPath;if("string"==typeof t)return iD(e,t);throw ik("Field path arguments must be of type string or ",e,!1,void 0,n)}let iN=RegExp("[~\\*/\\[\\]]");function iD(e,t,n){if(t.search(iN)>=0)throw ik(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new id(...t.split("."))._internalPath}catch(r){throw ik(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function ik(e,t,n,r,s){let i=r&&!r.isEmpty(),a=void 0!==s,o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(i||a)&&(l+=" (found",i&&(l+=` in field ${r}`),a&&(l+=` in document ${s}`),l+=")"),new N(A.INVALID_ARGUMENT,o+e+l)}class ix{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new ie(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new iR(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(iV("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class iR extends ix{data(){return super.data()}}function iV(e,t){return"string"==typeof t?iD(e,t):t instanceof id?t._internalPath:t._delegate._internalPath}class iO{}class iL extends iO{}function iF(e,t,...n){let r=[];for(let s of(t instanceof iO&&r.push(t),function(e){let t=e.filter(e=>e instanceof iU).length,n=e.filter(e=>e instanceof iP).length;if(t>1||t>0&&n>0)throw new N(A.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=s._apply(e);return e}class iP extends iL{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new iP(e,t,n)}_apply(e){let t=this._parse(e);return ij(e._query,t),new s7(e.firestore,e.converter,tC(e._query,t))}_parse(e){let t=iT(e.firestore);return function(e,t,n,r,s,i,a){let o;
7if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new N(A.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){iB(a,i);let t=[];for(let n of a)t.push(iz(r,e,n));o={arrayValue:{values:t}}}else o=iz(r,e,a)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||iB(a,i),o=function(e,t,n,r=!1){return iS(n,e.Dc(r?4:3,t))}(n,t,a,"in"===i||"not-in"===i);return tr.create(s,i,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function iM(e,t,n){let r=iV("where",e);return iP._create(r,t,n)}class iU extends iO{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new iU(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]:ts.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())ij(n,e),n=tC(n,e)}(e._query,t),new s7(e.firestore,e.converter,tC(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class iq extends iL{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new iq(e,t,n)}_apply(e){return new s7(e.firestore,e.converter,tb(e._query,this._limit,this._limitType))}}function i$(e){return function(e,t){if(t<=0)throw new N(A.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}("limit",e),iq._create("limit",e,"F")}function iz(e,t,n){if("string"==typeof(n=(0,h.Ku)(n))){if(""===n)throw new N(A.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!tT(t)&&-1!==n.indexOf("/"))throw new N(A.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(!H.isDocumentKey(r))throw new N(A.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 eY(e,new H(r))}if(n instanceof ie)return eY(e,n._key);throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${ee(n)}.`)}function iB(e,t){if(!Array.isArray(e)||0===e.length)throw new N(A.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function ij(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 N(A.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class iG{convertValue(e,t="none"){switch(ej(e)){case 0:return null;case 1:return e.booleanValue;case 2:return eA(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(eN(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 S(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return eg(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertVectorValue(e){var t,n,r;return new ip(null==(r=null==(n=null==(t=e.fields)?void 0:t[eB].arrayValue)?void 0:n.values)?void 0:r.map(e=>eA(e.doubleValue)))}convertGeoPoint(e){return new ig(eA(e.latitude),eA(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=eO(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(eL(e));default:return null}}convertTimestamp(e){let t=eb(e);return new es(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=K.fromString(e);b(nz(n),9688,{name:e});let r=new eM(n.get(1),n.get(3)),s=new H(n.popFirst(5));return r.isEqual(t)||E(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}class iK{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class iQ extends ix{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new iW(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(iV("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new N(A.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,t={};return t.type=iQ._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),e&&e.isValidDocument()&&e.isFoundDocument()&&
7(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),this._firestore,this.ref.path,t.bundle="NOT SUPPORTED"),t}}iQ._jsonSchemaVersion="firestore/documentSnapshot/1.0",iQ._jsonSchema={type:en("string",iQ._jsonSchemaVersion),bundleSource:en("string","DocumentSnapshot"),bundleName:en("string"),bundle:en("string")};class iW extends iQ{data(e={}){return super.data(e)}}class iH{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new iK(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 iW(this._firestore,this._userDataWriter,n.key,n,new iK(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 N(A.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 iW(e._firestore,e._userDataWriter,n.doc.key,n.doc,new iK(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 iW(e._firestore,e._userDataWriter,t.doc.key,t.doc,new iK(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),s=-1,i=-1;return 0!==t.type&&(s=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(i=(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 S(61501,{type:e})}}(t.type),doc:r,oldIndex:s,newIndex:i}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new N(A.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=iH._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=U.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let t=[],n=[],r=[];return this.docs.forEach(e=>{null!==e._document&&(t.push(e._document),n.push(this._userDataWriter.convertObjectMap(e._document.data.value.mapValue.fields,"previous")),r.push(e.ref.path))}),this._firestore,this.query._query,e.bundleName,e.bundle="NOT SUPPORTED",e}}function iX(e){e=et(e,ie);let t=et(e.firestore,il);return(function(e,t,n={}){let r=new D;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,s){let i=new sX({next:o=>{i.Ou(),t.enqueueAndForget(()=>sf(e,a));let l=o.docs.has(n);!l&&o.fromCache?s.reject(new N(A.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&o.fromCache&&r&&"server"===r.source?s.reject(new N(A.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.)')):s.resolve(o)},error:e=>s.reject(e)}),a=new sy(new t_(n.path),i,{includeMetadataChanges:!0,ka:!0});return sd(e,a)})(await s3(e),e.asyncQueue,t,n,r)),r.promise})(ih(t),e._key).then(n=>(function(e,t,n){let r=n.docs.get(t._key),s=new iY(e);return new iQ(e,s,t._key,r,new iK(n.hasPendingWrites,n.fromCache),t.converter)})(t,e,n))}iH._jsonSchemaVersion="firestore/querySnapshot/1.0",iH._jsonSchema={type:en("string",iH._jsonSchemaVersion),bundleSource:en("string","QuerySnapshot"),bundleName:en("string"),bundle:en("string")};class iY extends iG{constructor(e){super(),this.firestore=e}convertBytes(e){return new ic(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);
7return new ie(this.firestore,null,t)}}function iJ(e){e=et(e,s7);let t=et(e.firestore,il),n=ih(t),r=new iY(t);return function(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new N(A.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query),(function(e,t,n={}){let r=new D;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,s){let i=new sX({next:n=>{i.Ou(),t.enqueueAndForget(()=>sf(e,a)),n.fromCache&&"server"===r.source?s.reject(new N(A.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):s.resolve(n)},error:e=>s.reject(e)}),a=new sy(n,i,{includeMetadataChanges:!0,ka:!0});return sd(e,a)})(await s3(e),e.asyncQueue,t,n,r)),r.promise})(n,e._query).then(n=>new iH(t,r,e,n))}function iZ(e,t,n,...r){e=et(e,ie);let s=et(e.firestore,il),i=iT(s);var a=s,o=[("string"==typeof(t=(0,h.Ku)(t))||t instanceof id?function(e,t,n,r,s,i){let a=e.Dc(1,t,n),o=[iA(t,r,n)],l=[s];if(i.length%2!=0)throw new N(A.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<i.length;e+=2)o.push(iA(t,i[e])),l.push(i[e+1]);let u=[],c=e5.empty();for(let e=o.length-1;e>=0;--e)if(!function(e,t){return e.some(e=>e.isEqual(t))}(u,o[e])){let t=o[e],n=l[e];n=(0,h.Ku)(n);let r=a.gc(t);if(n instanceof iI)u.push(t);else{let e=iS(n,r);null!=e&&(u.push(t),c.set(t,e))}}return new iv(c,new eT(u),a.fieldTransforms)}(i,"updateDoc",e._key,t,n,r):function(e,t,n,r){let s=e.Dc(1,t,n);ib("Data must be an object, but it was:",s,r);let i=[],a=e5.empty();return eg(r,(e,r)=>{let o=iD(t,e,n);r=(0,h.Ku)(r);let l=s.gc(o);if(r instanceof iI)i.push(o);else{let e=iS(r,l);null!=e&&(i.push(o),a.set(o,e))}}),new iv(a,new eT(i),s.fieldTransforms)}(i,"updateDoc",e._key,t)).toMutation(e._key,t1.exists(!0))],l=ih(a);let u=new D;return l.asyncQueue.enqueueAndForget(async()=>sx(await s2(l).then(e=>e.syncEngine),o,u)),u.promise}new WeakMap,function(e=!0){y=o.MF,(0,o.om)(new l.uA("firestore",(t,{instanceIdentifier:n,options:r})=>{let s=t.getProvider("app").getImmediate(),i=new il(new V(t.getProvider("auth-internal")),new P(s,t.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new N(A.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new eM(e.options.projectId,t)}(s,n),s);return r=Object.assign({useFetchStreams:e},r),i._setSettings(r),i},"PUBLIC").setMultipleInstances(!0)),(0,o.KO)(m,g,void 0),(0,o.KO)(m,g,"esm2017")}()}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.