-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7112840a-78f439a90988a15ff477.js
3 lines (3 loc) · 160 KB
/
7112840a-78f439a90988a15ff477.js
1
2
3
/*! For license information please see 7112840a-78f439a90988a15ff477.js.LICENSE.txt */
"use strict";(self.webpackChunkkotomusubi=self.webpackChunkkotomusubi||[]).push([[16],{19:function(e,t,n){n.d(t,{ET:function(){return Ho},PL:function(){return jo},ad:function(){return ho},hJ:function(){return uo}});var s=n(389),r=n(8463),i=n(3333),o=n(4444),a=n(6640);const u="@firebase/firestore";class c{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}}c.UNAUTHENTICATED=new c(null),c.GOOGLE_CREDENTIALS=new c("google-credentials-uid"),c.FIRST_PARTY=new c("first-party-uid"),c.MOCK_USER=new c("mock-user");let l="10.7.0";const h=new i.Yd("@firebase/firestore");function d(){return h.logLevel}function f(e,...t){if(h.logLevel<=i.in.DEBUG){const n=t.map(p);h.debug(`Firestore (${l}): ${e}`,...n)}}function m(e,...t){if(h.logLevel<=i.in.ERROR){const n=t.map(p);h.error(`Firestore (${l}): ${e}`,...n)}}function g(e,...t){if(h.logLevel<=i.in.WARN){const n=t.map(p);h.warn(`Firestore (${l}): ${e}`,...n)}}function p(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function y(e="Unexpected state"){const t=`FIRESTORE (${l}) INTERNAL ASSERTION FAILED: `+e;throw m(t),new Error(t)}function w(e,t){e||y()}function v(e,t){return e}const E={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 _ extends o.ZR{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class T{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class I{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class C{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(c.UNAUTHENTICATED)))}shutdown(){}}class S{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable((()=>t(this.token.user)))}shutdown(){this.changeListener=null}}class A{constructor(e){this.t=e,this.currentUser=c.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const s=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let r=new T;this.o=()=>{this.i++,this.currentUser=this.u(),r.resolve(),r=new T,e.enqueueRetryable((()=>s(this.currentUser)))};const i=()=>{const t=r;e.enqueueRetryable((async()=>{await t.promise,await s(this.currentUser)}))},o=e=>{f("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),i()};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(f("FirebaseAuthCredentialsProvider","Auth not yet detected"),r.resolve(),r=new T)}}),0),i()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(f("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new I(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return w(null===e||"string"==typeof e),new c(e)}}class N{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=c.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);const e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class b{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new N(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable((()=>t(c.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class k{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 D{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){const n=e=>{null!=e.error&&f("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.R;return this.R=e.token,f("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const s=e=>{f("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>s(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?s(e):f("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(w("string"==typeof e.token),this.R=e.token,new k(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}function R(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let s=0;s<e;s++)n[s]=Math.floor(256*Math.random());return n}class x{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(256/62);let n="";for(;n.length<20;){const s=R(40);for(let r=0;r<s.length;++r)n.length<20&&s[r]<t&&(n+=e.charAt(s[r]%62))}return n}}function L(e,t){return e<t?-1:e>t?1:0}function M(e,t,n){return e.length===t.length&&e.every(((e,s)=>n(e,t[s])))}class V{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new _(E.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new _(E.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new _(E.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new _(E.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return V.fromMillis(Date.now())}static fromDate(e){return V.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new V(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?L(this.nanoseconds,e.nanoseconds):L(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class O{constructor(e){this.timestamp=e}static fromTimestamp(e){return new O(e)}static min(){return new O(new V(0,0))}static max(){return new O(new V(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class F{constructor(e,t,n){void 0===t?t=0:t>e.length&&y(),void 0===n?n=e.length-t:n>e.length-t&&y(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===F.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof F?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){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++){const n=e.get(s),r=t.get(s);if(n<r)return-1;if(n>r)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class P extends F{construct(e,t,n){return new P(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new _(E.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new P(t)}static emptyPath(){return new P([])}}const U=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class q extends F{construct(e,t,n){return new q(e,t,n)}static isValidIdentifier(e){return U.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),q.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new q(["__name__"])}static fromServerFormat(e){const t=[];let n="",s=0;const r=()=>{if(0===n.length)throw new _(E.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;s<e.length;){const t=e[s];if("\\"===t){if(s+1===e.length)throw new _(E.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[s+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new _(E.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,s+=2}else"`"===t?(i=!i,s++):"."!==t||i?(n+=t,s++):(r(),s++)}if(r(),i)throw new _(E.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new q(t)}static emptyPath(){return new q([])}}class B{constructor(e){this.path=e}static fromPath(e){return new B(P.fromString(e))}static fromName(e){return new B(P.fromString(e).popFirst(5))}static empty(){return new B(P.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===P.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return P.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new B(new P(e.slice()))}}class z{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}}z.UNKNOWN_ID=-1;function $(e,t){const n=e.toTimestamp().seconds,s=e.toTimestamp().nanoseconds+1,r=O.fromTimestamp(1e9===s?new V(n+1,0):new V(n,s));return new G(r,B.empty(),t)}function K(e){return new G(e.readTime,e.key,-1)}class G{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new G(O.min(),B.empty(),-1)}static max(){return new G(O.max(),B.empty(),-1)}}function Q(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=B.comparator(e.documentKey,t.documentKey),0!==n?n:L(e.largestBatchId,t.largestBatchId))}const j="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class H{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function W(e){if(e.code!==E.FAILED_PRECONDITION||e.message!==j)throw e;f("LocalStore","Unexpectedly lost primary lease")}class Y{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&&y(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new Y(((n,s)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,s)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,s)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof Y?t:Y.resolve(t)}catch(e){return Y.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):Y.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):Y.reject(t)}static resolve(e){return new Y(((t,n)=>{t(e)}))}static reject(e){return new Y(((t,n)=>{n(e)}))}static waitFor(e){return new Y(((t,n)=>{let s=0,r=0,i=!1;e.forEach((e=>{++s,e.next((()=>{++r,i&&r===s&&t()}),(e=>n(e)))})),i=!0,r===s&&t()}))}static or(e){let t=Y.resolve(!1);for(const n of e)t=t.next((e=>e?Y.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,s)=>{n.push(t.call(this,e,s))})),this.waitFor(n)}static mapArray(e,t){return new Y(((n,s)=>{const r=e.length,i=new Array(r);let o=0;for(let a=0;a<r;a++){const u=a;t(e[u]).next((e=>{i[u]=e,++o,o===r&&n(i)}),(e=>s(e)))}}))}static doWhile(e,t){return new Y(((n,s)=>{const r=()=>{!0===e()?t().next((()=>{r()}),s):n()};r()}))}}function X(e){return"IndexedDbTransactionError"===e.name}class J{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.se(e),this.oe=e=>t.writeSequenceNumber(e))}se(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.oe&&this.oe(e),e}}function Z(e){return null==e}function ee(e){return 0===e&&1/e==-1/0}function te(e){return"number"==typeof e&&Number.isInteger(e)&&!ee(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}J._e=-1;const ne=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],se=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],re=se;function ie(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function oe(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ae(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ue{constructor(e,t){this.comparator=e,this.root=t||le.EMPTY}insert(e,t){return new ue(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,le.BLACK,null,null))}remove(e){return new ue(this.comparator,this.root.remove(e,this.comparator).copy(null,null,le.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const 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();){const s=this.comparator(e,n.key);if(0===s)return t+n.left.size;s<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(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new ce(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ce(this.root,e,this.comparator,!1)}getReverseIterator(){return new ce(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ce(this.root,e,this.comparator,!0)}}class ce{constructor(e,t,n,s){this.isReverse=s,this.nodeStack=[];let r=1;for(;!e.isEmpty();)if(r=t?n(e.key,t):1,t&&s&&(r*=-1),r<0)e=this.isReverse?e.left:e.right;else{if(0===r){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const 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;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class le{constructor(e,t,n,s,r){this.key=e,this.value=t,this.color=null!=n?n:le.RED,this.left=null!=s?s:le.EMPTY,this.right=null!=r?r:le.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,s,r){return new le(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=s?s:this.left,null!=r?r: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 s=this;const r=n(e,s.key);return s=r<0?s.copy(null,null,null,s.left.insert(e,t,n),null):0===r?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return le.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,s=this;if(t(e,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),0===t(e,s.key)){if(s.right.isEmpty())return le.EMPTY;n=s.right.min(),s=s.copy(n.key,n.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(e,t))}return s.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,le.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,le.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const 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(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw y();if(this.right.isRed())throw y();const e=this.left.check();if(e!==this.right.check())throw y();return e+(this.isRed()?0:1)}}le.EMPTY=null,le.RED=!0,le.BLACK=!1,le.EMPTY=new class{constructor(){this.size=0}get key(){throw y()}get value(){throw y()}get color(){throw y()}get left(){throw y()}get right(){throw y()}copy(e,t,n,s,r){return this}insert(e,t,n){return new le(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 he{constructor(e){this.comparator=e,this.data=new ue(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){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const s=n.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new de(this.data.getIterator())}getIteratorFrom(e){return new de(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach((e=>{t=t.add(e)})),t}isEqual(e){if(!(e instanceof he))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,s=n.getNext().key;if(0!==this.comparator(e,s))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new he(this.comparator);return t.data=e,t}}class de{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class fe{constructor(e){this.fields=e,e.sort(q.comparator)}static empty(){return new fe([])}unionWith(e){let t=new he(q.comparator);for(const n of this.fields)t=t.add(n);for(const n of e)t=t.add(n);return new fe(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return M(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class me extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ge{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new me("Invalid base64 string: "+e):e}}(e);return new ge(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new ge(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return L(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ge.EMPTY_BYTE_STRING=new ge("");const pe=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ye(e){if(w(!!e),"string"==typeof e){let t=0;const n=pe.exec(e);if(w(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const s=new Date(e);return{seconds:Math.floor(s.getTime()/1e3),nanos:t}}return{seconds:we(e.seconds),nanos:we(e.nanos)}}function we(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function ve(e){return"string"==typeof e?ge.fromBase64String(e):ge.fromUint8Array(e)}function Ee(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function _e(e){const t=e.mapValue.fields.__previous_value__;return Ee(t)?_e(t):t}function Te(e){const t=ye(e.mapValue.fields.__local_write_time__.timestampValue);return new V(t.seconds,t.nanos)}class Ie{constructor(e,t,n,s,r,i,o,a,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=s,this.ssl=r,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=u}}class Ce{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Ce("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Ce&&e.projectId===this.projectId&&e.database===this.database}}const Se={mapValue:{fields:{__type__:{stringValue:"__max__"}}}};function Ae(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?Ee(e)?4:Ue(e)?9007199254740991:10:y()}function Ne(e,t){if(e===t)return!0;const n=Ae(e);if(n!==Ae(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Te(e).isEqual(Te(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=ye(e.timestampValue),s=ye(t.timestampValue);return n.seconds===s.seconds&&n.nanos===s.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return ve(e.bytesValue).isEqual(ve(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return we(e.geoPointValue.latitude)===we(t.geoPointValue.latitude)&&we(e.geoPointValue.longitude)===we(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return we(e.integerValue)===we(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=we(e.doubleValue),s=we(t.doubleValue);return n===s?ee(n)===ee(s):isNaN(n)&&isNaN(s)}return!1}(e,t);case 9:return M(e.arrayValue.values||[],t.arrayValue.values||[],Ne);case 10:return function(e,t){const n=e.mapValue.fields||{},s=t.mapValue.fields||{};if(ie(n)!==ie(s))return!1;for(const r in n)if(n.hasOwnProperty(r)&&(void 0===s[r]||!Ne(n[r],s[r])))return!1;return!0}(e,t);default:return y()}}function be(e,t){return void 0!==(e.values||[]).find((e=>Ne(e,t)))}function ke(e,t){if(e===t)return 0;const n=Ae(e),s=Ae(t);if(n!==s)return L(n,s);switch(n){case 0:case 9007199254740991:return 0;case 1:return L(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=we(e.integerValue||e.doubleValue),s=we(t.integerValue||t.doubleValue);return n<s?-1:n>s?1:n===s?0:isNaN(n)?isNaN(s)?0:-1:1}(e,t);case 3:return De(e.timestampValue,t.timestampValue);case 4:return De(Te(e),Te(t));case 5:return L(e.stringValue,t.stringValue);case 6:return function(e,t){const n=ve(e),s=ve(t);return n.compareTo(s)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),s=t.split("/");for(let r=0;r<n.length&&r<s.length;r++){const e=L(n[r],s[r]);if(0!==e)return e}return L(n.length,s.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=L(we(e.latitude),we(t.latitude));return 0!==n?n:L(we(e.longitude),we(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){const n=e.values||[],s=t.values||[];for(let r=0;r<n.length&&r<s.length;++r){const e=ke(n[r],s[r]);if(e)return e}return L(n.length,s.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Se.mapValue&&t===Se.mapValue)return 0;if(e===Se.mapValue)return 1;if(t===Se.mapValue)return-1;const n=e.fields||{},s=Object.keys(n),r=t.fields||{},i=Object.keys(r);s.sort(),i.sort();for(let o=0;o<s.length&&o<i.length;++o){const e=L(s[o],i[o]);if(0!==e)return e;const t=ke(n[s[o]],r[i[o]]);if(0!==t)return t}return L(s.length,i.length)}(e.mapValue,t.mapValue);default:throw y()}}function De(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return L(e,t);const n=ye(e),s=ye(t),r=L(n.seconds,s.seconds);return 0!==r?r:L(n.nanos,s.nanos)}function Re(e){return xe(e)}function xe(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=ye(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return ve(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return B.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const s of e.values||[])n?n=!1:t+=",",t+=xe(s);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",s=!0;for(const r of t)s?s=!1:n+=",",n+=`${r}:${xe(e.fields[r])}`;return n+"}"}(e.mapValue):y()}function Le(e){return!!e&&"integerValue"in e}function Me(e){return!!e&&"arrayValue"in e}function Ve(e){return!!e&&"nullValue"in e}function Oe(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Fe(e){return!!e&&"mapValue"in e}function Pe(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){const t={mapValue:{fields:{}}};return oe(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=Pe(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Pe(e.arrayValue.values[n]);return t}return Object.assign({},e)}function Ue(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}class qe{constructor(e){this.value=e}static empty(){return new qe({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Fe(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Pe(t)}setAll(e){let t=q.emptyPath(),n={},s=[];e.forEach(((e,r)=>{if(!t.isImmediateParentOf(r)){const e=this.getFieldsMap(t);this.applyChanges(e,n,s),n={},s=[],t=r.popLast()}e?n[r.lastSegment()]=Pe(e):s.push(r.lastSegment())}));const r=this.getFieldsMap(t);this.applyChanges(r,n,s)}delete(e){const t=this.field(e.popLast());Fe(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ne(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 s=t.mapValue.fields[e.get(n)];Fe(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){oe(t,((t,n)=>e[t]=n));for(const s of n)delete e[s]}clone(){return new qe(Pe(this.value))}}function Be(e){const t=[];return oe(e.fields,((e,n)=>{const s=new q([e]);if(Fe(n)){const e=Be(n.mapValue).fields;if(0===e.length)t.push(s);else for(const n of e)t.push(s.child(n))}else t.push(s)})),new fe(t)}class ze{constructor(e,t,n,s,r,i,o){this.key=e,this.documentType=t,this.version=n,this.readTime=s,this.createTime=r,this.data=i,this.documentState=o}static newInvalidDocument(e){return new ze(e,0,O.min(),O.min(),O.min(),qe.empty(),0)}static newFoundDocument(e,t,n,s){return new ze(e,1,t,O.min(),n,s,0)}static newNoDocument(e,t){return new ze(e,2,t,O.min(),O.min(),qe.empty(),0)}static newUnknownDocument(e,t){return new ze(e,3,t,O.min(),O.min(),qe.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(O.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=qe.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=qe.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=O.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 ze&&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 ze(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 $e{constructor(e,t){this.position=e,this.inclusive=t}}function Ke(e,t,n){let s=0;for(let r=0;r<e.position.length;r++){const i=t[r],o=e.position[r];if(s=i.field.isKeyField()?B.comparator(B.fromName(o.referenceValue),n.key):ke(o,n.data.field(i.field)),"desc"===i.dir&&(s*=-1),0!==s)break}return s}function Ge(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ne(e.position[n],t.position[n]))return!1;return!0}class Qe{constructor(e,t="asc"){this.field=e,this.dir=t}}function je(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class He{}class We extends He{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 st(e,t,n):"array-contains"===t?new at(e,n):"in"===t?new ut(e,n):"not-in"===t?new ct(e,n):"array-contains-any"===t?new lt(e,n):new We(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new rt(e,n):new it(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(ke(t,this.value)):null!==t&&Ae(this.value)===Ae(t)&&this.matchesComparison(ke(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 y()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class Ye extends He{constructor(e,t){super(),this.filters=e,this.op=t,this.ue=null}static create(e,t){return new Ye(e,t)}matches(e){return Xe(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ue||(this.ue=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ue}getFilters(){return Object.assign([],this.filters)}}function Xe(e){return"and"===e.op}function Je(e){return Ze(e)&&Xe(e)}function Ze(e){for(const t of e.filters)if(t instanceof Ye)return!1;return!0}function et(e){if(e instanceof We)return e.field.canonicalString()+e.op.toString()+Re(e.value);if(Je(e))return e.filters.map((e=>et(e))).join(",");{const t=e.filters.map((e=>et(e))).join(",");return`${e.op}(${t})`}}function tt(e,t){return e instanceof We?function(e,t){return t instanceof We&&e.op===t.op&&e.field.isEqual(t.field)&&Ne(e.value,t.value)}(e,t):e instanceof Ye?function(e,t){return t instanceof Ye&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,s)=>e&&tt(n,t.filters[s])),!0)}(e,t):void y()}function nt(e){return e instanceof We?function(e){return`${e.field.canonicalString()} ${e.op} ${Re(e.value)}`}(e):e instanceof Ye?function(e){return e.op.toString()+" {"+e.getFilters().map(nt).join(" ,")+"}"}(e):"Filter"}class st extends We{constructor(e,t,n){super(e,t,n),this.key=B.fromName(n.referenceValue)}matches(e){const t=B.comparator(e.key,this.key);return this.matchesComparison(t)}}class rt extends We{constructor(e,t){super(e,"in",t),this.keys=ot("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class it extends We{constructor(e,t){super(e,"not-in",t),this.keys=ot("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function ot(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>B.fromName(e.referenceValue)))}class at extends We{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Me(t)&&be(t.arrayValue,this.value)}}class ut extends We{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&be(this.value.arrayValue,t)}}class ct extends We{constructor(e,t){super(e,"not-in",t)}matches(e){if(be(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!be(this.value.arrayValue,t)}}class lt extends We{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Me(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>be(this.value.arrayValue,e)))}}class ht{constructor(e,t=null,n=[],s=[],r=null,i=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=s,this.limit=r,this.startAt=i,this.endAt=o,this.ce=null}}function dt(e,t=null,n=[],s=[],r=null,i=null,o=null){return new ht(e,t,n,s,r,i,o)}function ft(e){const t=v(e);if(null===t.ce){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>et(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),Z(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Re(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Re(e))).join(",")),t.ce=e}return t.ce}function mt(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!je(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!tt(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Ge(e.startAt,t.startAt)&&Ge(e.endAt,t.endAt)}function gt(e){return B.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class pt{constructor(e,t=null,n=[],s=[],r=null,i="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=s,this.limit=r,this.limitType=i,this.startAt=o,this.endAt=a,this.le=null,this.he=null,this.Pe=null,this.startAt,this.endAt}}function yt(e,t,n,s,r,i,o,a){return new pt(e,t,n,s,r,i,o,a)}function wt(e){return new pt(e)}function vt(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 Et(e){return null!==e.collectionGroup}function _t(e){const t=v(e);if(null===t.le){t.le=[];const e=new Set;for(const r of t.explicitOrderBy)t.le.push(r),e.add(r.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",s=function(e){let t=new he(q.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t}(t);s.forEach((s=>{e.has(s.canonicalString())||s.isKeyField()||t.le.push(new Qe(s,n))})),e.has(q.keyField().canonicalString())||t.le.push(new Qe(q.keyField(),n))}return t.le}function Tt(e){const t=v(e);return t.he||(t.he=It(t,_t(e))),t.he}function It(e,t){if("F"===e.limitType)return dt(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new Qe(e.field,t)}));const n=e.endAt?new $e(e.endAt.position,e.endAt.inclusive):null,s=e.startAt?new $e(e.startAt.position,e.startAt.inclusive):null;return dt(e.path,e.collectionGroup,t,e.filters,e.limit,n,s)}}function Ct(e,t,n){return new pt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function St(e,t){return mt(Tt(e),Tt(t))&&e.limitType===t.limitType}function At(e){return`${ft(Tt(e))}|lt:${e.limitType}`}function Nt(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>nt(e))).join(", ")}]`),Z(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Re(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Re(e))).join(",")),`Target(${t})`}(Tt(e))}; limitType=${e.limitType})`}function bt(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):B.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of _t(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const s=Ke(e,t,n);return e.inclusive?s<=0:s<0}(e.startAt,_t(e),t))&&!(e.endAt&&!function(e,t,n){const s=Ke(e,t,n);return e.inclusive?s>=0:s>0}(e.endAt,_t(e),t))}(e,t)}function kt(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Dt(e){return(t,n)=>{let s=!1;for(const r of _t(e)){const e=Rt(r,t,n);if(0!==e)return e;s=s||r.field.isKeyField()}return 0}}function Rt(e,t,n){const s=e.field.isKeyField()?B.comparator(t.key,n.key):function(e,t,n){const s=t.data.field(e),r=n.data.field(e);return null!==s&&null!==r?ke(s,r):y()}(e.field,t,n);switch(e.dir){case"asc":return s;case"desc":return-1*s;default:return y()}}class xt{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[s,r]of n)if(this.equalsFn(s,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),s=this.inner[n];if(void 0===s)return this.inner[n]=[[e,t]],void this.innerSize++;for(let r=0;r<s.length;r++)if(this.equalsFn(s[r][0],e))return void(s[r]=[e,t]);s.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let s=0;s<n.length;s++)if(this.equalsFn(n[s][0],e))return 1===n.length?delete this.inner[t]:n.splice(s,1),this.innerSize--,!0;return!1}forEach(e){oe(this.inner,((t,n)=>{for(const[s,r]of n)e(s,r)}))}isEmpty(){return ae(this.inner)}size(){return this.innerSize}}const Lt=new ue(B.comparator);function Mt(){return Lt}const Vt=new ue(B.comparator);function Ot(...e){let t=Vt;for(const n of e)t=t.insert(n.key,n);return t}function Ft(e){let t=Vt;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Pt(){return qt()}function Ut(){return qt()}function qt(){return new xt((e=>e.toString()),((e,t)=>e.isEqual(t)))}const Bt=new ue(B.comparator),zt=new he(B.comparator);function $t(...e){let t=zt;for(const n of e)t=t.add(n);return t}const Kt=new he(L);function Gt(){return Kt}function Qt(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:ee(t)?"-0":t}}function jt(e){return{integerValue:""+e}}function Ht(e,t){return te(t)?jt(t):Qt(e,t)}class Wt{constructor(){this._=void 0}}function Yt(e,t,n){return e instanceof Zt?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&Ee(t)&&(t=_e(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof en?tn(e,t):e instanceof nn?sn(e,t):function(e,t){const n=Jt(e,t),s=on(n)+on(e.Ie);return Le(n)&&Le(e.Ie)?jt(s):Qt(e.serializer,s)}(e,t)}function Xt(e,t,n){return e instanceof en?tn(e,t):e instanceof nn?sn(e,t):n}function Jt(e,t){return e instanceof rn?function(e){return Le(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class Zt extends Wt{}class en extends Wt{constructor(e){super(),this.elements=e}}function tn(e,t){const n=an(t);for(const s of e.elements)n.some((e=>Ne(e,s)))||n.push(s);return{arrayValue:{values:n}}}class nn extends Wt{constructor(e){super(),this.elements=e}}function sn(e,t){let n=an(t);for(const s of e.elements)n=n.filter((e=>!Ne(e,s)));return{arrayValue:{values:n}}}class rn extends Wt{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function on(e){return we(e.integerValue||e.doubleValue)}function an(e){return Me(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class un{constructor(e,t){this.version=e,this.transformResults=t}}class cn{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new cn}static exists(e){return new cn(void 0,e)}static updateTime(e){return new cn(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 ln(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class hn{}function dn(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Tn(e.key,cn.none()):new yn(e.key,e.data,cn.none());{const n=e.data,s=qe.empty();let r=new he(q.comparator);for(let e of t.fields)if(!r.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?s.delete(e):s.set(e,t),r=r.add(e)}return new wn(e.key,s,new fe(r.toArray()),cn.none())}}function fn(e,t,n){e instanceof yn?function(e,t,n){const s=e.value.clone(),r=En(e.fieldTransforms,t,n.transformResults);s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):e instanceof wn?function(e,t,n){if(!ln(e.precondition,t))return void t.convertToUnknownDocument(n.version);const s=En(e.fieldTransforms,t,n.transformResults),r=t.data;r.setAll(vn(e)),r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function mn(e,t,n,s){return e instanceof yn?function(e,t,n,s){if(!ln(e.precondition,t))return n;const r=e.value.clone(),i=_n(e.fieldTransforms,s,t);return r.setAll(i),t.convertToFoundDocument(t.version,r).setHasLocalMutations(),null}(e,t,n,s):e instanceof wn?function(e,t,n,s){if(!ln(e.precondition,t))return n;const r=_n(e.fieldTransforms,s,t),i=t.data;return i.setAll(vn(e)),i.setAll(r),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,s):function(e,t,n){return ln(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function gn(e,t){let n=null;for(const s of e.fieldTransforms){const e=t.data.field(s.field),r=Jt(s.transform,e||null);null!=r&&(null===n&&(n=qe.empty()),n.set(s.field,r))}return n||null}function pn(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&M(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof en&&t instanceof en||e instanceof nn&&t instanceof nn?M(e.elements,t.elements,Ne):e instanceof rn&&t instanceof rn?Ne(e.Ie,t.Ie):e instanceof Zt&&t instanceof Zt}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class yn extends hn{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class wn extends hn{constructor(e,t,n,s,r=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=s,this.fieldTransforms=r,this.type=1}getFieldMask(){return this.fieldMask}}function vn(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const s=e.data.field(n);t.set(n,s)}})),t}function En(e,t,n){const s=new Map;w(e.length===n.length);for(let r=0;r<n.length;r++){const i=e[r],o=i.transform,a=t.data.field(i.field);s.set(i.field,Xt(o,a,n[r]))}return s}function _n(e,t,n){const s=new Map;for(const r of e){const e=r.transform,i=n.data.field(r.field);s.set(r.field,Yt(e,i,t))}return s}class Tn extends hn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class In extends hn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Cn{constructor(e,t,n,s){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let s=0;s<this.mutations.length;s++){const t=this.mutations[s];t.key.isEqual(e.key)&&fn(t,e,n[s])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=mn(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=mn(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Ut();return this.mutations.forEach((s=>{const r=e.get(s.key),i=r.overlayedDocument;let o=this.applyToLocalView(i,r.mutatedFields);o=t.has(s.key)?null:o;const a=dn(i,o);null!==a&&n.set(s.key,a),i.isValidDocument()||i.convertToNoDocument(O.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),$t())}isEqual(e){return this.batchId===e.batchId&&M(this.mutations,e.mutations,((e,t)=>pn(e,t)))&&M(this.baseMutations,e.baseMutations,((e,t)=>pn(e,t)))}}class Sn{constructor(e,t,n,s){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=s}static from(e,t,n){w(e.mutations.length===n.length);let s=Bt;const r=e.mutations;for(let i=0;i<r.length;i++)s=s.insert(r[i].key,n[i].version);return new Sn(e,t,n,s)}}class An{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Nn{constructor(e,t){this.count=e,this.unchangedNames=t}}var bn,kn;function Dn(e){switch(e){default:return y();case E.CANCELLED:case E.UNKNOWN:case E.DEADLINE_EXCEEDED:case E.RESOURCE_EXHAUSTED:case E.INTERNAL:case E.UNAVAILABLE:case E.UNAUTHENTICATED:return!1;case E.INVALID_ARGUMENT:case E.NOT_FOUND:case E.ALREADY_EXISTS:case E.PERMISSION_DENIED:case E.FAILED_PRECONDITION:case E.ABORTED:case E.OUT_OF_RANGE:case E.UNIMPLEMENTED:case E.DATA_LOSS:return!0}}function Rn(e){if(void 0===e)return m("GRPC error has no .code"),E.UNKNOWN;switch(e){case bn.OK:return E.OK;case bn.CANCELLED:return E.CANCELLED;case bn.UNKNOWN:return E.UNKNOWN;case bn.DEADLINE_EXCEEDED:return E.DEADLINE_EXCEEDED;case bn.RESOURCE_EXHAUSTED:return E.RESOURCE_EXHAUSTED;case bn.INTERNAL:return E.INTERNAL;case bn.UNAVAILABLE:return E.UNAVAILABLE;case bn.UNAUTHENTICATED:return E.UNAUTHENTICATED;case bn.INVALID_ARGUMENT:return E.INVALID_ARGUMENT;case bn.NOT_FOUND:return E.NOT_FOUND;case bn.ALREADY_EXISTS:return E.ALREADY_EXISTS;case bn.PERMISSION_DENIED:return E.PERMISSION_DENIED;case bn.FAILED_PRECONDITION:return E.FAILED_PRECONDITION;case bn.ABORTED:return E.ABORTED;case bn.OUT_OF_RANGE:return E.OUT_OF_RANGE;case bn.UNIMPLEMENTED:return E.UNIMPLEMENTED;case bn.DATA_LOSS:return E.DATA_LOSS;default:return y()}}(kn=bn||(bn={}))[kn.OK=0]="OK",kn[kn.CANCELLED=1]="CANCELLED",kn[kn.UNKNOWN=2]="UNKNOWN",kn[kn.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",kn[kn.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",kn[kn.NOT_FOUND=5]="NOT_FOUND",kn[kn.ALREADY_EXISTS=6]="ALREADY_EXISTS",kn[kn.PERMISSION_DENIED=7]="PERMISSION_DENIED",kn[kn.UNAUTHENTICATED=16]="UNAUTHENTICATED",kn[kn.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",kn[kn.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",kn[kn.ABORTED=10]="ABORTED",kn[kn.OUT_OF_RANGE=11]="OUT_OF_RANGE",kn[kn.UNIMPLEMENTED=12]="UNIMPLEMENTED",kn[kn.INTERNAL=13]="INTERNAL",kn[kn.UNAVAILABLE=14]="UNAVAILABLE",kn[kn.DATA_LOSS=15]="DATA_LOSS";let xn=null;function Ln(){return new TextEncoder}const Mn=new a.z8([4294967295,4294967295],0);function Vn(e){const t=Ln().encode(e),n=new a.V8;return n.update(t),new Uint8Array(n.digest())}function On(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),s=t.getUint32(4,!0),r=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new a.z8([n,s],0),new a.z8([r,i],0)]}class Fn{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Pn(`Invalid padding: ${t}`);if(n<0)throw new Pn(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new Pn(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Pn(`Invalid padding when bitmap length is 0: ${t}`);this.Te=8*e.length-t,this.Ee=a.z8.fromNumber(this.Te)}de(e,t,n){let s=e.add(t.multiply(a.z8.fromNumber(n)));return 1===s.compare(Mn)&&(s=new a.z8([s.getBits(0),s.getBits(1)],0)),s.modulo(this.Ee).toNumber()}Ae(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Te)return!1;const t=Vn(e),[n,s]=On(t);for(let r=0;r<this.hashCount;r++){const e=this.de(n,s,r);if(!this.Ae(e))return!1}return!0}static create(e,t,n){const s=e%8==0?0:8-e%8,r=new Uint8Array(Math.ceil(e/8)),i=new Fn(r,s,t);return n.forEach((e=>i.insert(e))),i}insert(e){if(0===this.Te)return;const t=Vn(e),[n,s]=On(t);for(let r=0;r<this.hashCount;r++){const e=this.de(n,s,r);this.Re(e)}}Re(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class Pn extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Un{constructor(e,t,n,s,r){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=r}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const s=new Map;return s.set(e,qn.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Un(O.min(),s,new ue(L),Mt(),$t())}}class qn{constructor(e,t,n,s,r){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=r}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new qn(n,t,$t(),$t(),$t())}}class Bn{constructor(e,t,n,s){this.Ve=e,this.removedTargetIds=t,this.key=n,this.me=s}}class zn{constructor(e,t){this.targetId=e,this.fe=t}}class $n{constructor(e,t,n=ge.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}}class Kn{constructor(){this.ge=0,this.pe=jn(),this.ye=ge.EMPTY_BYTE_STRING,this.we=!1,this.Se=!0}get current(){return this.we}get resumeToken(){return this.ye}get be(){return 0!==this.ge}get De(){return this.Se}Ce(e){e.approximateByteSize()>0&&(this.Se=!0,this.ye=e)}ve(){let e=$t(),t=$t(),n=$t();return this.pe.forEach(((s,r)=>{switch(r){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:n=n.add(s);break;default:y()}})),new qn(this.ye,this.we,e,t,n)}Fe(){this.Se=!1,this.pe=jn()}Me(e,t){this.Se=!0,this.pe=this.pe.insert(e,t)}xe(e){this.Se=!0,this.pe=this.pe.remove(e)}Oe(){this.ge+=1}Ne(){this.ge-=1,w(this.ge>=0)}Be(){this.Se=!0,this.we=!0}}class Gn{constructor(e){this.Le=e,this.ke=new Map,this.qe=Mt(),this.Qe=Qn(),this.Ke=new ue(L)}$e(e){for(const t of e.Ve)e.me&&e.me.isFoundDocument()?this.Ue(t,e.me):this.We(t,e.key,e.me);for(const t of e.removedTargetIds)this.We(t,e.key,e.me)}Ge(e){this.forEachTarget(e,(t=>{const n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.Ce(e.resumeToken);break;case 1:n.Ne(),n.be||n.Fe(),n.Ce(e.resumeToken);break;case 2:n.Ne(),n.be||this.removeTarget(t);break;case 3:this.je(t)&&(n.Be(),n.Ce(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.Ce(e.resumeToken));break;default:y()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ke.forEach(((e,n)=>{this.je(n)&&t(n)}))}Je(e){const t=e.targetId,n=e.fe.count,s=this.Ye(t);if(s){const r=s.target;if(gt(r))if(0===n){const e=new B(r.path);this.We(t,e,ze.newNoDocument(e,O.min()))}else w(1===n);else{const s=this.Ze(t);if(s!==n){const n=this.Xe(e),r=n?this.et(n,e,s):1;if(0!==r){this.He(t);const e=2===r?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==xn||xn.tt(function(e,t,n,s,r){var i,o,a,u,c,l;const h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===r,hashCount:null!==(i=null==d?void 0:d.hashCount)&&void 0!==i?i:0,bitmapLength:null!==(u=null===(a=null===(o=null==d?void 0:d.bits)||void 0===o?void 0:o.bitmap)||void 0===a?void 0:a.length)&&void 0!==u?u:0,padding:null!==(l=null===(c=null==d?void 0:d.bits)||void 0===c?void 0:c.padding)&&void 0!==l?l:0,mightContain:e=>{var t;return null!==(t=null==s?void 0:s.mightContain(e))&&void 0!==t&&t}}),h}(s,e.fe,this.Le.nt(),n,r))}}}}Xe(e){const t=e.fe.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:s=0},hashCount:r=0}=t;let i,o;try{i=ve(n).toUint8Array()}catch(e){if(e instanceof me)return g("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{o=new Fn(i,s,r)}catch(e){return g(e instanceof Pn?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===o.Te?null:o}et(e,t,n){return t.fe.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let s=0;return n.forEach((n=>{const r=this.Le.nt(),i=`projects/${r.projectId}/databases/${r.database}/documents/${n.path.canonicalString()}`;e.mightContain(i)||(this.We(t,n,null),s++)})),s}it(e){const t=new Map;this.ke.forEach(((n,s)=>{const r=this.Ye(s);if(r){if(n.current&>(r.target)){const t=new B(r.target.path);null!==this.qe.get(t)||this.st(s,t)||this.We(s,t,ze.newNoDocument(t,e))}n.De&&(t.set(s,n.ve()),n.Fe())}}));let n=$t();this.Qe.forEach(((e,t)=>{let s=!0;t.forEachWhile((e=>{const t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(s=!1,!1)})),s&&(n=n.add(e))})),this.qe.forEach(((t,n)=>n.setReadTime(e)));const s=new Un(e,t,this.Ke,this.qe,n);return this.qe=Mt(),this.Qe=Qn(),this.Ke=new ue(L),s}Ue(e,t){if(!this.je(e))return;const n=this.st(e,t.key)?2:0;this.ze(e).Me(t.key,n),this.qe=this.qe.insert(t.key,t),this.Qe=this.Qe.insert(t.key,this.ot(t.key).add(e))}We(e,t,n){if(!this.je(e))return;const s=this.ze(e);this.st(e,t)?s.Me(t,1):s.xe(t),this.Qe=this.Qe.insert(t,this.ot(t).delete(e)),n&&(this.qe=this.qe.insert(t,n))}removeTarget(e){this.ke.delete(e)}Ze(e){const t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Oe(e){this.ze(e).Oe()}ze(e){let t=this.ke.get(e);return t||(t=new Kn,this.ke.set(e,t)),t}ot(e){let t=this.Qe.get(e);return t||(t=new he(L),this.Qe=this.Qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||f("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){const t=this.ke.get(e);return t&&t.be?null:this.Le._t(e)}He(e){this.ke.set(e,new Kn),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}st(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Qn(){return new ue(B.comparator)}function jn(){return new ue(B.comparator)}const Hn={asc:"ASCENDING",desc:"DESCENDING"},Wn={"<":"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"},Yn={and:"AND",or:"OR"};class Xn{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Jn(e,t){return e.useProto3Json||Z(t)?t:{value:t}}function Zn(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 es(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function ts(e,t){return Zn(e,t.toTimestamp())}function ns(e){return w(!!e),O.fromTimestamp(function(e){const t=ye(e);return new V(t.seconds,t.nanos)}(e))}function ss(e,t){return function(e){return new P(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function rs(e){const t=P.fromString(e);return w(Cs(t)),t}function is(e,t){return ss(e.databaseId,t.path)}function os(e,t){const n=rs(t);if(n.get(1)!==e.databaseId.projectId)throw new _(E.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 _(E.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new B(ls(n))}function as(e,t){return ss(e.databaseId,t)}function us(e){const t=rs(e);return 4===t.length?P.emptyPath():ls(t)}function cs(e){return new P(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function ls(e){return w(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function hs(e,t,n){return{name:is(e,t),fields:n.value.mapValue.fields}}function ds(e,t){let n;if(t instanceof yn)n={update:hs(e,t.key,t.value)};else if(t instanceof Tn)n={delete:is(e,t.key)};else if(t instanceof wn)n={update:hs(e,t.key,t.data),updateMask:Is(t.fieldMask)};else{if(!(t instanceof In))return y();n={verify:is(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof Zt)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof en)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof nn)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof rn)return{fieldPath:t.field.canonicalString(),increment:n.Ie};throw y()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:ts(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:y()}(e,t.precondition)),n}function fs(e,t){return{documents:[as(e,t.path)]}}function ms(e,t){const n={structuredQuery:{}},s=t.path;null!==t.collectionGroup?(n.parent=as(e,s),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=as(e,s.popLast()),n.structuredQuery.from=[{collectionId:s.lastSegment()}]);const r=function(e){if(0!==e.length)return Ts(Ye.create(e,"and"))}(t.filters);r&&(n.structuredQuery.where=r);const i=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:Es(e.field),direction:ys(e.dir)}}(e)))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);const o=Jn(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt=function(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function gs(e){let t=us(e.parent);const n=e.structuredQuery,s=n.from?n.from.length:0;let r=null;if(s>0){w(1===s);const e=n.from[0];e.allDescendants?r=e.collectionId:t=t.child(e.collectionId)}let i=[];n.where&&(i=function(e){const t=ps(e);return t instanceof Ye&&Je(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=function(e){return e.map((e=>function(e){return new Qe(_s(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,Z(t)?null:t}(n.limit));let u=null;n.startAt&&(u=function(e){const t=!!e.before,n=e.values||[];return new $e(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new $e(n,t)}(n.endAt)),yt(t,r,o,i,a,"F",u,c)}function ps(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=_s(e.unaryFilter.field);return We.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=_s(e.unaryFilter.field);return We.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const s=_s(e.unaryFilter.field);return We.create(s,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const r=_s(e.unaryFilter.field);return We.create(r,"!=",{nullValue:"NULL_VALUE"});default:return y()}}(e):void 0!==e.fieldFilter?function(e){return We.create(_s(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return y()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return Ye.create(e.compositeFilter.filters.map((e=>ps(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return y()}}(e.compositeFilter.op))}(e):y()}function ys(e){return Hn[e]}function ws(e){return Wn[e]}function vs(e){return Yn[e]}function Es(e){return{fieldPath:e.canonicalString()}}function _s(e){return q.fromServerFormat(e.fieldPath)}function Ts(e){return e instanceof We?function(e){if("=="===e.op){if(Oe(e.value))return{unaryFilter:{field:Es(e.field),op:"IS_NAN"}};if(Ve(e.value))return{unaryFilter:{field:Es(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Oe(e.value))return{unaryFilter:{field:Es(e.field),op:"IS_NOT_NAN"}};if(Ve(e.value))return{unaryFilter:{field:Es(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Es(e.field),op:ws(e.op),value:e.value}}}(e):e instanceof Ye?function(e){const t=e.getFilters().map((e=>Ts(e)));return 1===t.length?t[0]:{compositeFilter:{op:vs(e.op),filters:t}}}(e):y()}function Is(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Cs(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class Ss{constructor(e,t,n,s,r=O.min(),i=O.min(),o=ge.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=s,this.snapshotVersion=r,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new Ss(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Ss(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Ss(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Ss(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class As{constructor(e){this.ut=e}}function Ns(e){const t=gs({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Ct(t,t.limit,"L"):t}class bs{constructor(){}ht(e,t){this.Pt(e,t),t.It()}Pt(e,t){if("nullValue"in e)this.Tt(t,5);else if("booleanValue"in e)this.Tt(t,10),t.Et(e.booleanValue?1:0);else if("integerValue"in e)this.Tt(t,15),t.Et(we(e.integerValue));else if("doubleValue"in e){const n=we(e.doubleValue);isNaN(n)?this.Tt(t,13):(this.Tt(t,15),ee(n)?t.Et(0):t.Et(n))}else if("timestampValue"in e){const n=e.timestampValue;this.Tt(t,20),"string"==typeof n?t.dt(n):(t.dt(`${n.seconds||""}`),t.Et(n.nanos||0))}else if("stringValue"in e)this.At(e.stringValue,t),this.Rt(t);else if("bytesValue"in e)this.Tt(t,30),t.Vt(ve(e.bytesValue)),this.Rt(t);else if("referenceValue"in e)this.ft(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.Tt(t,45),t.Et(n.latitude||0),t.Et(n.longitude||0)}else"mapValue"in e?Ue(e)?this.Tt(t,Number.MAX_SAFE_INTEGER):(this.gt(e.mapValue,t),this.Rt(t)):"arrayValue"in e?(this.yt(e.arrayValue,t),this.Rt(t)):y()}At(e,t){this.Tt(t,25),this.wt(e,t)}wt(e,t){t.dt(e)}gt(e,t){const n=e.fields||{};this.Tt(t,55);for(const s of Object.keys(n))this.At(s,t),this.Pt(n[s],t)}yt(e,t){const n=e.values||[];this.Tt(t,50);for(const s of n)this.Pt(s,t)}ft(e,t){this.Tt(t,37),B.fromName(e).path.forEach((e=>{this.Tt(t,60),this.wt(e,t)}))}Tt(e,t){e.Et(t)}Rt(e){e.Et(2)}}bs.St=new bs;class ks{constructor(){this.on=new Ds}addToCollectionParentIndex(e,t){return this.on.add(t),Y.resolve()}getCollectionParents(e,t){return Y.resolve(this.on.getEntries(t))}addFieldIndex(e,t){return Y.resolve()}deleteFieldIndex(e,t){return Y.resolve()}deleteAllFieldIndexes(e){return Y.resolve()}createTargetIndexes(e,t){return Y.resolve()}getDocumentsMatchingTarget(e,t){return Y.resolve(null)}getIndexType(e,t){return Y.resolve(0)}getFieldIndexes(e,t){return Y.resolve([])}getNextCollectionGroupToUpdate(e){return Y.resolve(null)}getMinOffset(e,t){return Y.resolve(G.min())}getMinOffsetFromCollectionGroup(e,t){return Y.resolve(G.min())}updateCollectionGroup(e,t,n){return Y.resolve()}updateIndexEntries(e,t){return Y.resolve()}}class Ds{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new he(P.comparator),r=!s.has(n);return this.index[t]=s.add(n),r}has(e){const t=e.lastSegment(),n=e.popLast(),s=this.index[t];return s&&s.has(n)}getEntries(e){return(this.index[e]||new he(P.comparator)).toArray()}}new Uint8Array(0);class Rs{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Rs(e,Rs.DEFAULT_COLLECTION_PERCENTILE,Rs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}Rs.DEFAULT_COLLECTION_PERCENTILE=10,Rs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Rs.DEFAULT=new Rs(41943040,Rs.DEFAULT_COLLECTION_PERCENTILE,Rs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Rs.DISABLED=new Rs(-1,0,0);class xs{constructor(e){this.xn=e}next(){return this.xn+=2,this.xn}static On(){return new xs(0)}static Nn(){return new xs(-1)}}class Ls{constructor(){this.changes=new xt((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,ze.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?Y.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Ms{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Vs{constructor(e,t,n,s){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=s}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((s=>(n=s,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&mn(n.mutation,e,fe.empty(),V.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,$t()).next((()=>t))))}getLocalViewOfDocuments(e,t,n=$t()){const s=Pt();return this.populateOverlays(e,s,t).next((()=>this.computeViews(e,t,s,n).next((e=>{let t=Ot();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Pt();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,$t())))}populateOverlays(e,t,n){const s=[];return n.forEach((e=>{t.has(e)||s.push(e)})),this.documentOverlayCache.getOverlays(e,s).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,s){let r=Mt();const i=qt(),o=qt();return t.forEach(((e,t)=>{const o=n.get(t.key);s.has(t.key)&&(void 0===o||o.mutation instanceof wn)?r=r.insert(t.key,t):void 0!==o?(i.set(t.key,o.mutation.getFieldMask()),mn(o.mutation,t,o.mutation.getFieldMask(),V.now())):i.set(t.key,fe.empty())})),this.recalculateAndSaveOverlays(e,r).next((e=>(e.forEach(((e,t)=>i.set(e,t))),t.forEach(((e,t)=>{var n;return o.set(e,new Ms(t,null!==(n=i.get(e))&&void 0!==n?n:null))})),o)))}recalculateAndSaveOverlays(e,t){const n=qt();let s=new ue(((e,t)=>e-t)),r=$t();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const r of e)r.keys().forEach((e=>{const i=t.get(e);if(null===i)return;let o=n.get(e)||fe.empty();o=r.applyToLocalView(i,o),n.set(e,o);const a=(s.get(r.batchId)||$t()).add(e);s=s.insert(r.batchId,a)}))})).next((()=>{const i=[],o=s.getReverseIterator();for(;o.hasNext();){const s=o.getNext(),a=s.key,u=s.value,c=Ut();u.forEach((e=>{if(!r.has(e)){const s=dn(t.get(e),n.get(e));null!==s&&c.set(e,s),r=r.add(e)}})),i.push(this.documentOverlayCache.saveOverlays(e,a,c))}return Y.waitFor(i)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n,s){return function(e){return B.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Et(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,s):this.getDocumentsMatchingCollectionQuery(e,t,n,s)}getNextDocuments(e,t,n,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,s).next((r=>{const i=s-r.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,s-r.size):Y.resolve(Pt());let o=-1,a=r;return i.next((t=>Y.forEach(t,((t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),r.get(t)?Y.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{a=a.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,r))).next((()=>this.computeViews(e,a,t,$t()))).next((e=>({batchId:o,changes:Ft(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new B(t)).next((e=>{let t=Ot();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){const r=t.collectionGroup;let i=Ot();return this.indexManager.getCollectionParents(e,r).next((o=>Y.forEach(o,(o=>{const a=function(e,t){return new pt(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,o.child(r));return this.getDocumentsMatchingCollectionQuery(e,a,n,s).next((e=>{e.forEach(((e,t)=>{i=i.insert(e,t)}))}))})).next((()=>i))))}getDocumentsMatchingCollectionQuery(e,t,n,s){let r;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((i=>(r=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,r,s)))).next((e=>{r.forEach(((t,n)=>{const s=n.getKey();null===e.get(s)&&(e=e.insert(s,ze.newInvalidDocument(s)))}));let n=Ot();return e.forEach(((e,s)=>{const i=r.get(e);void 0!==i&&mn(i.mutation,s,fe.empty(),V.now()),bt(t,s)&&(n=n.insert(e,s))})),n}))}}class Os{constructor(e){this.serializer=e,this.ur=new Map,this.cr=new Map}getBundleMetadata(e,t){return Y.resolve(this.ur.get(t))}saveBundleMetadata(e,t){return this.ur.set(t.id,function(e){return{id:e.id,version:e.version,createTime:ns(e.createTime)}}(t)),Y.resolve()}getNamedQuery(e,t){return Y.resolve(this.cr.get(t))}saveNamedQuery(e,t){return this.cr.set(t.name,function(e){return{name:e.name,query:Ns(e.bundledQuery),readTime:ns(e.readTime)}}(t)),Y.resolve()}}class Fs{constructor(){this.overlays=new ue(B.comparator),this.lr=new Map}getOverlay(e,t){return Y.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Pt();return Y.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,s)=>{this.lt(e,t,s)})),Y.resolve()}removeOverlaysForBatchId(e,t,n){const s=this.lr.get(n);return void 0!==s&&(s.forEach((e=>this.overlays=this.overlays.remove(e))),this.lr.delete(n)),Y.resolve()}getOverlaysForCollection(e,t,n){const s=Pt(),r=t.length+1,i=new B(t.child("")),o=this.overlays.getIteratorFrom(i);for(;o.hasNext();){const e=o.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===r&&e.largestBatchId>n&&s.set(e.getKey(),e)}return Y.resolve(s)}getOverlaysForCollectionGroup(e,t,n,s){let r=new ue(((e,t)=>e-t));const i=this.overlays.getIterator();for(;i.hasNext();){const e=i.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=r.get(e.largestBatchId);null===t&&(t=Pt(),r=r.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Pt(),a=r.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach(((e,t)=>o.set(e,t))),!(o.size()>=s)););return Y.resolve(o)}lt(e,t,n){const s=this.overlays.get(n.key);if(null!==s){const e=this.lr.get(s.largestBatchId).delete(n.key);this.lr.set(s.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new An(t,n));let r=this.lr.get(t);void 0===r&&(r=$t(),this.lr.set(t,r)),this.lr.set(t,r.add(n.key))}}class Ps{constructor(){this.hr=new he(Us.Pr),this.Ir=new he(Us.Tr)}isEmpty(){return this.hr.isEmpty()}addReference(e,t){const n=new Us(e,t);this.hr=this.hr.add(n),this.Ir=this.Ir.add(n)}Er(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.dr(new Us(e,t))}Ar(e,t){e.forEach((e=>this.removeReference(e,t)))}Rr(e){const t=new B(new P([])),n=new Us(t,e),s=new Us(t,e+1),r=[];return this.Ir.forEachInRange([n,s],(e=>{this.dr(e),r.push(e.key)})),r}Vr(){this.hr.forEach((e=>this.dr(e)))}dr(e){this.hr=this.hr.delete(e),this.Ir=this.Ir.delete(e)}mr(e){const t=new B(new P([])),n=new Us(t,e),s=new Us(t,e+1);let r=$t();return this.Ir.forEachInRange([n,s],(e=>{r=r.add(e.key)})),r}containsKey(e){const t=new Us(e,0),n=this.hr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class Us{constructor(e,t){this.key=e,this.gr=t}static Pr(e,t){return B.comparator(e.key,t.key)||L(e.gr,t.gr)}static Tr(e,t){return L(e.gr,t.gr)||B.comparator(e.key,t.key)}}class qs{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.pr=1,this.yr=new he(Us.Pr)}checkEmpty(e){return Y.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,s){const r=this.pr;this.pr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const i=new Cn(r,t,n,s);this.mutationQueue.push(i);for(const o of s)this.yr=this.yr.add(new Us(o.key,r)),this.indexManager.addToCollectionParentIndex(e,o.key.path.popLast());return Y.resolve(i)}lookupMutationBatch(e,t){return Y.resolve(this.wr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,s=this.Sr(n),r=s<0?0:s;return Y.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return Y.resolve(0===this.mutationQueue.length?-1:this.pr-1)}getAllMutationBatches(e){return Y.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Us(t,0),s=new Us(t,Number.POSITIVE_INFINITY),r=[];return this.yr.forEachInRange([n,s],(e=>{const t=this.wr(e.gr);r.push(t)})),Y.resolve(r)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new he(L);return t.forEach((e=>{const t=new Us(e,0),s=new Us(e,Number.POSITIVE_INFINITY);this.yr.forEachInRange([t,s],(e=>{n=n.add(e.gr)}))})),Y.resolve(this.br(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,s=n.length+1;let r=n;B.isDocumentKey(r)||(r=r.child(""));const i=new Us(new B(r),0);let o=new he(L);return this.yr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===s&&(o=o.add(e.gr)),!0)}),i),Y.resolve(this.br(o))}br(e){const t=[];return e.forEach((e=>{const n=this.wr(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){w(0===this.Dr(t.batchId,"removed")),this.mutationQueue.shift();let n=this.yr;return Y.forEach(t.mutations,(s=>{const r=new Us(s.key,t.batchId);return n=n.delete(r),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)})).next((()=>{this.yr=n}))}Fn(e){}containsKey(e,t){const n=new Us(t,0),s=this.yr.firstAfterOrEqual(n);return Y.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,Y.resolve()}Dr(e,t){return this.Sr(e)}Sr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}wr(e){const t=this.Sr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Bs{constructor(e){this.Cr=e,this.docs=new ue(B.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,s=this.docs.get(n),r=s?s.size:0,i=this.Cr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-r,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return Y.resolve(n?n.document.mutableCopy():ze.newInvalidDocument(t))}getEntries(e,t){let n=Mt();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():ze.newInvalidDocument(e))})),Y.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let r=Mt();const i=t.path,o=new B(i.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!i.isPrefixOf(e.path))break;e.path.length>i.length+1||Q(K(o),n)<=0||(s.has(o.key)||bt(t,o))&&(r=r.insert(o.key,o.mutableCopy()))}return Y.resolve(r)}getAllFromCollectionGroup(e,t,n,s){y()}vr(e,t){return Y.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new zs(this)}getSize(e){return Y.resolve(this.size)}}class zs extends Ls{constructor(e){super(),this._r=e}applyChanges(e){const t=[];return this.changes.forEach(((n,s)=>{s.isValidDocument()?t.push(this._r.addEntry(e,s)):this._r.removeEntry(n)})),Y.waitFor(t)}getFromCache(e,t){return this._r.getEntry(e,t)}getAllFromCache(e,t){return this._r.getEntries(e,t)}}class $s{constructor(e){this.persistence=e,this.Fr=new xt((e=>ft(e)),mt),this.lastRemoteSnapshotVersion=O.min(),this.highestTargetId=0,this.Mr=0,this.Or=new Ps,this.targetCount=0,this.Nr=xs.On()}forEachTarget(e,t){return this.Fr.forEach(((e,n)=>t(n))),Y.resolve()}getLastRemoteSnapshotVersion(e){return Y.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Y.resolve(this.Mr)}allocateTargetId(e){return this.highestTargetId=this.Nr.next(),Y.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Mr&&(this.Mr=t),Y.resolve()}kn(e){this.Fr.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Nr=new xs(t),this.highestTargetId=t),e.sequenceNumber>this.Mr&&(this.Mr=e.sequenceNumber)}addTargetData(e,t){return this.kn(t),this.targetCount+=1,Y.resolve()}updateTargetData(e,t){return this.kn(t),Y.resolve()}removeTargetData(e,t){return this.Fr.delete(t.target),this.Or.Rr(t.targetId),this.targetCount-=1,Y.resolve()}removeTargets(e,t,n){let s=0;const r=[];return this.Fr.forEach(((i,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Fr.delete(i),r.push(this.removeMatchingKeysForTargetId(e,o.targetId)),s++)})),Y.waitFor(r).next((()=>s))}getTargetCount(e){return Y.resolve(this.targetCount)}getTargetData(e,t){const n=this.Fr.get(t)||null;return Y.resolve(n)}addMatchingKeys(e,t,n){return this.Or.Er(t,n),Y.resolve()}removeMatchingKeys(e,t,n){this.Or.Ar(t,n);const s=this.persistence.referenceDelegate,r=[];return s&&t.forEach((t=>{r.push(s.markPotentiallyOrphaned(e,t))})),Y.waitFor(r)}removeMatchingKeysForTargetId(e,t){return this.Or.Rr(t),Y.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Or.mr(t);return Y.resolve(n)}containsKey(e,t){return Y.resolve(this.Or.containsKey(t))}}class Ks{constructor(e,t){this.Br={},this.overlays={},this.Lr=new J(0),this.kr=!1,this.kr=!0,this.referenceDelegate=e(this),this.qr=new $s(this),this.indexManager=new ks,this.remoteDocumentCache=function(e){return new Bs(e)}((e=>this.referenceDelegate.Qr(e))),this.serializer=new As(t),this.Kr=new Os(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.kr=!1,Promise.resolve()}get started(){return this.kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Fs,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Br[e.toKey()];return n||(n=new qs(t,this.referenceDelegate),this.Br[e.toKey()]=n),n}getTargetCache(){return this.qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Kr}runTransaction(e,t,n){f("MemoryPersistence","Starting transaction:",e);const s=new Gs(this.Lr.next());return this.referenceDelegate.$r(),n(s).next((e=>this.referenceDelegate.Ur(s).next((()=>e)))).toPromise().then((e=>(s.raiseOnCommittedEvent(),e)))}Wr(e,t){return Y.or(Object.values(this.Br).map((n=>()=>n.containsKey(e,t))))}}class Gs extends H{constructor(e){super(),this.currentSequenceNumber=e}}class Qs{constructor(e){this.persistence=e,this.Gr=new Ps,this.zr=null}static jr(e){return new Qs(e)}get Hr(){if(this.zr)return this.zr;throw y()}addReference(e,t,n){return this.Gr.addReference(n,t),this.Hr.delete(n.toString()),Y.resolve()}removeReference(e,t,n){return this.Gr.removeReference(n,t),this.Hr.add(n.toString()),Y.resolve()}markPotentiallyOrphaned(e,t){return this.Hr.add(t.toString()),Y.resolve()}removeTarget(e,t){this.Gr.Rr(t.targetId).forEach((e=>this.Hr.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.Hr.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}$r(){this.zr=new Set}Ur(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Y.forEach(this.Hr,(n=>{const s=B.fromPath(n);return this.Jr(e,s).next((e=>{e||t.removeEntry(s,O.min())}))})).next((()=>(this.zr=null,t.apply(e))))}updateLimboDocument(e,t){return this.Jr(e,t).next((e=>{e?this.Hr.delete(t.toString()):this.Hr.add(t.toString())}))}Qr(e){return 0}Jr(e,t){return Y.or([()=>Y.resolve(this.Gr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Wr(e,t)])}}class js{constructor(e,t,n,s){this.targetId=e,this.fromCache=t,this.ki=n,this.qi=s}static Qi(e,t){let n=$t(),s=$t();for(const r of t.docChanges)switch(r.type){case 0:n=n.add(r.doc.key);break;case 1:s=s.add(r.doc.key)}return new js(e,t.fromCache,n,s)}}class Hs{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Ws{constructor(){this.Ki=!1,this.$i=!1,this.Ui=100,this.Wi=8}initialize(e,t){this.Gi=e,this.indexManager=t,this.Ki=!0}getDocumentsMatchingQuery(e,t,n,s){const r={result:null};return this.zi(e,t).next((e=>{r.result=e})).next((()=>{if(!r.result)return this.ji(e,t,s,n).next((e=>{r.result=e}))})).next((()=>{if(r.result)return;const n=new Hs;return this.Hi(e,t,n).next((s=>{if(r.result=s,this.$i)return this.Ji(e,t,n,s.size)}))})).next((()=>r.result))}Ji(e,t,n,s){return n.documentReadCount<this.Ui?(d()<=i.in.DEBUG&&f("QueryEngine","SDK will not create cache indexes for query:",Nt(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ui,"documents"),Y.resolve()):(d()<=i.in.DEBUG&&f("QueryEngine","Query:",Nt(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.Wi*s?(d()<=i.in.DEBUG&&f("QueryEngine","The SDK decides to create cache indexes for query:",Nt(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Tt(t))):Y.resolve())}zi(e,t){if(vt(t))return Y.resolve(null);let n=Tt(t);return this.indexManager.getIndexType(e,n).next((s=>0===s?null:(null!==t.limit&&1===s&&(t=Ct(t,null,"F"),n=Tt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((s=>{const r=$t(...s);return this.Gi.getDocuments(e,r).next((s=>this.indexManager.getMinOffset(e,n).next((n=>{const i=this.Yi(t,s);return this.Zi(t,i,r,n.readTime)?this.zi(e,Ct(t,null,"F")):this.Xi(e,i,t,n)}))))})))))}ji(e,t,n,s){return vt(t)||s.isEqual(O.min())?Y.resolve(null):this.Gi.getDocuments(e,n).next((r=>{const o=this.Yi(t,r);return this.Zi(t,o,n,s)?Y.resolve(null):(d()<=i.in.DEBUG&&f("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Nt(t)),this.Xi(e,o,t,$(s,-1)).next((e=>e)))}))}Yi(e,t){let n=new he(Dt(e));return t.forEach(((t,s)=>{bt(e,s)&&(n=n.add(s))})),n}Zi(e,t,n,s){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const r="F"===e.limitType?t.last():t.first();return!!r&&(r.hasPendingWrites||r.version.compareTo(s)>0)}Hi(e,t,n){return d()<=i.in.DEBUG&&f("QueryEngine","Using full collection scan to execute query:",Nt(t)),this.Gi.getDocumentsMatchingQuery(e,t,G.min(),n)}Xi(e,t,n,s){return this.Gi.getDocumentsMatchingQuery(e,n,s).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class Ys{constructor(e,t,n,s){this.persistence=e,this.es=t,this.serializer=s,this.ts=new ue(L),this.ns=new xt((e=>ft(e)),mt),this.rs=new Map,this.ss=e.getRemoteDocumentCache(),this.qr=e.getTargetCache(),this.Kr=e.getBundleCache(),this.os(n)}os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Vs(this.ss,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ss.setIndexManager(this.indexManager),this.es.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.ts)))}}function Xs(e,t,n,s){return new Ys(e,t,n,s)}async function Js(e,t){const n=v(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let s;return n.mutationQueue.getAllMutationBatches(e).next((r=>(s=r,n.os(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const r=[],i=[];let o=$t();for(const e of s){r.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next((e=>({_s:e,removedBatchIds:r,addedBatchIds:i})))}))}))}function Zs(e){const t=v(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.qr.getLastRemoteSnapshotVersion(e)))}function er(e,t,n){let s=$t(),r=$t();return n.forEach((e=>s=s.add(e))),t.getEntries(e,s).next((e=>{let s=Mt();return n.forEach(((n,i)=>{const o=e.get(n);i.isFoundDocument()!==o.isFoundDocument()&&(r=r.add(n)),i.isNoDocument()&&i.version.isEqual(O.min())?(t.removeEntry(n,i.readTime),s=s.insert(n,i)):!o.isValidDocument()||i.version.compareTo(o.version)>0||0===i.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(i),s=s.insert(n,i)):f("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",i.version)})),{us:s,cs:r}}))}function tr(e,t){const n=v(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function nr(e,t){const n=v(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let s;return n.qr.getTargetData(e,t).next((r=>r?(s=r,Y.resolve(s)):n.qr.allocateTargetId(e).next((r=>(s=new Ss(t,r,"TargetPurposeListen",e.currentSequenceNumber),n.qr.addTargetData(e,s).next((()=>s)))))))})).then((e=>{const s=n.ts.get(e.targetId);return(null===s||e.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(n.ts=n.ts.insert(e.targetId,e),n.ns.set(t,e.targetId)),e}))}async function sr(e,t,n){const s=v(e),r=s.ts.get(t),i=n?"readwrite":"readwrite-primary";try{n||await s.persistence.runTransaction("Release target",i,(e=>s.persistence.referenceDelegate.removeTarget(e,r)))}catch(e){if(!X(e))throw e;f("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}s.ts=s.ts.remove(t),s.ns.delete(r.target)}function rr(e,t,n){const s=v(e);let r=O.min(),i=$t();return s.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const s=v(e),r=s.ns.get(n);return void 0!==r?Y.resolve(s.ts.get(r)):s.qr.getTargetData(t,n)}(s,e,Tt(t)).next((t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,s.qr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{i=e}))})).next((()=>s.es.getDocumentsMatchingQuery(e,t,n?r:O.min(),n?i:$t()))).next((e=>(ir(s,kt(t),e),{documents:e,ls:i})))))}function ir(e,t,n){let s=e.rs.get(t)||O.min();n.forEach(((e,t)=>{t.readTime.compareTo(s)>0&&(s=t.readTime)})),e.rs.set(t,s)}class or{constructor(){this.activeTargetIds=Gt()}ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}As(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Es(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class ar{constructor(){this.eo=new or,this.no={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.eo.ds(e),this.no[e]||"not-current"}updateQueryState(e,t,n){this.no[e]=t}removeLocalQueryTarget(e){this.eo.As(e)}isLocalQueryTarget(e){return this.eo.activeTargetIds.has(e)}clearQueryState(e){delete this.no[e]}getAllActiveQueryTargets(){return this.eo.activeTargetIds}isActiveQueryTarget(e){return this.eo.activeTargetIds.has(e)}start(){return this.eo=new or,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class ur{ro(e){}shutdown(){}}class cr{constructor(){this.io=()=>this.so(),this.oo=()=>this._o(),this.ao=[],this.uo()}ro(e){this.ao.push(e)}shutdown(){window.removeEventListener("online",this.io),window.removeEventListener("offline",this.oo)}uo(){window.addEventListener("online",this.io),window.addEventListener("offline",this.oo)}so(){f("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ao)e(0)}_o(){f("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ao)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let lr=null;function hr(){return null===lr?lr=268435456+Math.round(2147483648*Math.random()):lr++,"0x"+lr.toString(16)}const dr={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class fr{constructor(e){this.co=e.co,this.lo=e.lo}ho(e){this.Po=e}Io(e){this.To=e}onMessage(e){this.Eo=e}close(){this.lo()}send(e){this.co(e)}Ao(){this.Po()}Ro(e){this.To(e)}Vo(e){this.Eo(e)}}const mr="WebChannelConnection";class gr extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.mo=t+"://"+e.host,this.fo=`projects/${n}/databases/${s}`,this.po="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${s}`}get yo(){return!1}wo(e,t,n,s,r){const i=hr(),o=this.So(e,t);f("RestConnection",`Sending RPC '${e}' ${i}:`,o,n);const a={"google-cloud-resource-prefix":this.fo,"x-goog-request-params":this.po};return this.bo(a,s,r),this.Do(e,o,a,n).then((t=>(f("RestConnection",`Received RPC '${e}' ${i}: `,t),t)),(t=>{throw g("RestConnection",`RPC '${e}' ${i} failed with error: `,t,"url: ",o,"request:",n),t}))}Co(e,t,n,s,r,i){return this.wo(e,t,n,s,r)}bo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+l,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))}So(e,t){const n=dr[e];return`${this.mo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Do(e,t,n,s){const r=hr();return new Promise(((i,o)=>{const u=new a.JJ;u.setWithCredentials(!0),u.listenOnce(a.tw.COMPLETE,(()=>{try{switch(u.getLastErrorCode()){case a.jK.NO_ERROR:const t=u.getResponseJson();f(mr,`XHR for RPC '${e}' ${r} received:`,JSON.stringify(t)),i(t);break;case a.jK.TIMEOUT:f(mr,`RPC '${e}' ${r} timed out`),o(new _(E.DEADLINE_EXCEEDED,"Request time out"));break;case a.jK.HTTP_ERROR:const n=u.getStatus();if(f(mr,`RPC '${e}' ${r} failed with status:`,n,"response text:",u.getResponseText()),n>0){let e=u.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(E).indexOf(t)>=0?t:E.UNKNOWN}(t.status);o(new _(e,t.message))}else o(new _(E.UNKNOWN,"Server responded with status "+u.getStatus()))}else o(new _(E.UNAVAILABLE,"Connection failed."));break;default:y()}}finally{f(mr,`RPC '${e}' ${r} completed.`)}}));const c=JSON.stringify(s);f(mr,`RPC '${e}' ${r} sending request:`,s),u.send(t,"POST",c,n,15)}))}vo(e,t,n){const s=hr(),r=[this.mo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=(0,a.UE)(),o=(0,a.FJ)(),u={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},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(u.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(u.useFetchStreams=!0),this.bo(u.initMessageHeaders,t,n),u.encodeInitMessageHeaders=!0;const l=r.join("");f(mr,`Creating RPC '${e}' stream ${s}: ${l}`,u);const h=i.createWebChannel(l,u);let d=!1,m=!1;const p=new fr({co:t=>{m?f(mr,`Not sending because RPC '${e}' stream ${s} is closed:`,t):(d||(f(mr,`Opening RPC '${e}' stream ${s} transport.`),h.open(),d=!0),f(mr,`RPC '${e}' stream ${s} sending:`,t),h.send(t))},lo:()=>h.close()}),y=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return y(h,a.ii.EventType.OPEN,(()=>{m||f(mr,`RPC '${e}' stream ${s} transport opened.`)})),y(h,a.ii.EventType.CLOSE,(()=>{m||(m=!0,f(mr,`RPC '${e}' stream ${s} transport closed`),p.Ro())})),y(h,a.ii.EventType.ERROR,(t=>{m||(m=!0,g(mr,`RPC '${e}' stream ${s} transport errored:`,t),p.Ro(new _(E.UNAVAILABLE,"The operation could not be completed")))})),y(h,a.ii.EventType.MESSAGE,(t=>{var n;if(!m){const r=t.data[0];w(!!r);const i=r,o=i.error||(null===(n=i[0])||void 0===n?void 0:n.error);if(o){f(mr,`RPC '${e}' stream ${s} received error:`,o);const t=o.status;let n=function(e){const t=bn[e];if(void 0!==t)return Rn(t)}(t),r=o.message;void 0===n&&(n=E.INTERNAL,r="Unknown error status: "+t+" with message "+o.message),m=!0,p.Ro(new _(n,r)),h.close()}else f(mr,`RPC '${e}' stream ${s} received:`,r),p.Vo(r)}})),y(o,a.ju.STAT_EVENT,(t=>{t.stat===a.kN.PROXY?f(mr,`RPC '${e}' stream ${s} detected buffering proxy`):t.stat===a.kN.NOPROXY&&f(mr,`RPC '${e}' stream ${s} detected no buffering proxy`)})),setTimeout((()=>{p.Ao()}),0),p}}function pr(){return"undefined"!=typeof document?document:null}function yr(e){return new Xn(e,!0)}class wr{constructor(e,t,n=1e3,s=1.5,r=6e4){this.si=e,this.timerId=t,this.Fo=n,this.Mo=s,this.xo=r,this.Oo=0,this.No=null,this.Bo=Date.now(),this.reset()}reset(){this.Oo=0}Lo(){this.Oo=this.xo}ko(e){this.cancel();const t=Math.floor(this.Oo+this.qo()),n=Math.max(0,Date.now()-this.Bo),s=Math.max(0,t-n);s>0&&f("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Oo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.No=this.si.enqueueAfterDelay(this.timerId,s,(()=>(this.Bo=Date.now(),e()))),this.Oo*=this.Mo,this.Oo<this.Fo&&(this.Oo=this.Fo),this.Oo>this.xo&&(this.Oo=this.xo)}Qo(){null!==this.No&&(this.No.skipDelay(),this.No=null)}cancel(){null!==this.No&&(this.No.cancel(),this.No=null)}qo(){return(Math.random()-.5)*this.Oo}}class vr{constructor(e,t,n,s,r,i,o,a){this.si=e,this.Ko=n,this.$o=s,this.connection=r,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Uo=0,this.Wo=null,this.Go=null,this.stream=null,this.zo=new wr(e,t)}jo(){return 1===this.state||5===this.state||this.Ho()}Ho(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Jo()}async stop(){this.jo()&&await this.close(0)}Yo(){this.state=0,this.zo.reset()}Zo(){this.Ho()&&null===this.Wo&&(this.Wo=this.si.enqueueAfterDelay(this.Ko,6e4,(()=>this.Xo())))}e_(e){this.t_(),this.stream.send(e)}async Xo(){if(this.Ho())return this.close(0)}t_(){this.Wo&&(this.Wo.cancel(),this.Wo=null)}n_(){this.Go&&(this.Go.cancel(),this.Go=null)}async close(e,t){this.t_(),this.n_(),this.zo.cancel(),this.Uo++,4!==e?this.zo.reset():t&&t.code===E.RESOURCE_EXHAUSTED?(m(t.toString()),m("Using maximum backoff delay to prevent overloading the backend."),this.zo.Lo()):t&&t.code===E.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.r_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Io(t)}r_(){}auth(){this.state=1;const e=this.i_(this.Uo),t=this.Uo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.Uo===t&&this.s_(e,n)}),(t=>{e((()=>{const e=new _(E.UNKNOWN,"Fetching auth token failed: "+t.message);return this.o_(e)}))}))}s_(e,t){const n=this.i_(this.Uo);this.stream=this.__(e,t),this.stream.ho((()=>{n((()=>(this.state=2,this.Go=this.si.enqueueAfterDelay(this.$o,1e4,(()=>(this.Ho()&&(this.state=3),Promise.resolve()))),this.listener.ho())))})),this.stream.Io((e=>{n((()=>this.o_(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}Jo(){this.state=5,this.zo.ko((async()=>{this.state=0,this.start()}))}o_(e){return f("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}i_(e){return t=>{this.si.enqueueAndForget((()=>this.Uo===e?t():(f("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class Er extends vr{constructor(e,t,n,s,r,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,s,i),this.serializer=r}__(e,t){return this.connection.vo("Listen",e,t)}onMessage(e){this.zo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const s=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:y()}(t.targetChange.targetChangeType||"NO_CHANGE"),r=t.targetChange.targetIds||[],i=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),ge.fromBase64String(t||"")):(w(void 0===t||t instanceof Uint8Array),ge.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?E.UNKNOWN:Rn(e.code);return new _(t,e.message||"")}(o);n=new $n(s,r,i,a||null)}else if("documentChange"in t){t.documentChange;const s=t.documentChange;s.document,s.document.name,s.document.updateTime;const r=os(e,s.document.name),i=ns(s.document.updateTime),o=s.document.createTime?ns(s.document.createTime):O.min(),a=new qe({mapValue:{fields:s.document.fields}}),u=ze.newFoundDocument(r,i,o,a),c=s.targetIds||[],l=s.removedTargetIds||[];n=new Bn(c,l,u.key,u)}else if("documentDelete"in t){t.documentDelete;const s=t.documentDelete;s.document;const r=os(e,s.document),i=s.readTime?ns(s.readTime):O.min(),o=ze.newNoDocument(r,i),a=s.removedTargetIds||[];n=new Bn([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const s=t.documentRemove;s.document;const r=os(e,s.document),i=s.removedTargetIds||[];n=new Bn([],i,r,null)}else{if(!("filter"in t))return y();{t.filter;const e=t.filter;e.targetId;const{count:s=0,unchangedNames:r}=e,i=new Nn(s,r),o=e.targetId;n=new zn(o,i)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return O.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?O.min():t.readTime?ns(t.readTime):O.min()}(e);return this.listener.a_(t,n)}u_(e){const t={};t.database=cs(this.serializer),t.addTarget=function(e,t){let n;const s=t.target;if(n=gt(s)?{documents:fs(e,s)}:{query:ms(e,s)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=es(e,t.resumeToken);const s=Jn(e,t.expectedCount);null!==s&&(n.expectedCount=s)}else if(t.snapshotVersion.compareTo(O.min())>0){n.readTime=Zn(e,t.snapshotVersion.toTimestamp());const s=Jn(e,t.expectedCount);null!==s&&(n.expectedCount=s)}return n}(this.serializer,e);const n=function(e,t){const 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 y()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.e_(t)}c_(e){const t={};t.database=cs(this.serializer),t.removeTarget=e,this.e_(t)}}class _r extends vr{constructor(e,t,n,s,r,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,s,i),this.serializer=r,this.l_=!1}get h_(){return this.l_}start(){this.l_=!1,this.lastStreamToken=void 0,super.start()}r_(){this.l_&&this.P_([])}__(e,t){return this.connection.vo("Write",e,t)}onMessage(e){if(w(!!e.streamToken),this.lastStreamToken=e.streamToken,this.l_){this.zo.reset();const t=function(e,t){return e&&e.length>0?(w(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?ns(e.updateTime):ns(t);return n.isEqual(O.min())&&(n=ns(t)),new un(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=ns(e.commitTime);return this.listener.I_(n,t)}return w(!e.writeResults||0===e.writeResults.length),this.l_=!0,this.listener.T_()}E_(){const e={};e.database=cs(this.serializer),this.e_(e)}P_(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>ds(this.serializer,e)))};this.e_(t)}}class Tr extends class{}{constructor(e,t,n,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=s,this.d_=!1}A_(){if(this.d_)throw new _(E.FAILED_PRECONDITION,"The client has already been terminated.")}wo(e,t,n){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,r])=>this.connection.wo(e,t,n,s,r))).catch((e=>{throw"FirebaseError"===e.name?(e.code===E.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new _(E.UNKNOWN,e.toString())}))}Co(e,t,n,s){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,i])=>this.connection.Co(e,t,n,r,i,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===E.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new _(E.UNKNOWN,e.toString())}))}terminate(){this.d_=!0}}class Ir{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.V_=0,this.m_=null,this.f_=!0}g_(){0===this.V_&&(this.p_("Unknown"),this.m_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.m_=null,this.y_("Backend didn't respond within 10 seconds."),this.p_("Offline"),Promise.resolve()))))}w_(e){"Online"===this.state?this.p_("Unknown"):(this.V_++,this.V_>=1&&(this.S_(),this.y_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.p_("Offline")))}set(e){this.S_(),this.V_=0,"Online"===e&&(this.f_=!1),this.p_(e)}p_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}y_(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.f_?(m(t),this.f_=!1):f("OnlineStateTracker",t)}S_(){null!==this.m_&&(this.m_.cancel(),this.m_=null)}}class Cr{constructor(e,t,n,s,r){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.b_=[],this.D_=new Map,this.C_=new Set,this.v_=[],this.F_=r,this.F_.ro((e=>{n.enqueueAndForget((async()=>{Lr(this)&&(f("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=v(e);t.C_.add(4),await Ar(t),t.M_.set("Unknown"),t.C_.delete(4),await Sr(t)}(this))}))})),this.M_=new Ir(n,s)}}async function Sr(e){if(Lr(e))for(const t of e.v_)await t(!0)}async function Ar(e){for(const t of e.v_)await t(!1)}function Nr(e,t){const n=v(e);n.D_.has(t.targetId)||(n.D_.set(t.targetId,t),xr(n)?Rr(n):Xr(n).Ho()&&kr(n,t))}function br(e,t){const n=v(e),s=Xr(n);n.D_.delete(t),s.Ho()&&Dr(n,t),0===n.D_.size&&(s.Ho()?s.Zo():Lr(n)&&n.M_.set("Unknown"))}function kr(e,t){if(e.x_.Oe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(O.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Xr(e).u_(t)}function Dr(e,t){e.x_.Oe(t),Xr(e).c_(t)}function Rr(e){e.x_=new Gn({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),_t:t=>e.D_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Xr(e).start(),e.M_.g_()}function xr(e){return Lr(e)&&!Xr(e).jo()&&e.D_.size>0}function Lr(e){return 0===v(e).C_.size}function Mr(e){e.x_=void 0}async function Vr(e){e.D_.forEach(((t,n)=>{kr(e,t)}))}async function Or(e,t){Mr(e),xr(e)?(e.M_.w_(t),Rr(e)):e.M_.set("Unknown")}async function Fr(e,t,n){if(e.M_.set("Online"),t instanceof $n&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const s of t.targetIds)e.D_.has(s)&&(await e.remoteSyncer.rejectListen(s,n),e.D_.delete(s),e.x_.removeTarget(s))}(e,t)}catch(n){f("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Pr(e,n)}else if(t instanceof Bn?e.x_.$e(t):t instanceof zn?e.x_.Je(t):e.x_.Ge(t),!n.isEqual(O.min()))try{const t=await Zs(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.x_.it(t);return n.targetChanges.forEach(((n,s)=>{if(n.resumeToken.approximateByteSize()>0){const r=e.D_.get(s);r&&e.D_.set(s,r.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const s=e.D_.get(t);if(!s)return;e.D_.set(t,s.withResumeToken(ge.EMPTY_BYTE_STRING,s.snapshotVersion)),Dr(e,t);const r=new Ss(s.target,t,n,s.sequenceNumber);kr(e,r)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){f("RemoteStore","Failed to raise snapshot:",t),await Pr(e,t)}}async function Pr(e,t,n){if(!X(t))throw t;e.C_.add(1),await Ar(e),e.M_.set("Offline"),n||(n=()=>Zs(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{f("RemoteStore","Retrying IndexedDB access"),await n(),e.C_.delete(1),await Sr(e)}))}function Ur(e,t){return t().catch((n=>Pr(e,n,t)))}async function qr(e){const t=v(e),n=Jr(t);let s=t.b_.length>0?t.b_[t.b_.length-1].batchId:-1;for(;Br(t);)try{const e=await tr(t.localStore,s);if(null===e){0===t.b_.length&&n.Zo();break}s=e.batchId,zr(t,e)}catch(e){await Pr(t,e)}$r(t)&&Kr(t)}function Br(e){return Lr(e)&&e.b_.length<10}function zr(e,t){e.b_.push(t);const n=Jr(e);n.Ho()&&n.h_&&n.P_(t.mutations)}function $r(e){return Lr(e)&&!Jr(e).jo()&&e.b_.length>0}function Kr(e){Jr(e).start()}async function Gr(e){Jr(e).E_()}async function Qr(e){const t=Jr(e);for(const n of e.b_)t.P_(n.mutations)}async function jr(e,t,n){const s=e.b_.shift(),r=Sn.from(s,t,n);await Ur(e,(()=>e.remoteSyncer.applySuccessfulWrite(r))),await qr(e)}async function Hr(e,t){t&&Jr(e).h_&&await async function(e,t){if(function(e){return Dn(e)&&e!==E.ABORTED}(t.code)){const n=e.b_.shift();Jr(e).Yo(),await Ur(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await qr(e)}}(e,t),$r(e)&&Kr(e)}async function Wr(e,t){const n=v(e);n.asyncQueue.verifyOperationInProgress(),f("RemoteStore","RemoteStore received new credentials");const s=Lr(n);n.C_.add(3),await Ar(n),s&&n.M_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.C_.delete(3),await Sr(n)}async function Yr(e,t){const n=v(e);t?(n.C_.delete(2),await Sr(n)):t||(n.C_.add(2),await Ar(n),n.M_.set("Unknown"))}function Xr(e){return e.O_||(e.O_=function(e,t,n){const s=v(e);return s.A_(),new Er(t,s.connection,s.authCredentials,s.appCheckCredentials,s.serializer,n)}(e.datastore,e.asyncQueue,{ho:Vr.bind(null,e),Io:Or.bind(null,e),a_:Fr.bind(null,e)}),e.v_.push((async t=>{t?(e.O_.Yo(),xr(e)?Rr(e):e.M_.set("Unknown")):(await e.O_.stop(),Mr(e))}))),e.O_}function Jr(e){return e.N_||(e.N_=function(e,t,n){const s=v(e);return s.A_(),new _r(t,s.connection,s.authCredentials,s.appCheckCredentials,s.serializer,n)}(e.datastore,e.asyncQueue,{ho:Gr.bind(null,e),Io:Hr.bind(null,e),T_:Qr.bind(null,e),I_:jr.bind(null,e)}),e.v_.push((async t=>{t?(e.N_.Yo(),await qr(e)):(await e.N_.stop(),e.b_.length>0&&(f("RemoteStore",`Stopping write stream with ${e.b_.length} pending writes`),e.b_=[]))}))),e.N_}class Zr{constructor(e,t,n,s,r){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=s,this.removalCallback=r,this.deferred=new T,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,s,r){const i=Date.now()+n,o=new Zr(e,t,i,s,r);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new _(E.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 ei(e,t){if(m("AsyncQueue",`${t}: ${e}`),X(e))return new _(E.UNAVAILABLE,`${t}: ${e}`);throw e}class ti{constructor(e){this.comparator=e?(t,n)=>e(t,n)||B.comparator(t.key,n.key):(e,t)=>B.comparator(e.key,t.key),this.keyedMap=Ot(),this.sortedSet=new ue(this.comparator)}static emptySet(e){return new ti(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const 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){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof ti))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,s=n.getNext().key;if(!e.isEqual(s))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new ti;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class ni{constructor(){this.B_=new ue(B.comparator)}track(e){const t=e.doc.key,n=this.B_.get(t);n?0!==e.type&&3===n.type?this.B_=this.B_.insert(t,e):3===e.type&&1!==n.type?this.B_=this.B_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.B_=this.B_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.B_=this.B_.remove(t):1===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):y():this.B_=this.B_.insert(t,e)}L_(){const e=[];return this.B_.inorderTraversal(((t,n)=>{e.push(n)})),e}}class si{constructor(e,t,n,s,r,i,o,a,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=r,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,s,r){const i=[];return t.forEach((e=>{i.push({type:0,doc:e})})),new si(e,t,ti.emptySet(t),i,n,s,!0,!1,r)}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)&&St(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(t[s].type!==n[s].type||!t[s].doc.isEqual(n[s].doc))return!1;return!0}}class ri{constructor(){this.k_=void 0,this.listeners=[]}}class ii{constructor(){this.queries=new xt((e=>At(e)),St),this.onlineState="Unknown",this.q_=new Set}}async function oi(e,t){const n=v(e),s=t.query;let r=!1,i=n.queries.get(s);if(i||(r=!0,i=new ri),r)try{i.k_=await n.onListen(s)}catch(e){const n=ei(e,`Initialization of query '${Nt(t.query)}' failed`);return void t.onError(n)}n.queries.set(s,i),i.listeners.push(t),t.Q_(n.onlineState),i.k_&&t.K_(i.k_)&&li(n)}async function ai(e,t){const n=v(e),s=t.query;let r=!1;const i=n.queries.get(s);if(i){const e=i.listeners.indexOf(t);e>=0&&(i.listeners.splice(e,1),r=0===i.listeners.length)}if(r)return n.queries.delete(s),n.onUnlisten(s)}function ui(e,t){const n=v(e);let s=!1;for(const r of t){const e=r.query,t=n.queries.get(e);if(t){for(const e of t.listeners)e.K_(r)&&(s=!0);t.k_=r}}s&&li(n)}function ci(e,t,n){const s=v(e),r=s.queries.get(t);if(r)for(const i of r.listeners)i.onError(n);s.queries.delete(t)}function li(e){e.q_.forEach((e=>{e.next()}))}class hi{constructor(e,t,n){this.query=e,this.U_=t,this.W_=!1,this.G_=null,this.onlineState="Unknown",this.options=n||{}}K_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new si(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.W_?this.z_(e)&&(this.U_.next(e),t=!0):this.j_(e,this.onlineState)&&(this.H_(e),t=!0),this.G_=e,t}onError(e){this.U_.error(e)}Q_(e){this.onlineState=e;let t=!1;return this.G_&&!this.W_&&this.j_(this.G_,e)&&(this.H_(this.G_),t=!0),t}j_(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.J_||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}z_(e){if(e.docChanges.length>0)return!0;const t=this.G_&&this.G_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}H_(e){e=si.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.W_=!0,this.U_.next(e)}}class di{constructor(e){this.key=e}}class fi{constructor(e){this.key=e}}class mi{constructor(e,t){this.query=e,this.ia=t,this.sa=null,this.hasCachedResults=!1,this.current=!1,this.oa=$t(),this.mutatedKeys=$t(),this._a=Dt(e),this.aa=new ti(this._a)}get ua(){return this.ia}ca(e,t){const n=t?t.la:new ni,s=t?t.aa:this.aa;let r=t?t.mutatedKeys:this.mutatedKeys,i=s,o=!1;const a="F"===this.query.limitType&&s.size===this.query.limit?s.last():null,u="L"===this.query.limitType&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal(((e,t)=>{const c=s.get(e),l=bt(this.query,t)?t:null,h=!!c&&this.mutatedKeys.has(c.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;c&&l?c.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.ha(c,l)||(n.track({type:2,doc:l}),f=!0,(a&&this._a(l,a)>0||u&&this._a(l,u)<0)&&(o=!0)):!c&&l?(n.track({type:0,doc:l}),f=!0):c&&!l&&(n.track({type:1,doc:c}),f=!0,(a||u)&&(o=!0)),f&&(l?(i=i.add(l),r=d?r.add(e):r.delete(e)):(i=i.delete(e),r=r.delete(e)))})),null!==this.query.limit)for(;i.size>this.query.limit;){const e="F"===this.query.limitType?i.last():i.first();i=i.delete(e.key),r=r.delete(e.key),n.track({type:1,doc:e})}return{aa:i,la:n,Zi:o,mutatedKeys:r}}ha(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,s){const r=this.aa;this.aa=e.aa,this.mutatedKeys=e.mutatedKeys;const i=e.la.L_();i.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return y()}};return n(e)-n(t)}(e.type,t.type)||this._a(e.doc,t.doc))),this.Pa(n),s=null!=s&&s;const o=t&&!s?this.Ia():[],a=0===this.oa.size&&this.current&&!s?1:0,u=a!==this.sa;return this.sa=a,0!==i.length||u?{snapshot:new si(this.query,e.aa,r,i,e.mutatedKeys,0===a,u,!1,!!n&&n.resumeToken.approximateByteSize()>0),Ta:o}:{Ta:o}}Q_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({aa:this.aa,la:new ni,mutatedKeys:this.mutatedKeys,Zi:!1},!1)):{Ta:[]}}Ea(e){return!this.ia.has(e)&&!!this.aa.has(e)&&!this.aa.get(e).hasLocalMutations}Pa(e){e&&(e.addedDocuments.forEach((e=>this.ia=this.ia.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.ia=this.ia.delete(e))),this.current=e.current)}Ia(){if(!this.current)return[];const e=this.oa;this.oa=$t(),this.aa.forEach((e=>{this.Ea(e.key)&&(this.oa=this.oa.add(e.key))}));const t=[];return e.forEach((e=>{this.oa.has(e)||t.push(new fi(e))})),this.oa.forEach((n=>{e.has(n)||t.push(new di(n))})),t}da(e){this.ia=e.ls,this.oa=$t();const t=this.ca(e.documents);return this.applyChanges(t,!0)}Aa(){return si.fromInitialDocuments(this.query,this.aa,this.mutatedKeys,0===this.sa,this.hasCachedResults)}}class gi{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class pi{constructor(e){this.key=e,this.Ra=!1}}class yi{constructor(e,t,n,s,r,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=s,this.currentUser=r,this.maxConcurrentLimboResolutions=i,this.Va={},this.ma=new xt((e=>At(e)),St),this.fa=new Map,this.ga=new Set,this.pa=new ue(B.comparator),this.ya=new Map,this.wa=new Ps,this.Sa={},this.ba=new Map,this.Da=xs.Nn(),this.onlineState="Unknown",this.Ca=void 0}get isPrimaryClient(){return!0===this.Ca}}async function wi(e,t){const n=Oi(e);let s,r;const i=n.ma.get(t);if(i)s=i.targetId,n.sharedClientState.addLocalQueryTarget(s),r=i.view.Aa();else{const e=await nr(n.localStore,Tt(t)),i=n.sharedClientState.addLocalQueryTarget(e.targetId);s=e.targetId,r=await vi(n,t,s,"current"===i,e.resumeToken),n.isPrimaryClient&&Nr(n.remoteStore,e)}return r}async function vi(e,t,n,s,r){e.va=(t,n,s)=>async function(e,t,n,s){let r=t.view.ca(n);r.Zi&&(r=await rr(e.localStore,t.query,!1).then((({documents:e})=>t.view.ca(e,r))));const i=s&&s.targetChanges.get(t.targetId),o=s&&null!=s.targetMismatches.get(t.targetId),a=t.view.applyChanges(r,e.isPrimaryClient,i,o);return Di(e,t.targetId,a.Ta),a.snapshot}(e,t,n,s);const i=await rr(e.localStore,t,!0),o=new mi(t,i.ls),a=o.ca(i.documents),u=qn.createSynthesizedTargetChangeForCurrentChange(n,s&&"Offline"!==e.onlineState,r),c=o.applyChanges(a,e.isPrimaryClient,u);Di(e,n,c.Ta);const l=new gi(t,n,o);return e.ma.set(t,l),e.fa.has(n)?e.fa.get(n).push(t):e.fa.set(n,[t]),c.snapshot}async function Ei(e,t){const n=v(e),s=n.ma.get(t),r=n.fa.get(s.targetId);if(r.length>1)return n.fa.set(s.targetId,r.filter((e=>!St(e,t)))),void n.ma.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await sr(n.localStore,s.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(s.targetId),br(n.remoteStore,s.targetId),bi(n,s.targetId)})).catch(W)):(bi(n,s.targetId),await sr(n.localStore,s.targetId,!0))}async function _i(e,t){const n=v(e);try{const e=await function(e,t){const n=v(e),s=t.snapshotVersion;let r=n.ts;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const i=n.ss.newChangeBuffer({trackRemovals:!0});r=n.ts;const o=[];t.targetChanges.forEach(((i,a)=>{const u=r.get(a);if(!u)return;o.push(n.qr.removeMatchingKeys(e,i.removedDocuments,a).next((()=>n.qr.addMatchingKeys(e,i.addedDocuments,a))));let c=u.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?c=c.withResumeToken(ge.EMPTY_BYTE_STRING,O.min()).withLastLimboFreeSnapshotVersion(O.min()):i.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(i.resumeToken,s)),r=r.insert(a,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(u,c,i)&&o.push(n.qr.updateTargetData(e,c))}));let a=Mt(),u=$t();if(t.documentUpdates.forEach((s=>{t.resolvedLimboDocuments.has(s)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,s))})),o.push(er(e,i,t.documentUpdates).next((e=>{a=e.us,u=e.cs}))),!s.isEqual(O.min())){const t=n.qr.getLastRemoteSnapshotVersion(e).next((t=>n.qr.setTargetsMetadata(e,e.currentSequenceNumber,s)));o.push(t)}return Y.waitFor(o).next((()=>i.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,a,u))).next((()=>a))})).then((e=>(n.ts=r,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const s=n.ya.get(t);s&&(w(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?s.Ra=!0:e.modifiedDocuments.size>0?w(s.Ra):e.removedDocuments.size>0&&(w(s.Ra),s.Ra=!1))})),await Li(n,e,t)}catch(e){await W(e)}}function Ti(e,t,n){const s=v(e);if(s.isPrimaryClient&&0===n||!s.isPrimaryClient&&1===n){const e=[];s.ma.forEach(((n,s)=>{const r=s.view.Q_(t);r.snapshot&&e.push(r.snapshot)})),function(e,t){const n=v(e);n.onlineState=t;let s=!1;n.queries.forEach(((e,n)=>{for(const r of n.listeners)r.Q_(t)&&(s=!0)})),s&&li(n)}(s.eventManager,t),e.length&&s.Va.a_(e),s.onlineState=t,s.isPrimaryClient&&s.sharedClientState.setOnlineState(t)}}async function Ii(e,t,n){const s=v(e);s.sharedClientState.updateQueryState(t,"rejected",n);const r=s.ya.get(t),i=r&&r.key;if(i){let e=new ue(B.comparator);e=e.insert(i,ze.newNoDocument(i,O.min()));const n=$t().add(i),r=new Un(O.min(),new Map,new ue(L),e,n);await _i(s,r),s.pa=s.pa.remove(i),s.ya.delete(t),xi(s)}else await sr(s.localStore,t,!1).then((()=>bi(s,t,n))).catch(W)}async function Ci(e,t){const n=v(e),s=t.batch.batchId;try{const e=await function(e,t){const n=v(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const s=t.batch.keys(),r=n.ss.newChangeBuffer({trackRemovals:!0});return function(e,t,n,s){const r=n.batch,i=r.keys();let o=Y.resolve();return i.forEach((e=>{o=o.next((()=>s.getEntry(t,e))).next((t=>{const i=n.docVersions.get(e);w(null!==i),t.version.compareTo(i)<0&&(r.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),s.addEntry(t)))}))})),o.next((()=>e.mutationQueue.removeMutationBatch(t,r)))}(n,e,t,r).next((()=>r.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,s,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=$t();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,s)))}))}(n.localStore,t);Ni(n,s,null),Ai(n,s),n.sharedClientState.updateMutationState(s,"acknowledged"),await Li(n,e)}catch(e){await W(e)}}async function Si(e,t,n){const s=v(e);try{const e=await function(e,t){const n=v(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let s;return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(w(null!==t),s=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,s,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,s))).next((()=>n.localDocuments.getDocuments(e,s)))}))}(s.localStore,t);Ni(s,t,n),Ai(s,t),s.sharedClientState.updateMutationState(t,"rejected",n),await Li(s,e)}catch(n){await W(n)}}function Ai(e,t){(e.ba.get(t)||[]).forEach((e=>{e.resolve()})),e.ba.delete(t)}function Ni(e,t,n){const s=v(e);let r=s.Sa[s.currentUser.toKey()];if(r){const e=r.get(t);e&&(n?e.reject(n):e.resolve(),r=r.remove(t)),s.Sa[s.currentUser.toKey()]=r}}function bi(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const s of e.fa.get(t))e.ma.delete(s),n&&e.Va.Fa(s,n);e.fa.delete(t),e.isPrimaryClient&&e.wa.Rr(t).forEach((t=>{e.wa.containsKey(t)||ki(e,t)}))}function ki(e,t){e.ga.delete(t.path.canonicalString());const n=e.pa.get(t);null!==n&&(br(e.remoteStore,n),e.pa=e.pa.remove(t),e.ya.delete(n),xi(e))}function Di(e,t,n){for(const s of n)s instanceof di?(e.wa.addReference(s.key,t),Ri(e,s)):s instanceof fi?(f("SyncEngine","Document no longer in limbo: "+s.key),e.wa.removeReference(s.key,t),e.wa.containsKey(s.key)||ki(e,s.key)):y()}function Ri(e,t){const n=t.key,s=n.path.canonicalString();e.pa.get(n)||e.ga.has(s)||(f("SyncEngine","New document in limbo: "+n),e.ga.add(s),xi(e))}function xi(e){for(;e.ga.size>0&&e.pa.size<e.maxConcurrentLimboResolutions;){const t=e.ga.values().next().value;e.ga.delete(t);const n=new B(P.fromString(t)),s=e.Da.next();e.ya.set(s,new pi(n)),e.pa=e.pa.insert(n,s),Nr(e.remoteStore,new Ss(Tt(wt(n.path)),s,"TargetPurposeLimboResolution",J._e))}}async function Li(e,t,n){const s=v(e),r=[],i=[],o=[];s.ma.isEmpty()||(s.ma.forEach(((e,a)=>{o.push(s.va(a,t,n).then((e=>{if((e||n)&&s.isPrimaryClient&&s.sharedClientState.updateQueryState(a.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){r.push(e);const t=js.Qi(a.targetId,e);i.push(t)}})))})),await Promise.all(o),s.Va.a_(r),await async function(e,t){const n=v(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>Y.forEach(t,(t=>Y.forEach(t.ki,(s=>n.persistence.referenceDelegate.addReference(e,t.targetId,s))).next((()=>Y.forEach(t.qi,(s=>n.persistence.referenceDelegate.removeReference(e,t.targetId,s)))))))))}catch(e){if(!X(e))throw e;f("LocalStore","Failed to update sequence numbers: "+e)}for(const s of t){const e=s.targetId;if(!s.fromCache){const t=n.ts.get(e),s=t.snapshotVersion,r=t.withLastLimboFreeSnapshotVersion(s);n.ts=n.ts.insert(e,r)}}}(s.localStore,i))}async function Mi(e,t){const n=v(e);if(!n.currentUser.isEqual(t)){f("SyncEngine","User change. New user:",t.toKey());const e=await Js(n.localStore,t);n.currentUser=t,function(e,t){e.ba.forEach((e=>{e.forEach((e=>{e.reject(new _(E.CANCELLED,t))}))})),e.ba.clear()}(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Li(n,e._s)}}function Vi(e,t){const n=v(e),s=n.ya.get(t);if(s&&s.Ra)return $t().add(s.key);{let e=$t();const s=n.fa.get(t);if(!s)return e;for(const t of s){const s=n.ma.get(t);e=e.unionWith(s.view.ua)}return e}}function Oi(e){const t=v(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=_i.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Vi.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Ii.bind(null,t),t.Va.a_=ui.bind(null,t.eventManager),t.Va.Fa=ci.bind(null,t.eventManager),t}function Fi(e){const t=v(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Ci.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Si.bind(null,t),t}class Pi{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=yr(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return Xs(this.persistence,new Ws,e.initialUser,this.serializer)}createPersistence(e){return new Ks(Qs.jr,this.serializer)}createSharedClientState(e){return new ar}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class Ui{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=>Ti(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Mi.bind(null,this.syncEngine),await Yr(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ii}createDatastore(e){const t=yr(e.databaseInfo.databaseId),n=function(e){return new gr(e)}(e.databaseInfo);return function(e,t,n,s){return new Tr(e,t,n,s)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,s,r){return new Cr(e,t,n,s,r)}(this.localStore,this.datastore,e.asyncQueue,(e=>Ti(this.syncEngine,e,0)),cr.D()?new cr:new ur)}createSyncEngine(e,t){return function(e,t,n,s,r,i,o){const a=new yi(e,t,n,s,r,i);return o&&(a.Ca=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=v(e);f("RemoteStore","RemoteStore shutting down."),t.C_.add(5),await Ar(t),t.F_.shutdown(),t.M_.set("Unknown")}(this.remoteStore)}}class qi{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Oa(this.observer.next,e)}error(e){this.observer.error?this.Oa(this.observer.error,e):m("Uncaught Error in snapshot listener:",e.toString())}Na(){this.muted=!0}Oa(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class Bi{constructor(e,t,n,s){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=c.UNAUTHENTICATED,this.clientId=x.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{f("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(f("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new _(E.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new T;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(t){const n=ei(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function zi(e,t){e.asyncQueue.verifyOperationInProgress(),f("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let s=n.initialUser;e.setCredentialChangeListener((async e=>{s.isEqual(e)||(await Js(t.localStore,e),s=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function $i(e,t){e.asyncQueue.verifyOperationInProgress();const n=await Gi(e);f("FirestoreClient","Initializing OnlineComponentProvider");const s=await e.getConfiguration();await t.initialize(n,s),e.setCredentialChangeListener((e=>Wr(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Wr(t.remoteStore,n))),e._onlineComponents=t}function Ki(e){return"FirebaseError"===e.name?e.code===E.FAILED_PRECONDITION||e.code===E.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function Gi(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){f("FirestoreClient","Using user provided OfflineComponentProvider");try{await zi(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!Ki(n))throw n;g("Error using user provided cache. Falling back to memory cache: "+n),await zi(e,new Pi)}}else f("FirestoreClient","Using default OfflineComponentProvider"),await zi(e,new Pi);return e._offlineComponents}async function Qi(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(f("FirestoreClient","Using user provided OnlineComponentProvider"),await $i(e,e._uninitializedComponentsProvider._online)):(f("FirestoreClient","Using default OnlineComponentProvider"),await $i(e,new Ui))),e._onlineComponents}function ji(e){return Qi(e).then((e=>e.syncEngine))}async function Hi(e){const t=await Qi(e),n=t.eventManager;return n.onListen=wi.bind(null,t.syncEngine),n.onUnlisten=Ei.bind(null,t.syncEngine),n}function Wi(e,t,n={}){const s=new T;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,s,r){const i=new qi({next:n=>{t.enqueueAndForget((()=>ai(e,o))),n.fromCache&&"server"===s.source?r.reject(new _(E.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.)')):r.resolve(n)},error:e=>r.reject(e)}),o=new hi(n,i,{includeMetadataChanges:!0,J_:!0});return oi(e,o)}(await Hi(e),e.asyncQueue,t,n,s))),s.promise}function Yi(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Xi=new Map;function Ji(e,t,n){if(!n)throw new _(E.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Zi(e){if(!B.isDocumentKey(e))throw new _(E.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function eo(e){if(B.isDocumentKey(e))throw new _(E.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function to(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";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":y()}function no(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new _(E.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=to(e);throw new _(E.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}class so{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new _(E.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new _(E.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,s){if(!0===t&&!0===s)throw new _(E.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=Yi(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new _(E.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new _(E.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new _(E.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class ro{constructor(e,t,n,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new so({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new _(E.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new _(E.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 so(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new C;switch(e.type){case"firstParty":return new b(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new _(E.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Xi.get(e);t&&(f("ComponentProvider","Removing Datastore"),Xi.delete(e),t.terminate())}(this),Promise.resolve()}}class io{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new io(this.firestore,e,this._query)}}class oo{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 ao(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new oo(this.firestore,e,this._key)}}class ao extends io{constructor(e,t,n){super(e,t,wt(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new oo(this.firestore,null,new B(e))}withConverter(e){return new ao(this.firestore,e,this._path)}}function uo(e,t,...n){if(e=(0,o.m9)(e),Ji("collection","path",t),e instanceof ro){const s=P.fromString(t,...n);return eo(s),new ao(e,null,s)}{if(!(e instanceof oo||e instanceof ao))throw new _(E.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=e._path.child(P.fromString(t,...n));return eo(s),new ao(e.firestore,null,s)}}class co{constructor(){this.Ja=Promise.resolve(),this.Ya=[],this.Za=!1,this.Xa=[],this.eu=null,this.tu=!1,this.nu=!1,this.ru=[],this.zo=new wr(this,"async_queue_retry"),this.iu=()=>{const e=pr();e&&f("AsyncQueue","Visibility state changed to "+e.visibilityState),this.zo.Qo()};const e=pr();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.iu)}get isShuttingDown(){return this.Za}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.su(),this.ou(e)}enterRestrictedMode(e){if(!this.Za){this.Za=!0,this.nu=e||!1;const t=pr();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.iu)}}enqueue(e){if(this.su(),this.Za)return new Promise((()=>{}));const t=new T;return this.ou((()=>this.Za&&this.nu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Ya.push(e),this._u())))}async _u(){if(0!==this.Ya.length){try{await this.Ya[0](),this.Ya.shift(),this.zo.reset()}catch(e){if(!X(e))throw e;f("AsyncQueue","Operation failed with retryable error: "+e)}this.Ya.length>0&&this.zo.ko((()=>this._u()))}}ou(e){const t=this.Ja.then((()=>(this.tu=!0,e().catch((e=>{this.eu=e,this.tu=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw m("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.tu=!1,e))))));return this.Ja=t,t}enqueueAfterDelay(e,t,n){this.su(),this.ru.indexOf(e)>-1&&(t=0);const s=Zr.createAndSchedule(this,e,t,n,(e=>this.au(e)));return this.Xa.push(s),s}su(){this.eu&&y()}verifyOperationInProgress(){}async uu(){let e;do{e=this.Ja,await e}while(e!==this.Ja)}cu(e){for(const t of this.Xa)if(t.timerId===e)return!0;return!1}lu(e){return this.uu().then((()=>{this.Xa.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.Xa)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.uu()}))}hu(e){this.ru.push(e)}au(e){const t=this.Xa.indexOf(e);this.Xa.splice(t,1)}}class lo extends ro{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new co,this._persistenceKey=(null==s?void 0:s.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||mo(this),this._firestoreClient.terminate()}}function ho(e,t){const n="object"==typeof e?e:(0,s.Mq)(),r="string"==typeof e?e:t||"(default)",i=(0,s.qX)(n,"firestore").getImmediate({identifier:r});if(!i._initialized){const e=(0,o.P0)("firestore");e&&function(e,t,n,s={}){var r;const i=(e=no(e,ro))._getSettings(),a=`${t}:${n}`;if("firestore.googleapis.com"!==i.host&&i.host!==a&&g("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},i),{host:a,ssl:!1})),s.mockUserToken){let t,n;if("string"==typeof s.mockUserToken)t=s.mockUserToken,n=c.MOCK_USER;else{t=(0,o.Sg)(s.mockUserToken,null===(r=e._app)||void 0===r?void 0:r.options.projectId);const i=s.mockUserToken.sub||s.mockUserToken.user_id;if(!i)throw new _(E.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new c(i)}e._authCredentials=new S(new I(t,n))}}(i,...e)}return i}function fo(e){return e._firestoreClient||mo(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function mo(e){var t,n,s;const r=e._freezeSettings(),i=function(e,t,n,s){return new Ie(e,t,n,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Yi(s.experimentalLongPollingOptions),s.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,r);e._firestoreClient=new Bi(e._authCredentials,e._appCheckCredentials,e._queue,i),(null===(n=r.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(s=r.localCache)||void 0===s?void 0:s._onlineComponentProvider)&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:r.localCache.kind,_offline:r.localCache._offlineComponentProvider,_online:r.localCache._onlineComponentProvider})}class go{constructor(e){this._byteString=e}static fromBase64String(e){try{return new go(ge.fromBase64String(e))}catch(e){throw new _(E.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new go(ge.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class po{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new _(E.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new q(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class yo{constructor(e){this._methodName=e}}class wo{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new _(E.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new _(E.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return L(this._lat,e._lat)||L(this._long,e._long)}}const vo=/^__.*__$/;class Eo{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new wn(e,this.data,this.fieldMask,t,this.fieldTransforms):new yn(e,this.data,t,this.fieldTransforms)}}function _o(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw y()}}class To{constructor(e,t,n,s,r,i){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=s,void 0===r&&this.Pu(),this.fieldTransforms=r||[],this.fieldMask=i||[]}get path(){return this.settings.path}get Iu(){return this.settings.Iu}Tu(e){return new To(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Eu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),s=this.Tu({path:n,du:!1});return s.Au(e),s}Ru(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),s=this.Tu({path:n,du:!1});return s.Pu(),s}Vu(e){return this.Tu({path:void 0,du:!0})}mu(e){return Lo(e,this.settings.methodName,this.settings.fu||!1,this.path,this.settings.gu)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}Pu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Au(this.path.get(e))}Au(e){if(0===e.length)throw this.mu("Document fields must not be empty");if(_o(this.Iu)&&vo.test(e))throw this.mu('Document fields cannot begin and end with "__"')}}class Io{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||yr(e)}pu(e,t,n,s=!1){return new To({Iu:e,methodName:t,gu:n,path:q.emptyPath(),du:!1,fu:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function Co(e){const t=e._freezeSettings(),n=yr(e._databaseId);return new Io(e._databaseId,!!t.ignoreUndefinedProperties,n)}function So(e,t,n,s,r,i={}){const o=e.pu(i.merge||i.mergeFields?2:0,t,n,r);ko("Data must be an object, but it was:",o,s);const a=No(s,o);let u,c;if(i.merge)u=new fe(o.fieldMask),c=o.fieldTransforms;else if(i.mergeFields){const e=[];for(const s of i.mergeFields){const r=Do(t,s,n);if(!o.contains(r))throw new _(E.INVALID_ARGUMENT,`Field '${r}' is specified in your field mask but missing from your input data.`);Mo(e,r)||e.push(r)}u=new fe(e),c=o.fieldTransforms.filter((e=>u.covers(e.field)))}else u=null,c=o.fieldTransforms;return new Eo(new qe(a),u,c)}function Ao(e,t){if(bo(e=(0,o.m9)(e)))return ko("Unsupported field value:",t,e),No(e,t);if(e instanceof yo)return function(e,t){if(!_o(t.Iu))throw t.mu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.mu(`${e._methodName}() is not currently supported inside arrays`);const 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.du&&4!==t.Iu)throw t.mu("Nested arrays are not supported");return function(e,t){const n=[];let s=0;for(const r of e){let e=Ao(r,t.Vu(s));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),s++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=(0,o.m9)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Ht(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=V.fromDate(e);return{timestampValue:Zn(t.serializer,n)}}if(e instanceof V){const n=new V(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Zn(t.serializer,n)}}if(e instanceof wo)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof go)return{bytesValue:es(t.serializer,e._byteString)};if(e instanceof oo){const n=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(n))throw t.mu(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:ss(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.mu(`Unsupported field value: ${to(e)}`)}(e,t)}function No(e,t){const n={};return ae(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):oe(e,((e,s)=>{const r=Ao(s,t.Eu(e));null!=r&&(n[e]=r)})),{mapValue:{fields:n}}}function bo(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof V||e instanceof wo||e instanceof go||e instanceof oo||e instanceof yo)}function ko(e,t,n){if(!bo(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const s=to(n);throw"an object"===s?t.mu(e+" a custom object"):t.mu(e+" "+s)}}function Do(e,t,n){if((t=(0,o.m9)(t))instanceof po)return t._internalPath;if("string"==typeof t)return xo(e,t);throw Lo("Field path arguments must be of type string or ",e,!1,void 0,n)}const Ro=new RegExp("[~\\*/\\[\\]]");function xo(e,t,n){if(t.search(Ro)>=0)throw Lo(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new po(...t.split("."))._internalPath}catch(s){throw Lo(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Lo(e,t,n,s,r){const i=s&&!s.isEmpty(),o=void 0!==r;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let u="";return(i||o)&&(u+=" (found",i&&(u+=` in field ${s}`),o&&(u+=` in document ${r}`),u+=")"),new _(E.INVALID_ARGUMENT,a+e+u)}function Mo(e,t){return e.some((e=>e.isEqual(t)))}class Vo{constructor(e,t,n,s,r){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=s,this._converter=r}get id(){return this._key.path.lastSegment()}get ref(){return new oo(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Oo(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){const t=this._document.data.field(Fo("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Oo extends Vo{data(){return super.data()}}function Fo(e,t){return"string"==typeof t?xo(e,t):t instanceof po?t._internalPath:t._delegate._internalPath}function Po(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new _(E.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Uo{convertValue(e,t="none"){switch(Ae(e)){case 0:return null;case 1:return e.booleanValue;case 2:return we(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(ve(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw y()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return oe(e,((e,s)=>{n[e]=this.convertValue(s,t)})),n}convertGeoPoint(e){return new wo(we(e.latitude),we(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=_e(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Te(e));default:return null}}convertTimestamp(e){const t=ye(e);return new V(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=P.fromString(e);w(Cs(n));const s=new Ce(n.get(1),n.get(3)),r=new B(n.popFirst(5));return s.isEqual(t)||m(`Document ${r} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),r}}function qo(e,t,n){let s;return s=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,s}class Bo{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class zo extends Vo{constructor(e,t,n,s,r,i){super(e,t,n,s,i),this._firestore=e,this._firestoreImpl=e,this.metadata=r}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new $o(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){const n=this._document.data.field(Fo("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class $o extends zo{data(e={}){return super.data(e)}}class Ko{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new Bo(s.hasPendingWrites,s.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new $o(this._firestore,this._userDataWriter,n.key,n,new Bo(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new _(E.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=>{const s=new $o(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Bo(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:s,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const s=new $o(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Bo(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let r=-1,i=-1;return 0!==t.type&&(r=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),i=n.indexOf(t.doc.key)),{type:Go(t.type),doc:s,oldIndex:r,newIndex:i}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Go(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return y()}}class Qo extends Uo{constructor(e){super(),this.firestore=e}convertBytes(e){return new go(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new oo(this.firestore,null,t)}}function jo(e){e=no(e,io);const t=no(e.firestore,lo),n=fo(t),s=new Qo(t);return Po(e._query),Wi(n,e._query).then((n=>new Ko(t,s,e,n)))}function Ho(e,t){const n=no(e.firestore,lo),s=function(e,t,...n){if(e=(0,o.m9)(e),1===arguments.length&&(t=x.newId()),Ji("doc","path",t),e instanceof ro){const s=P.fromString(t,...n);return Zi(s),new oo(e,null,new B(s))}{if(!(e instanceof oo||e instanceof ao))throw new _(E.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=e._path.child(P.fromString(t,...n));return Zi(s),new oo(e.firestore,e instanceof ao?e.converter:null,new B(s))}}(e),r=qo(e.converter,t);return Wo(n,[So(Co(e.firestore),"addDoc",s._key,r,null!==e.converter,{}).toMutation(s._key,cn.exists(!1))]).then((()=>s))}function Wo(e,t){return function(e,t){const n=new T;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const s=Fi(e);try{const e=await function(e,t){const n=v(e),s=V.now(),r=t.reduce(((e,t)=>e.add(t.key)),$t());let i,o;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let a=Mt(),u=$t();return n.ss.getEntries(e,r).next((e=>{a=e,a.forEach(((e,t)=>{t.isValidDocument()||(u=u.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,a))).next((r=>{i=r;const o=[];for(const e of t){const t=gn(e,i.get(e.key).overlayedDocument);null!=t&&o.push(new wn(e.key,t,Be(t.value.mapValue),cn.exists(!0)))}return n.mutationQueue.addMutationBatch(e,s,o,t)})).next((t=>{o=t;const s=t.applyToLocalDocumentSet(i,u);return n.documentOverlayCache.saveOverlays(e,t.batchId,s)}))})).then((()=>({batchId:o.batchId,changes:Ft(i)})))}(s.localStore,t);s.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let s=e.Sa[e.currentUser.toKey()];s||(s=new ue(L)),s=s.insert(t,n),e.Sa[e.currentUser.toKey()]=s}(s,e.batchId,n),await Li(s,e.changes),await qr(s.remoteStore)}catch(e){const t=ei(e,"Failed to persist write");n.reject(t)}}(await ji(e),t,n))),n.promise}(fo(e),t)}new WeakMap;!function(e,t=!0){!function(e){l=e}(s.Jn),(0,s.Xd)(new r.wA("firestore",((e,{instanceIdentifier:n,options:s})=>{const r=e.getProvider("app").getImmediate(),i=new lo(new A(e.getProvider("auth-internal")),new D(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new _(E.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ce(e.options.projectId,t)}(r,n),r);return s=Object.assign({useFetchStreams:t},s),i._setSettings(s),i}),"PUBLIC").setMultipleInstances(!0)),(0,s.KN)(u,"4.4.0",e),(0,s.KN)(u,"4.4.0","esm2017")}()}}]);
//# sourceMappingURL=7112840a-78f439a90988a15ff477.js.map