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