PageSourceSearch

https://app.coresportsai.com/_next/static/chunks/bc9e92e6-3842ac6f51a38c10.js

js coresportsai.com collected 2026-10-09 22:59:00 UTC 291,916 bytes, 9 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[62992],{6596:(e,t,n)=>{n.d(t,{$$:()=>cV,$1:()=>uW,$c:()=>uH,$t:()=>cc,AB:()=>uQ,AM:()=>ht,B:()=>lU,BN:()=>cv,Bh:()=>c4,C3:()=>cX,CL:()=>cW,Ci:()=>ui,Cq:()=>uq,Cs:()=>lM,Dc:()=>ec,EO:()=>uJ,F7:()=>c6,FA:()=>Y,FC:()=>cS,FD:()=>u0,Fs:()=>un,G8:()=>ce,GA:()=>c$,GG:()=>cp,GV:()=>cY,Gv:()=>uY,H6:()=>lG,H9:()=>lL,HM:()=>uX,He:()=>I,Ix:()=>ue,J_:()=>c5,K$:()=>Z,K7:()=>cB,LA:()=>l6,LV:()=>c1,Li:()=>uB,MH:()=>l4,Mh:()=>lj,My:()=>uj,NJ:()=>cu,O5:()=>cH,O8:()=>cr,O_:()=>cN,Os:()=>l5,P:()=>uL,Q5:()=>lZ,Rr:()=>cw,Rw:()=>tX,S0:()=>ur,St:()=>l8,T1:()=>lO,U9:()=>ct,Uo:()=>u$,V7:()=>us,W6:()=>k,Wc:()=>l9,Wq:()=>ca,Ws:()=>lJ,XK:()=>lF,Y$:()=>$,YQ:()=>cl,YS:()=>lV,Z9:()=>he,ZX:()=>cG,_7:()=>lQ,_A:()=>lW,_J:()=>co,_M:()=>uU,_e:()=>cg,aQ:()=>cT,aU:()=>lH,bI:()=>N,bg:()=>cE,c4:()=>cQ,c8:()=>et,cY:()=>cU,cm:()=>nt,cz:()=>u7,d_:()=>cC,eQ:()=>O,fS:()=>u3,gS:()=>c_,gT:()=>cn,hq:()=>cJ,i1:()=>cZ,iB:()=>l2,jy:()=>uK,kA:()=>hn,kL:()=>cO,kU:()=>cy,kd:()=>cI,lN:()=>ch,lo:()=>ea,mT:()=>c3,mZ:()=>cb,mc:()=>cs,me:()=>l1,nY:()=>cm,oN:()=>l7,ol:()=>lY,or:()=>uz,po:()=>l3,qG:()=>tJ,qi:()=>E,rJ:()=>lP,rf:()=>uZ,ts:()=>cP,uY:()=>ut,vK:()=>cM,vN:()=>lR,wP:()=>c0,wx:()=>uM,wy:()=>B,x7:()=>cd,xC:()=>uG,yf:()=>c8,yx:()=>lq,z6:()=>cx});var r,i,s,a,o=n(91398),l=n(22396),u=n(5969),c=n(57176),h=n(90916),d=n(24052),f=n(87358),m=n(81029).hp;let g="@firebase/firestore",p="4.8.0";class y{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}y.UNAUTHENTICATED=new y(null),y.GOOGLE_CREDENTIALS=new y("google-credentials-uid"),y.FIRST_PARTY=new y("first-party-uid"),y.MOCK_USER=new y("mock-user");let w="11.10.0",v=new u.Vy("@firebase/firestore");function b(){return v.logLevel}function I(e){v.setLogLevel(e)}function _(e,...t){if(v.logLevel<=u.$b.DEBUG){let n=t.map(S);v.debug(`Firestore (${w}): ${e}`,...n)}}function T(e,...t){if(v.logLevel<=u.$b.ERROR){let n=t.map(S);v.error(`Firestore (${w}): ${e}`,...n)}}function E(e,...t){if(v.logLevel<=u.$b.WARN){let n=t.map(S);v.warn(`Firestore (${w}): ${e}`,...n)}}function S(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function x(e,t,n){let r="Unexpected state";"string"==typeof t?r=t:n=t,D(e,r,n)}function D(e,t,n){let r=`FIRESTORE (${w}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==n)try{r+=" CONTEXT: "+JSON.stringify(n)}catch(e){r+=" CONTEXT: "+n}throw T(r),Error(r)}function C(e,t,n,r){let i="Unexpected state";"string"==typeof n?i=n:r=n,e||D(t,i,r)}function N(e,t){e||x(57014,t)}let A={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class k extends c.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class R{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class F{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class O{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(y.UNAUTHENTICATED))}shutdown(){}}class V{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class P{constructor(e){this.t=e,this.currentUser=y.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){C(void 0===this.o,42304);let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),i=new R;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new R,e.enqueueRetryable(()=>r(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},a=e=>{_("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(_("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new R)}},0),s()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(_("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(C("string"==typeof t.accessToken,31837,{l:t}),new F(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return C(null===e||"string"==typeof e,2055,{h:e}),new y(e)}}class M{constructor(e,t,n){this.P=e,this.T=t,this.I=n,this.type="FirstParty",this.user=y.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set("X-Goog-AuthUser",this.P);let e=this.R();return e&&this.A.set("Authorization",e),this.T&&this.A.set("X-Goog-Iam-Authorization-Token",this.T),this.A}}class L{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new M(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(y.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class q{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class U{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,o.xZ)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){C(void 0===this.o,3512);let n=e=>{null!=e.error&&_("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let n=e.token!==this.m;return this.m=e.token,_("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>{_("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?r(e):_("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new q(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(C("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new q(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class B{getToken(){return Promise.resolve(new q(""))}invalidateToken(){}start(e,t){}shutdown(){}}function z(){return new TextEncoder}class ${static newId(){let e=62*Math.floor(256/62),t="";for(;t.length<20;){let n=function(e){let t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(40);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let e=0;e<40;
1e++)n[e]=Math.floor(256*Math.random());return n}(40);for(let r=0;r<n.length;++r)t.length<20&&n[r]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[r]%62))}return t}}function K(e,t){return e<t?-1:+(e>t)}function j(e,t){let n=0;for(;n<e.length&&n<t.length;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i){if(r<128&&i<128)return K(r,i);{let s=z(),a=function(e,t){for(let n=0;n<e.length&&n<t.length;++n)if(e[n]!==t[n])return K(e[n],t[n]);return K(e.length,t.length)}(s.encode(G(e,n)),s.encode(G(t,n)));return 0!==a?a:K(r,i)}}n+=r>65535?2:1}return K(e.length,t.length)}function G(e,t){return e.codePointAt(t)>65535?e.substring(t,t+2):e.substring(t,t+1)}function Q(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}let W="__name__";class H{constructor(e,t,n){void 0===t?t=0:t>e.length&&x(637,{offset:t,range:e.length}),void 0===n?n=e.length-t:n>e.length-t&&x(1746,{length:n,range:e.length-t}),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===H.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof H?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=H.compareSegments(e.get(r),t.get(r));if(0!==n)return n}return K(e.length,t.length)}static compareSegments(e,t){let n=H.isNumericId(e),r=H.isNumericId(t);return n&&!r?-1:!n&&r?1:n&&r?H.extractNumericId(e).compare(H.extractNumericId(t)):j(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return h.jz.fromString(e.substring(4,e.length-2))}}class J extends H{construct(e,t,n){return new J(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new k(A.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new J(t)}static emptyPath(){return new J([])}}let X=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Y extends H{construct(e,t,n){return new Y(e,t,n)}static isValidIdentifier(e){return X.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Y.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===W}static keyField(){return new Y([W])}static fromServerFormat(e){let t=[],n="",r=0,i=()=>{if(0===n.length)throw new k(A.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},s=!1;for(;r<e.length;){let t=e[r];if("\\"===t){if(r+1===e.length)throw new k(A.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new k(A.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new k(A.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Y(t)}static emptyPath(){return new Y([])}}class Z{constructor(e){this.path=e}static fromPath(e){return new Z(J.fromString(e))}static fromName(e){return new Z(J.fromString(e).popFirst(5))}static empty(){return new Z(J.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===J.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return J.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new Z(new J(e.slice()))}}function ee(e,t,n){if(!n)throw new k(A.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function et(e,t,n,r){if(!0===t&&!0===r)throw new k(A.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function en(e){if(!Z.isDocumentKey(e))throw new k(A.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function er(e){if(Z.isDocumentKey(e))throw new k(A.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function ei(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function es(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var t;let n=(t=e).constructor?t.constructor.name:null;return n?`a custom ${n} object`:"an object"}}return"function"==typeof e?"a function":x(12329,{type:typeof e})}function ea(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new k(A.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=es(e);throw new k(A.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function eo(e,t){if(t<=0)throw new k(A.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}function el(e,t){let n={typeString:e};return t&&(n.value=t),n}function eu(e,t){let n;if(!ei(e))throw new k(A.INVALID_ARGUMENT,"JSON must be an object");for(let r in t)if(t[r]){let i=t[r].typeString,s="value"in t[r]?{value:t[r].value}:void 0;if(!(r in e)){n=`JSON missing required field: '${r}'`;break}let a=e[r];if(i&&typeof a!==i){n=`JSON field '${r}' must be a ${i}.`;break}if(void 0!==s&&a!==s.value){n=`Expected '${r}' field to equal '${s.value}'`;break}}if(n)throw new k(A.INVALID_ARGUMENT,n);return!0}class ec{static now(){return ec.fromMillis(Date.now())}static fromDate(e){return ec.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*1e6);return new ec(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new k(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new k(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?K(this.nanoseconds,e.nanoseconds):K(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:ec._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(eu(e,ec._jsonSchema))return new ec(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}
1}ec._jsonSchemaVersion="firestore/timestamp/1.0",ec._jsonSchema={type:el("string",ec._jsonSchemaVersion),seconds:el("number"),nanoseconds:el("number")};class eh{static fromTimestamp(e){return new eh(e)}static min(){return new eh(new ec(0,0))}static max(){return new eh(new ec(0x3afff4417f,0x3b9ac9ff))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class ed{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function ef(e){return e.fields.find(e=>2===e.kind)}function em(e){return e.fields.filter(e=>2!==e.kind)}function eg(e,t){let n=K(e.collectionGroup,t.collectionGroup);if(0!==n)return n;for(let r=0;r<Math.min(e.fields.length,t.fields.length);++r)if(0!==(n=function(e,t){let n=Y.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:K(e.kind,t.kind)}(e.fields[r],t.fields[r])))return n;return K(e.fields.length,t.fields.length)}ed.UNKNOWN_ID=-1;class ep{constructor(e,t){this.fieldPath=e,this.kind=t}}class ey{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new ey(0,eb.min())}}function ew(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;return new eb(eh.fromTimestamp(1e9===r?new ec(n+1,0):new ec(n,r)),Z.empty(),t)}function ev(e){return new eb(e.readTime,e.key,-1)}class eb{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new eb(eh.min(),Z.empty(),-1)}static max(){return new eb(eh.max(),Z.empty(),-1)}}function eI(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n||0!==(n=Z.comparator(e.documentKey,t.documentKey))?n:K(e.largestBatchId,t.largestBatchId)}let e_="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class eT{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function eE(e){if(e.code!==A.FAILED_PRECONDITION||e.message!==e_)throw e;_("LocalStore","Unexpectedly lost primary lease")}class eS{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&x(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new eS((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof eS?t:eS.resolve(t)}catch(e){return eS.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):eS.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):eS.reject(t)}static resolve(e){return new eS((t,n)=>{t(e)})}static reject(e){return new eS((t,n)=>{n(e)})}static waitFor(e){return new eS((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=eS.resolve(!1);for(let n of e)t=t.next(e=>e?eS.resolve(e):n());return t}static forEach(e,t){let n=[];return e.forEach((e,r)=>{n.push(t.call(this,e,r))}),this.waitFor(n)}static mapArray(e,t){return new eS((n,r)=>{let i=e.length,s=Array(i),a=0;for(let o=0;o<i;o++){let l=o;t(e[l]).next(e=>{s[l]=e,++a===i&&n(s)},e=>r(e))}})}static doWhile(e,t){return new eS((n,r)=>{let i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}let ex="SimpleDb";class eD{static open(e,t,n,r){try{return new eD(t,e.transaction(r,n))}catch(e){throw new ek(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.S=new R,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{t.error?this.S.reject(new ek(e,t.error)):this.S.resolve()},this.transaction.onerror=t=>{let n=eP(t.target.error);this.S.reject(new ek(e,n))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(_(ex,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}v(){let e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){return new eF(this.transaction.objectStore(e))}}class eC{static delete(e){return _(ex,"Removing database:",e),eO((0,c.mS)().indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!(0,c.zW)())return!1;if(eC.F())return!0;let e=(0,c.ZQ)(),t=eC.M(e),n=eN(e);return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||0<t&&t<10||0<n&&n<4.5)}static F(){var e;return void 0!==f&&"YES"===(null==(e=f.__PRIVATE_env)?void 0:e.O)}static N(e,t){return e.store(t)}static M(e){let t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i);return Number(t?t[1].split("_").slice(0,2).join("."):"-1")}constructor(e,t,n){this.name=e,this.version=t,this.B=n,this.L=null,12.2===eC.M((0,c.ZQ)())&&T("Firestore persistence suffers from a bug in 
1iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async k(e){return this.db||(_(ex,"Opening database:",this.name),this.db=await new Promise((t,n)=>{let r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{t(e.target.result)},r.onblocked=()=>{n(new ek(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{let r=t.target.error;"VersionError"===r.name?n(new k(A.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===r.name?n(new k(A.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+r)):n(new ek(e,r))},r.onupgradeneeded=e=>{_(ex,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);let t=e.target.result;if(null!==this.L&&this.L!==e.oldVersion)throw Error(`refusing to open IndexedDB database due to potential corruption of the IndexedDB database data; this corruption could be caused by clicking the "clear site data" button in a web browser; try reloading the web page to re-initialize the IndexedDB database: lastClosedDbVersion=${this.L}, event.oldVersion=${e.oldVersion}, event.newVersion=${e.newVersion}, db.version=${t.version}`);this.B.q(t,r.transaction,e.oldVersion,this.version).next(()=>{_(ex,"Database upgrade to version "+this.version+" complete")})}}),this.db.addEventListener("close",e=>{let t=e.target;this.L=t.version},{passive:!0})),this.db.addEventListener("versionchange",e=>{var t;null===e.newVersion&&(E('Received "versionchange" event with newVersion===null; notifying the registered DatabaseDeletedListener, if any'),null==(t=this.databaseDeletedListener)||t.call(this))},{passive:!0}),this.db}setDatabaseDeletedListener(e){if(this.databaseDeletedListener)throw Error("setDatabaseDeletedListener() may only be called once, and it has already been called");this.databaseDeletedListener=e}async runTransaction(e,t,n,r){let i="readonly"===t,s=0;for(;;){++s;try{this.db=await this.k(e);let t=eD.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.v(),e)).catch(e=>(t.abort(e),eS.reject(e))).toPromise();return s.catch(()=>{}),await t.D,s}catch(t){let e="FirebaseError"!==t.name&&s<3;if(_(ex,"Transaction failed with error:",t.message,"Retrying:",e),this.close(),!e)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function eN(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class eA{constructor(e){this.$=e,this.U=!1,this.K=null}get isDone(){return this.U}get W(){return this.K}set cursor(e){this.$=e}done(){this.U=!0}G(e){this.K=e}delete(){return eO(this.$.delete())}}class ek extends k{constructor(e,t){super(A.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function eR(e){return"IndexedDbTransactionError"===e.name}class eF{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(_(ex,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(_(ex,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),eO(n)}add(e){return _(ex,"ADD",this.store.name,e,e),eO(this.store.add(e))}get(e){return eO(this.store.get(e)).next(t=>(void 0===t&&(t=null),_(ex,"GET",this.store.name,e,t),t))}delete(e){return _(ex,"DELETE",this.store.name,e),eO(this.store.delete(e))}count(){return _(ex,"COUNT",this.store.name),eO(this.store.count())}j(e,t){let n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){let e=r.getAll(n.range);return new eS((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),t=[];return this.J(e,(e,n)=>{t.push(n)}).next(()=>t)}}H(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new eS((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}Y(e,t){_(ex,"DELETE ALL",this.store.name);let n=this.options(e,t);n.Z=!1;let r=this.cursor(n);return this.J(r,(e,t,n)=>n.delete())}X(e,t){let n;t?n=e:(n={},t=e);let r=this.cursor(n);return this.J(r,t)}ee(e){let t=this.cursor({});return new eS((n,r)=>{t.onerror=e=>{r(eP(e.target.error))},t.onsuccess=t=>{let r=t.target.result;r?e(r.primaryKey,r.value).next(e=>{e?r.continue():n()}):n()}})}J(e,t){let n=[];return new eS((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{let i=e.target.result;if(!i)return void r();let s=new eA(i),a=t(i.primaryKey,i.value,s);if(a instanceof eS){let e=a.catch(e=>(s.done(),eS.reject(e)));n.push(e)}s.isDone?r():null===s.W?i.continue():i.continue(s.W)}}).next(()=>eS.waitFor(n))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){let n=this.store.index(e.index);return e.Z?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function eO(e){return new eS((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{n(eP(e.target.error))}})}let eV=!1;function eP(e){let t=eC.M((0,c.ZQ)());if(t>=12.2&&t<13){let t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){let e=new k("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return eV||(eV=!0,setTimeout(()=>{throw e},0)),e}}return e}let eM="IndexBackfiller";class eL{constructor(e,t){this.asyncQueue=e,this.te=t,this.task=null}start(){this.ne(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}ne(e){_(eM,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let e=await this.te.re();_(eM,`Documents written: ${e}`)}catch(e){eR(e)?_(eM,"Ignoring IndexedDB error during index backfill: ",e):await eE(e)}await this.ne(6e4)})}}class eq{constructor(e,t){this.localStore=e,this.persistence=t}async re(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.ie(t,e))}ie(e,t){let n=new Set,r=t,i=!0;
1return eS.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!n.has(t))return _(eM,`Processing collection: ${t}`),this.se(e,t,r).next(e=>{r-=e,n.add(t)});i=!1})).next(()=>t-r)}se(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next(n=>{let i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next(()=>this.oe(r,n)).next(n=>(_(eM,`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n))).next(()=>i.size)}))}oe(e,t){let n=e;return t.changes.forEach((e,t)=>{let r=ev(t);eI(r,n)>0&&(n=r)}),new eb(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class eU{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this._e(e),this.ae=e=>t.writeSequenceNumber(e))}_e(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ae&&this.ae(e),e}}function eB(e){return null==e}function ez(e){return 0===e&&1/e==-1/0}function e$(e){return"number"==typeof e&&Number.isInteger(e)&&!ez(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function eK(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let n=t,r=e.length;for(let t=0;t<r;t++){let r=e.charAt(t);switch(r){case"\0":n+="\x01\x10";break;case"\x01":n+="\x01\x11";break;default:n+=r}}return n}(e.get(n),t);return t+"\x01\x01"}eU.ue=-1;function ej(e){let t=e.length;if(C(t>=2,64408,{path:e}),2===t)return C("\x01"===e.charAt(0)&&"\x01"===e.charAt(1),56145,{path:e}),J.emptyPath();let n=t-2,r=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>n)&&x(50515,{path:e}),e.charAt(t+1)){case"\x01":let a,o=e.substring(s,t);0===i.length?a=o:(i+=o,a=i,i=""),r.push(a);break;case"\x10":i+=e.substring(s,t),i+="\0";break;case"\x11":i+=e.substring(s,t+1);break;default:x(61167,{path:e})}s=t+2}return new J(r)}let eG="remoteDocuments",eQ="owner",eW="owner",eH="mutationQueues",eJ="mutations",eX="batchId",eY="userMutationsIndex",eZ=["userId","batchId"],e0={},e1="documentMutations",e2="remoteDocumentsV14",e5=["prefixPath","collectionGroup","readTime","documentId"],e6="documentKeyIndex",e4=["prefixPath","collectionGroup","documentId"],e3="collectionGroupIndex",e8=["collectionGroup","readTime","prefixPath","documentId"],e9="remoteDocumentGlobal",e7="remoteDocumentGlobalKey",te="targets",tt="queryTargetsIndex",tn=["canonicalId","targetId"],tr="targetDocuments",ti=["targetId","path"],ts="documentTargetsIndex",ta=["path","targetId"],to="targetGlobalKey",tl="targetGlobal",tu="collectionParents",tc=["collectionId","parent"],th="clientMetadata",td="bundles",tf="namedQueries",tm="indexConfiguration",tg="collectionGroupIndex",tp="indexState",ty=["indexId","uid"],tw="sequenceNumberIndex",tv=["uid","sequenceNumber"],tb="indexEntries",tI=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],t_="documentKeyIndex",tT=["indexId","uid","orderedDocumentKey"],tE="documentOverlays",tS=["userId","collectionPath","documentId"],tx="collectionPathOverlayIndex",tD=["userId","collectionPath","largestBatchId"],tC="collectionGroupOverlayIndex",tN=["userId","collectionGroup","largestBatchId"],tA="globals",tk=[eH,eJ,e1,eG,te,eQ,tl,tr,th,e9,tu,td,tf],tR=[...tk,tE],tF=[eH,eJ,e1,e2,te,eQ,tl,tr,th,e9,tu,td,tf,tE],tO=[...tF,tm,tp,tb],tV=[...tO,tA];class tP extends eT{constructor(e,t){super(),this.ce=e,this.currentSequenceNumber=t}}function tM(e,t){return eC.N(e.ce,t)}function tL(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tq(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function tU(e,t){let n=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.push(t(e[r],r,e));return n}function tB(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class tz{constructor(e,t){this.comparator=e,this.root=t||tK.EMPTY}insert(e,t){return new tz(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,tK.BLACK,null,
1null))}remove(e){return new tz(this.comparator,this.root.remove(e,this.comparator).copy(null,null,tK.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){let r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return -1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new t$(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new t$(this.root,e,this.comparator,!1)}getReverseIterator(){return new t$(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new t$(this.root,e,this.comparator,!0)}}class t${constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class tK{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:tK.RED,this.left=null!=r?r:tK.EMPTY,this.right=null!=i?i:tK.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new tK(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this,i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp()}removeMin(){if(this.left.isEmpty())return tK.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()}remove(e,t){let n,r=this;if(0>t(e,r.key))r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return tK.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}rotateLeft(){let e=this.copy(null,null,tK.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,tK.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw x(43730,{key:this.key,value:this.value});if(this.right.isRed())throw x(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw x(27949);return e+ +!this.isRed()}}
1tK.EMPTY=null,tK.RED=!0,tK.BLACK=!1,tK.EMPTY=new class{constructor(){this.size=0}get key(){throw x(57766)}get value(){throw x(16141)}get color(){throw x(16727)}get left(){throw x(29726)}get right(){throw x(36894)}copy(e,t,n,r,i){return this}insert(e,t,n){return new tK(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class tj{constructor(e){this.comparator=e,this.data=new tz(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,n)=>(e(t),!1))}forEachInRange(e,t){let n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){let r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new tG(this.data.getIterator())}getIteratorFrom(e){return new tG(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof tj)||this.size!==e.size)return!1;let t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new tj(this.comparator);return t.data=e,t}}class tG{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function tQ(e){return e.hasNext()?e.getNext():void 0}class tW{constructor(e){this.fields=e,e.sort(Y.comparator)}static empty(){return new tW([])}unionWith(e){let t=new tj(Y.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new tW(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Q(this.fields,e.fields,(e,t)=>e.isEqual(t))}}
1class tH extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}function tJ(){return"undefined"!=typeof atob}class tX{constructor(e){this.binaryString=e}static fromBase64String(e){return new tX(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new tH("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new tX(function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e))}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return btoa(this.binaryString)}toUint8Array(){var e=this.binaryString;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return K(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}tX.EMPTY_BYTE_STRING=new tX("");let tY=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function tZ(e){if(C(!!e,39018),"string"==typeof e){let t=0,n=tY.exec(e);if(C(!!n,46558,{timestamp:e}),n[1]){let e=n[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:t0(e.seconds),nanos:t0(e.nanos)}}function t0(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function t1(e){return"string"==typeof e?tX.fromBase64String(e):tX.fromUint8Array(e)}let t2="server_timestamp",t5="__type__",t6="__previous_value__",t4="__local_write_time__";function t3(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[t5])?void 0:n.stringValue)===t2}function t8(e){let t=e.mapValue.fields[t6];return t3(t)?t8(t):t}function t9(e){let t=tZ(e.mapValue.fields[t4].timestampValue);return new ec(t.seconds,t.nanos)}class t7{constructor(e,t,n,r,i,s,a,o,l,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u}}let ne="(default)";class nt{constructor(e,t){this.projectId=e,this.database=t||ne}static empty(){return new nt("","")}get isDefaultDatabase(){return this.database===ne}isEqual(e){return e instanceof nt&&e.projectId===this.projectId&&e.database===this.database}}let nn="__type__",nr="__max__",ni={mapValue:{fields:{__type__:{stringValue:nr}}}},ns="__vector__",na="value",no={nullValue:"NULL_VALUE"};function nl(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?t3(e)?4:nT(e)?0x1fffffffffffff:nI(e)?10:11:x(28295,{value:e})}function nu(e,t){if(e===t)return!0;let n=nl(e);if(n!==nl(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return t9(e).isEqual(t9(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let r=tZ(e.timestampValue),i=tZ(t.timestampValue);return r.seconds===i.seconds&&r.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return t1(e.bytesValue).isEqual(t1(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return t0(e.geoPointValue.latitude)===t0(t.geoPointValue.latitude)&&t0(e.geoPointValue.longitude)===t0(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return t0(e.integerValue)===t0(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=t0(e.doubleValue),r=t0(t.doubleValue);return n===r?ez(n)===ez(r):isNaN(n)&&isNaN(r)}return!1;case 9:return Q(e.arrayValue.values||[],t.arrayValue.values||[],nu);case 10:case 11:let s=e.mapValue.fields||{},a=t.mapValue.fields||{};if(tL(s)!==tL(a))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===a[e]||!nu(s[e],a[e])))return!1;return!0;default:return x(52216,{left:e})}}function nc(e,t){return void 0!==(e.values||[]).find(e=>nu(e,t))}function nh(e,t){if(e===t)return 0;let n=nl(e),r=nl(t);if(n!==r)return K(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return K(e.booleanValue,t.booleanValue);case 2:let i=t0(e.integerValue||e.doubleValue),s=t0(t.integerValue||t.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return nd(e.timestampValue,t.timestampValue);case 4:return nd(t9(e),t9(t));case 5:return j(e.stringValue,t.stringValue);case 6:return function(e,t){let n=t1(e),r=t1(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){let n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){let t=K(n[e],r[e]);if(0!==t)return t}return K(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let n=K(t0(e.latitude),t0(t.latitude));return 0!==n?n:K(t0(e.longitude),t0(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return nf(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,i,s;let a=e.fields||{},o=t.fields||{},l=null==(n=a[na])?void 0:n.arrayValue,u=null==(r=o[na])?void 0:r.arrayValue,c=K((null==(i=null==l?void 0:l.values)?void 0:i.length)||0,(null==(s=null==u?void 0:u.values)?void 0:s.length)||0);return 0!==c?c:nf(l,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===ni.mapValue&&t===ni.mapValue)return 0;if(e===ni.mapValue)return 1;if(t===ni.mapValue)return -1;let n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){let t=j(r[e],s[e]);if(0!==t)return t;let a=nh(n[r[e]],i[s[e]]);if(0!==a)return a}return K(r.length,s.length)}(e.mapValue,t.mapValue);default:throw x(23264,{le:n})}}
1function nd(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return K(e,t);let n=tZ(e),r=tZ(t),i=K(n.seconds,r.seconds);return 0!==i?i:K(n.nanos,r.nanos)}function nf(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=nh(n[e],r[e]);if(t)return t}return K(n.length,r.length)}function nm(e){var t,n;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){let t=tZ(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?t1(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,Z.fromName(t).toString()):"geoPointValue"in e?(n=e.geoPointValue,`geo(${n.latitude},${n.longitude})`):"arrayValue"in e?function(e){let t="[",n=!0;for(let r of e.values||[])n?n=!1:t+=",",t+=nm(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),n="{",r=!0;for(let i of t)r?r=!1:n+=",",n+=`${i}:${nm(e.fields[i])}`;return n+"}"}(e.mapValue):x(61005,{value:e})}function ng(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function np(e){return!!e&&"integerValue"in e}function ny(e){return!!e&&"arrayValue"in e}function nw(e){return!!e&&"nullValue"in e}function nv(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function nb(e){return!!e&&"mapValue"in e}function nI(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[nn])?void 0:n.stringValue)===ns}function n_(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){let t={mapValue:{fields:{}}};return tq(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=n_(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=n_(e.arrayValue.values[n]);return t}return Object.assign({},e)}function nT(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===nr}let nE={mapValue:{fields:{[nn]:{stringValue:ns},[na]:{arrayValue:{}}}}};function nS(e,t){let n=nh(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function nx(e,t){let n=nh(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class nD{constructor(e){this.value=e}static empty(){return new nD({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!nb(t=(t.mapValue.fields||{})[e.get(n)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=n_(t)}setAll(e){let t=Y.emptyPath(),n={},r=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){let e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=n_(e):r.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){let t=this.field(e.popLast());nb(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return nu(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];nb(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){for(let r of(tq(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new nD(n_(this.value))}}class nC{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new nC(e,0,eh.min(),eh.min(),eh.min(),nD.empty(),0)}static newFoundDocument(e,t,n,r){return new nC(e,1,t,eh.min(),n,r,0)}static newNoDocument(e,t){return new nC(e,2,t,eh.min(),eh.min(),nD.empty(),0)}static newUnknownDocument(e,t){return new nC(e,3,t,eh.min(),eh.min(),nD.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(eh.min())&&(2===this.documentType||0===this.documentType)&&(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=nD.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=nD.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=eh.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof nC&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new nC(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 nN{constructor(e,t){this.position=e,this.inclusive=t}}function nA(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){let s=t[i],a=e.position[i];if(r=s.field.isKeyField()?Z.comparator(Z.fromName(a.referenceValue),n.key):nh(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function nk(e,t){if(null===e)return null===t;if(null===t||e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!nu(e.position[n],t.position[n]))return!1;return!0}class nR{constructor(e,t="asc"){this.field=e,this.dir=t}}class nF{}class nO extends nF{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new nB(e,t,n):"array-contains"===t?new nj(e,n):"in"===t?new nG(e,n):"not-in"===t?new nQ(e,n):"array-contains-any"===t?new nW(e,n):new nO(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new nz(e,n):new n$(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(nh(t,this.value)):null!==t&&nl(this.value)===nl(t)&&this.matchesComparison(nh(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return x(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class nV extends nF{constructor(e,t){super(),this.filters=e,this.op=t,this.he=null}static create(e,t){return new nV(e,t)}matches(e){return nP(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.he||(this.he=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.he}getFilters(){return Object.assign([],this.filters)}}function nP(e){return"and"===e.op}function nM(e){return"or"===e.op}function nL(e){return nq(e)&&nP(e)}function nq(e){for(let t of e.filters)if(t instanceof nV)return!1;return!0}function nU(e,t){let n=e.filters.concat(t);return nV.create(n,e.op)}class nB extends nO{constructor(e,t,n){super(e,t,n),this.key=Z.fromName(n.referenceValue)}matches(e){let t=Z.comparator(e.key,this.key);return this.matchesComparison(t)}}class nz extends nO{constructor(e,t){super(e,"in",t),this.keys=nK("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class n$ extends nO{constructor(e,t){super(e,"not-in",t),this.keys=nK("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function nK(e,t){var n;return((null==(n=t.arrayValue)?void 0:n.values)||[]).map(e=>Z.fromName(e.referenceValue))}class nj extends nO{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return ny(t)&&nc(t.arrayValue,this.value)}}class nG extends nO{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&nc(this.value.arrayValue,t)}}class nQ extends nO{constructor(e,t){super(e,"not-in",t)}matches(e){if(nc(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!nc(this.value.arrayValue,t)}}class nW extends nO{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!ny(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>nc(this.value.arrayValue,e))}}class nH{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.Pe=null}}function nJ(e,t=null,n=[],r=[],i=null,s=null,a=null){return new nH(e,t,n,r,i,s,a)}function nX(e){if(null===e.Pe){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(e=>(function e(t){if(t instanceof nO)return t.field.canonicalString()+t.op.toString()+nm(t.value);if(nL(t))return t.filters.map(t=>e(t)).join(",");{let n=t.filters.map(t=>e(t)).join(",");return`${t.op}(${n})`}})(e)).join(","),t+="|ob:",t+=e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),eB(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>nm(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>nm(e)).join(",")),e.Pe=t}return e.Pe}function nY(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++){var n,r;if(n=e.orderBy[i],r=t.orderBy[i],!(n.dir===r.dir&&n.field.isEqual(r.field)))return!1}if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!function e(t,n){return t instanceof nO?n instanceof nO&&t.op===n.op&&t.field.isEqual(n.field)&&nu(t.value,n.value):t instanceof nV?n instanceof nV&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,i)=>t&&e(r,n.filters[i]),!0):void x(19439)}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!nk(e.startAt,t.startAt)&&nk(e.endAt,t.endAt)}function nZ(e){return Z.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function n0(e,t){return e.filters.filter(e=>e instanceof nO&&e.field.isEqual(t))}function n1(e,t,n){let r=no,i=!0;for(let n of n0(e,t)){let e=no,t=!0;switch(n.op){case"<":case"<=":var s;
1e="nullValue"in(s=n.value)?no:"booleanValue"in s?{booleanValue:!1}:"integerValue"in s||"doubleValue"in s?{doubleValue:NaN}:"timestampValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in s?{stringValue:""}:"bytesValue"in s?{bytesValue:""}:"referenceValue"in s?ng(nt.empty(),Z.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?nI(s)?nE:{mapValue:{}}:x(35942,{value:s});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=no}0>nS({value:r,inclusive:i},{value:e,inclusive:t})&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];0>nS({value:r,inclusive:i},{value:e,inclusive:n.inclusive})&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}function n2(e,t,n){let r=ni,i=!0;for(let n of n0(e,t)){let e=ni,t=!0;switch(n.op){case">=":case">":var s;e="nullValue"in(s=n.value)?{booleanValue:!1}:"booleanValue"in s?{doubleValue:NaN}:"integerValue"in s||"doubleValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in s?{stringValue:""}:"stringValue"in s?{bytesValue:""}:"bytesValue"in s?ng(nt.empty(),Z.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?nE:"mapValue"in s?nI(s)?{mapValue:{}}:ni:x(61959,{value:s}),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=ni}nx({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];nx({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}class n5{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Te=null,this.Ie=null,this.de=null,this.startAt,this.endAt}}function n6(e){return new n5(e)}function n4(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function n3(e){return null!==e.collectionGroup}function n8(e){if(null===e.Te){let t;e.Te=[];let n=new Set;for(let t of e.explicitOrderBy)e.Te.push(t),n.add(t.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(t=new tj(Y.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t).forEach(t=>{n.has(t.canonicalString())||t.isKeyField()||e.Te.push(new nR(t,r))}),n.has(Y.keyField().canonicalString())||e.Te.push(new nR(Y.keyField(),r))}return e.Te}function n9(e){return e.Ie||(e.Ie=re(e,n8(e))),e.Ie}function n7(e){return e.de||(e.de=re(e,e.explicitOrderBy)),e.de}function re(e,t){if("F"===e.limitType)return nJ(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{let t="desc"===e.dir?"asc":"desc";return new nR(e.field,t)});let n=e.endAt?new nN(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new nN(e.startAt.position,e.startAt.inclusive):null;return nJ(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function rt(e,t){let n=e.filters.concat([t]);return new n5(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function rn(e,t,n){return new n5(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function rr(e,t){return nY(n9(e),n9(t))&&e.limitType===t.limitType}function ri(e){return`${nX(n9(e))}|lt:${e.limitType}`}function rs(e){var t;let n;return`Query(target=${n=(t=n9(e)).path.canonicalString(),null!==t.collectionGroup&&(n+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(n+=`, filters: [${t.filters.map(e=>(function e(t){return t instanceof nO?`${t.field.canonicalString()} ${t.op} ${nm(t.value)}`:t instanceof nV?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),eB(t.limit)||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(e=>nm(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>nm(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function ra(e,t){return t.isFoundDocument()&&function(e,t){let n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):Z.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(let n of n8(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(let n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&(!e.startAt||!!function(e,t,n){let r=nA(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,n8(e),t))&&(!e.endAt||!!function(e,t,n){let r=nA(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,n8(e),t))}function ro(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function rl(e){return(t,n)=>{let r=!1;for(let i of n8(e)){let e=function(e,t,n){let r=e.field.isKeyField()?Z.comparator(t.key,n.key):function(e,t,n){let r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?nh(r,i):x(42886)}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return x(19790,{direction:e.dir})}}(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}class ru{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n){for(let[t,r]of n)if(this.equalsFn(t,e))return r}}has(e){return void 0!==this.get(e)}set(e,t){let n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);
1r.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){tq(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){return tB(this.inner)}size(){return this.innerSize}}let rc=new tz(Z.comparator),rh=new tz(Z.comparator);function rd(...e){let t=rh;for(let n of e)t=t.insert(n.key,n);return t}function rf(e){let t=rh;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function rm(){return new ru(e=>e.toString(),(e,t)=>e.isEqual(t))}let rg=new tz(Z.comparator),rp=new tj(Z.comparator);function ry(...e){let t=rp;for(let n of e)t=t.add(n);return t}let rw=new tj(K);function rv(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:ez(t)?"-0":t}}function rb(e){return{integerValue:""+e}}function rI(e,t){return e$(t)?rb(t):rv(e,t)}class r_{constructor(){this._=void 0}}function rT(e,t){return e instanceof rN?np(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}class rE extends r_{}class rS extends r_{constructor(e){super(),this.elements=e}}function rx(e,t){let n=rk(t);for(let t of e.elements)n.some(e=>nu(e,t))||n.push(t);return{arrayValue:{values:n}}}class rD extends r_{constructor(e){super(),this.elements=e}}function rC(e,t){let n=rk(t);for(let t of e.elements)n=n.filter(e=>!nu(e,t));return{arrayValue:{values:n}}}class rN extends r_{constructor(e,t){super(),this.serializer=e,this.Ee=t}}function rA(e){return t0(e.integerValue||e.doubleValue)}function rk(e){return ny(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class rR{constructor(e,t){this.field=e,this.transform=t}}class rF{constructor(e,t){this.version=e,this.transformResults=t}}class rO{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new rO}static exists(e){return new rO(void 0,e)}static updateTime(e){return new rO(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function rV(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class rP{}function rM(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new rj(e.key,rO.none()):new rU(e.key,e.data,rO.none());{let n=e.data,r=nD.empty(),i=new tj(Y.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new rB(e.key,r,new tW(i.toArray()),rO.none())}}function rL(e,t,n,r){return e instanceof rU?function(e,t,n,r){if(!rV(e.precondition,t))return n;let i=e.value.clone(),s=rK(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof rB?function(e,t,n,r){if(!rV(e.precondition,t))return n;let i=rK(e.fieldTransforms,r,t),s=t.data;return(s.setAll(rz(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n)?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):rV(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function rq(e,t){var n,r;return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||!(!n||!r)&&Q(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof rS&&r instanceof rS||n instanceof rD&&r instanceof rD?Q(n.elements,r.elements,nu):n instanceof rN&&r instanceof rN?nu(n.Ee,r.Ee):n instanceof rE&&r instanceof rE)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class rU extends rP{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class rB extends rP{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.prec
1ondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function rz(e){let t=new Map;return e.fieldMask.fields.forEach(n=>{if(!n.isEmpty()){let r=e.data.field(n);t.set(n,r)}}),t}function r$(e,t,n){let r=new Map;C(e.length===n.length,32656,{Ae:n.length,Re:e.length});for(let s=0;s<n.length;s++){var i;let a=e[s],o=a.transform,l=t.data.field(a.field);r.set(a.field,(i=n[s],o instanceof rS?rx(o,l):o instanceof rD?rC(o,l):i))}return r}function rK(e,t,n){let r=new Map;for(let i of e){let e=i.transform,s=n.data.field(i.field);r.set(i.field,e instanceof rE?function(e,t){let n={fields:{[t5]:{stringValue:t2},[t4]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&t3(t)&&(t=t8(t)),t&&(n.fields[t6]=t),{mapValue:n}}(t,s):e instanceof rS?rx(e,s):e instanceof rD?rC(e,s):function(e,t){let n=rT(e,t),r=rA(n)+rA(e.Ee);return np(n)&&np(e.Ee)?rb(r):rv(e.serializer,r)}(e,s))}return r}class rj extends rP{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rG extends rP{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class rQ{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let r=this.mutations[t];r.key.isEqual(e.key)&&function(e,t,n){e instanceof rU?function(e,t,n){let r=e.value.clone(),i=r$(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof rB?function(e,t,n){if(!rV(e.precondition,t))return t.convertToUnknownDocument(n.version);let r=r$(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(rz(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}(r,e,n[t])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=rL(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=rL(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=rm();return this.mutations.forEach(r=>{let i=e.get(r.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=rM(s,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(eh.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),ry())}isEqual(e){return this.batchId===e.batchId&&Q(this.mutations,e.mutations,(e,t)=>rq(e,t))&&Q(this.baseMutations,e.baseMutations,(e,t)=>rq(e,t))}}class rW{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){C(e.mutations.length===n.length,58842,{Ve:e.mutations.length,me:n.length});let r=rg,i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new rW(e,t,n,r)}}class rH{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{
2      largestBatchId: ${this.largestBatchId},
3      mutation: ${this.mutation.toString()}
4    }`}}class rJ{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class rX{constructor(e,t){this.count=e,this.unchangedNames=t}}function rY(e){switch(e){case A.OK:return x(64938);case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return x(15467,{code:e})}}function rZ(e){if(void 0===e)return T("GRPC error has no .code"),A.UNKNOWN;switch(e){case r.OK:return A.OK;case r.CANCELLED:return A.CANCELLED;case r.UNKNOWN:return A.UNKNOWN;case r.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case r.INTERNAL:return A.INTERNAL;case r.UNAVAILABLE:return A.UNAVAILABLE;case r.UNAUTHENTICATED:return A.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case r.NOT_FOUND:return A.NOT_FOUND;case r.ALREADY_EXISTS:return A.ALREADY_EXISTS;case r.PERMISSION_DENIED:return A.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case r.ABORTED:return A.ABORTED;case r.OUT_OF_RANGE:return A.OUT_OF_RANGE;
4case r.UNIMPLEMENTED:return A.UNIMPLEMENTED;case r.DATA_LOSS:return A.DATA_LOSS;default:return x(39323,{code:e})}}(i=r||(r={}))[i.OK=0]="OK",i[i.CANCELLED=1]="CANCELLED",i[i.UNKNOWN=2]="UNKNOWN",i[i.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",i[i.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",i[i.NOT_FOUND=5]="NOT_FOUND",i[i.ALREADY_EXISTS=6]="ALREADY_EXISTS",i[i.PERMISSION_DENIED=7]="PERMISSION_DENIED",i[i.UNAUTHENTICATED=16]="UNAUTHENTICATED",i[i.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",i[i.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",i[i.ABORTED=10]="ABORTED",i[i.OUT_OF_RANGE=11]="OUT_OF_RANGE",i[i.UNIMPLEMENTED=12]="UNIMPLEMENTED",i[i.INTERNAL=13]="INTERNAL",i[i.UNAVAILABLE=14]="UNAVAILABLE",i[i.DATA_LOSS=15]="DATA_LOSS";let r0=null,r1=new h.jz([0xffffffff,0xffffffff],0);function r2(e){let t=z().encode(e),n=new h.VV;return n.update(t),new Uint8Array(n.digest())}function r5(e){let t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new h.jz([n,r],0),new h.jz([i,s],0)]}class r6{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new r4(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new r4(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new r4(`Invalid padding when bitmap length is 0: ${t}`);this.fe=8*e.length-t,this.ge=h.jz.fromNumber(this.fe)}pe(e,t,n){let r=e.add(t.multiply(h.jz.fromNumber(n)));return 1===r.compare(r1)&&(r=new h.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.ge).toNumber()}ye(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.fe)return!1;let[t,n]=r5(r2(e));for(let e=0;e<this.hashCount;e++){let r=this.pe(t,n,e);if(!this.ye(r))return!1}return!0}static create(e,t,n){let r=new r6(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);return n.forEach(e=>r.insert(e)),r}insert(e){if(0===this.fe)return;let[t,n]=r5(r2(e));for(let e=0;e<this.hashCount;e++){let r=this.pe(t,n,e);this.we(r)}}we(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class r4 extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class r3{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let r=new Map;return r.set(e,r8.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r3(eh.min(),r,new tz(K),rc,ry())}}class r8{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new r8(n,t,ry(),ry(),ry())}}class r9{constructor(e,t,n,r){this.Se=e,this.removedTargetIds=t,this.key=n,this.be=r}}class r7{constructor(e,t){this.targetId=e,this.De=t}}class ie{constructor(e,t,n=tX.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class it{constructor(){this.ve=0,this.Ce=is(),this.Fe=tX.EMPTY_BYTE_STRING,this.Me=!1,this.xe=!0}get current(){return this.Me}get resumeToken(){return this.Fe}get Oe(){return 0!==this.ve}get Ne(){return this.xe}Be(e){e.approximateByteSize()>0&&(this.xe=!0,this.Fe=e)}Le(){let e=ry(),t=ry(),n=ry();return this.Ce.forEach((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:x(38017,{changeType:i})}}),new r8(this.Fe,this.Me,e,t,n)}ke(){this.xe=!1,this.Ce=is()}qe(e,t){this.xe=!0,this.Ce=this.Ce.insert(e,t)}Qe(e){this.xe=!0,this.Ce=this.Ce.remove(e)}$e(){this.ve+=1}Ue(){this.ve-=1,C(this.ve>=0,3241,{ve:this.ve})}Ke(){this.xe=!0,this.Me=!0}}class ir{constructor(e){this.We=e,this.Ge=new Map,this.ze=rc,this.je=ii(),this.Je=ii(),this.He=new tz(K)}Ye(e){for(let t of e.Se)e.be&&e.be.isFoundDocument()?this.Ze(t,e.be):this.Xe(t,e.key,e.be);for(let t of e.removedTargetIds)this.Xe(t,e.key,e.be)}et(e){this.forEachTarget(e,t=>{let n=this.tt(t);switch(e.state){case 0:this.nt(t)&&n.Be(e.resumeToken);break;case 1:n.Ue(),n.Oe||n.ke(),n.Be(e.resumeToken);break;case 2:n.Ue(),n.Oe||this.removeTarget(t);break;case 3:this.nt(t)&&(n.Ke(),n.Be(e.resumeToken));break;case 4:this.nt(t)&&(this.rt(t),n.Be(e.resumeToken));break;default:x(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Ge.forEach((e,n)=>{this.nt(n)&&t(n)})}it(e){let t=e.targetId,n=e.De.count,r=this.st(t);if(r){let i=r.target;if(nZ(i))if(0===n){let e=new Z(i.path);this.Xe(t,e,nC.newNoDocument(e,eh.min()))}else C(1===n,20013,{expectedCount:n});else{let r=this.ot(t);if(r!==n){let n=this._t(e),i=n?this.ut(n,e,r):1;0!==i&&(this.rt(t),this.He=this.He.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch")),null==r0||r0.ct(function(e,t,n,r,i){var s,a,o,l,u,c;let h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===i,hashCount:null!=(s=null==d?void 0:d.hashCount)?s:0,bitmapLength:null!=(l=null==(o=null==(a=null==d?void 0:d.bits)?void 0:a.bitmap)?void 0:o.length)?l:0,padding:null!=(c=null==(u=null==d?void 0:d.bits)?void 0:u.padding)?c:0,mightContain:e=>{var t;return null!=(t=null==r?void 0:r.mightContain(e))&&t}}),h}(r,e.De,this.We.lt(),n,i))}}}}_t(e){let t,n,r=e.De.unchangedNames;if(!r||!r.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=r;try{t=t1(i).toUint8Array()}catch(e){if(e instanceof tH)return E("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{n=new r6(t,s,a)}catch(e){return E(e instanceof r4?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===n.fe?null:n}ut(e,t,n){return 2*(t.De.count!==n-this.ht(e,t.targetId))}ht(e,t){let n=this.We.getRemoteKeysForTarget(t),r=0;
4return n.forEach(n=>{let i=this.We.lt(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.Xe(t,n,null),r++)}),r}Pt(e){let t=new Map;this.Ge.forEach((n,r)=>{let i=this.st(r);if(i){if(n.current&&nZ(i.target)){let t=new Z(i.target.path);this.Tt(t).has(r)||this.It(r,t)||this.Xe(r,t,nC.newNoDocument(t,e))}n.Ne&&(t.set(r,n.Le()),n.ke())}});let n=ry();this.Je.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{let t=this.st(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.ze.forEach((t,n)=>n.setReadTime(e));let r=new r3(e,t,this.He,this.ze,n);return this.ze=rc,this.je=ii(),this.Je=ii(),this.He=new tz(K),r}Ze(e,t){if(!this.nt(e))return;let n=2*!!this.It(e,t.key);this.tt(e).qe(t.key,n),this.ze=this.ze.insert(t.key,t),this.je=this.je.insert(t.key,this.Tt(t.key).add(e)),this.Je=this.Je.insert(t.key,this.dt(t.key).add(e))}Xe(e,t,n){if(!this.nt(e))return;let r=this.tt(e);this.It(e,t)?r.qe(t,1):r.Qe(t),this.Je=this.Je.insert(t,this.dt(t).delete(e)),this.Je=this.Je.insert(t,this.dt(t).add(e)),n&&(this.ze=this.ze.insert(t,n))}removeTarget(e){this.Ge.delete(e)}ot(e){let t=this.tt(e).Le();return this.We.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.tt(e).$e()}tt(e){let t=this.Ge.get(e);return t||(t=new it,this.Ge.set(e,t)),t}dt(e){let t=this.Je.get(e);return t||(t=new tj(K),this.Je=this.Je.insert(e,t)),t}Tt(e){let t=this.je.get(e);return t||(t=new tj(K),this.je=this.je.insert(e,t)),t}nt(e){let t=null!==this.st(e);return t||_("WatchChangeAggregator","Detected inactive target",e),t}st(e){let t=this.Ge.get(e);return t&&t.Oe?null:this.We.Et(e)}rt(e){this.Ge.set(e,new it),this.We.getRemoteKeysForTarget(e).forEach(t=>{this.Xe(e,t,null)})}It(e,t){return this.We.getRemoteKeysForTarget(e).has(t)}}function ii(){return new tz(Z.comparator)}function is(){return new tz(Z.comparator)}let ia={asc:"ASCENDING",desc:"DESCENDING"},io={"<":"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"},il={and:"AND",or:"OR"};class iu{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function ic(e,t){return e.useProto3Json||eB(t)?t:{value:t}}function ih(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function id(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function im(e){return C(!!e,49232),eh.fromTimestamp(function(e){let t=tZ(e);return new ec(t.seconds,t.nanos)}(e))}function ig(e,t){return ip(e,t).canonicalString()}function ip(e,t){let n=new J(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function iy(e){let t=J.fromString(e);return C(iO(t),10190,{key:t.toString()}),t}function iw(e,t){return ig(e.databaseId,t.path)}function iv(e,t){let n=iy(t);if(n.get(1)!==e.databaseId.projectId)throw new k(A.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new k(A.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new Z(iT(n))}function ib(e,t){return ig(e.databaseId,t)}function iI(e){let t=iy(e);return 4===t.length?J.emptyPath():iT(t)}function i_(e){return new J(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function iT(e){return C(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function iE(e,t,n){return{name:iw(e,t),fields:n.value.mapValue.fields}}function iS(e,t,n){let r=iv(e,t.name),i=im(t.updateTime),s=t.createTime?im(t.createTime):eh.min(),a=new nD({mapValue:{fields:t.fields}}),o=nC.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function ix(e,t){var n;let r;if(t instanceof rU)r={update:iE(e,t.key,t.value)};else if(t instanceof rj)r={delete:iw(e,t.key)};else if(t instanceof rB)r={update:iE(e,t.key,t.data),updateMask:function(e){let t=[];
4return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof rG))return x(16599,{Rt:t.type});r={verify:iw(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof rE)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof rS)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof rD)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof rN)return{fieldPath:t.field.canonicalString(),increment:n.Ee};throw x(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:ih(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:x(27497)),r}function iD(e,t){var n;let r=t.currentDocument?void 0!==(n=t.currentDocument).updateTime?rO.updateTime(im(n.updateTime)):void 0!==n.exists?rO.exists(n.exists):rO.none():rO.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let n;return n=null,"setToServerValue"in t?(C("REQUEST_TIME"===t.setToServerValue,16630,{proto:t}),n=new rE):"appendMissingElements"in t?n=new rS(t.appendMissingElements.values||[]):"removeAllFromArray"in t?n=new rD(t.removeAllFromArray.values||[]):"increment"in t?n=new rN(e,t.increment):x(16584,{proto:t}),new rR(Y.fromServerFormat(t.fieldPath),n)}):[];if(t.update){t.update.name;let n=iv(e,t.update.name),s=new nD({mapValue:{fields:t.update.fields}});return t.updateMask?new rB(n,s,new tW((t.updateMask.fieldPaths||[]).map(e=>Y.fromServerFormat(e))),r,i):new rU(n,s,r,i)}return t.delete?new rj(iv(e,t.delete),r):t.verify?new rG(iv(e,t.verify),r):x(1463,{proto:t})}function iC(e,t){return{documents:[ib(e,t.path)]}}function iN(e,t){var n,r;let i,s={structuredQuery:{}},a=t.path;null!==t.collectionGroup?(i=a,s.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=a.popLast(),s.structuredQuery.from=[{collectionId:a.lastSegment()}]),s.parent=ib(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof nO?function(e){if("=="===e.op){if(nv(e.value))return{unaryFilter:{field:iR(e.field),op:"IS_NAN"}};if(nw(e.value))return{unaryFilter:{field:iR(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(nv(e.value))return{unaryFilter:{field:iR(e.field),op:"IS_NOT_NAN"}};if(nw(e.value))return{unaryFilter:{field:iR(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:iR(e.field),op:io[e.op],value:e.value}}}(t):t instanceof nV?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:il[t.op],filters:n}}}(t):x(54877,{filter:t})}(nV.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:iR(e.field),direction:ia[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=ic(e,t.limit);return null!==u&&(s.structuredQuery.limit=u),t.startAt&&(s.structuredQuery.startAt={before:(n=t.startAt).inclusive,values:n.position}),t.endAt&&(s.structuredQuery.endAt={before:!(r=t.endAt).inclusive,values:r.position}),{Vt:s,parent:i}}function iA(e,t,n,r){let{Vt:i,parent:s}=iN(e,t),a={},o=[],l=0;return n.forEach(e=>{let t=r?e.alias:"aggregate_"+l++;a[t]=e.alias,"count"===e.aggregateType?o.push({alias:t,count:{}}):"avg"===e.aggregateType?o.push({alias:t,avg:{field:iR(e.fieldPath)}}):"sum"===e.aggregateType&&o.push({alias:t,sum:{field:iR(e.fieldPath)}})}),{request:{structuredAggregationQuery:{aggregations:o,structuredQuery:i.structuredQuery},parent:i.parent},ft:a,parent:s}}function ik(e){var t;let n,r=iI(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){C(1===s,65062);let e=i.from[0];e.allDescendants?a=e.collectionId:r=r.child(e.collectionId)}let o=[];i.where&&(o=function(e){let t=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=iF(e.unaryFilter.field);return nO.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=iF(e.unaryFilter.field);return nO.create(n,"==",{nullValue:"NULL_VALUE"});
4case"IS_NOT_NAN":let r=iF(e.unaryFilter.field);return nO.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=iF(e.unaryFilter.field);return nO.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return x(61313);default:return x(60726)}}(t):void 0!==t.fieldFilter?nO.create(iF(t.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return x(58110);default:return x(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?nV.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return x(1026)}}(t.compositeFilter.op)):x(30097,{filter:t})}(e);return t instanceof nV&&nL(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new nR(iF(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=eB(n="object"==typeof(t=i.limit)?t.value:t)?null:n);let c=null;i.startAt&&(c=function(e){let t=!!e.before;return new nN(e.values||[],t)}(i.startAt));let h=null;return i.endAt&&(h=function(e){let t=!e.before;return new nN(e.values||[],t)}(i.endAt)),new n5(r,a,l,o,u,"F",c,h)}function iR(e){return{fieldPath:e.canonicalString()}}function iF(e){return Y.fromServerFormat(e.fieldPath)}function iO(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class iV{constructor(e,t,n,r,i=eh.min(),s=eh.min(),a=tX.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new iV(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new iV(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new iV(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new iV(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class iP{constructor(e){this.gt=e}}function iM(e,t){let n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:iL(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;r.document={name:iw(i=e.gt,t.key),fields:t.data.value.mapValue.fields,updateTime:ih(i,t.version.toTimestamp()),createTime:ih(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:iq(t.version)};else{if(!t.isUnknownDocument())return x(57904,{document:t});r.unknownDocument={path:n.path.toArray(),version:iq(t.version)}}return r}function iL(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function iq(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function iU(e){let t=new ec(e.seconds,e.nanoseconds);return eh.fromTimestamp(t)}function iB(e,t){let n=(t.baseMutations||[]).map(t=>iD(e.gt,t));for(let e=0;e<t.mutations.length-1;++e){let n=t.mutations[e];e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform&&(n.updateTransforms=t.mutations[e+1].transform.fieldTransforms,t.mutations.splice(e+1,1),++e)}let r=t.mutations.map(t=>iD(e.gt,t)),i=ec.fromMillis(t.localWriteTimeMs);return new rQ(t.batchId,i,n,r)}function iz(e){let t=iU(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?iU(e.lastLimboFreeSnapshotVersion):eh.min();return new iV(void 0!==e.query.documents?function(e){let t=e.documents.length;return C(1===t,1966,{count:t}),n9(n6(iI(e.documents[0])))}(e.query):n9(ik(e.query)),e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,tX.fromBase64String(e.resumeToken))}function i$(e,t){let n,r=iq(t.snapshotVersion),i=iq(t.lastLimboFreeSnapshotVersion);n=nZ(t.target)?iC(e.gt,t.target):iN(e.gt,t.target).Vt;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:nX(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function iK(e){let t=ik({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?rn(t,t.limit,"L"):t}function ij(e,t){return new rH(t.largestBatchId,iD(e.gt,t.overlayMutation))}function iG(e,t){let n=t.path.lastSegment();return[e,eK(t.path.popLast()),n]}function iQ(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:iq(r.readTime),documentKey:eK(r.documentKey.path),largestBatchId:r.largestBatchId}}class iW{getBundleMetadata(e,t){return tM(e,td).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:iU(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return tM(e,td).put({bundleId:t.id,createTime:iq(im(t.createTime)),version:t.version})}getNamedQuery(e,t){return tM(e,tf).get(t).next(e=>{if(e)return{name:e.name,query:iK(e.bundledQuery),readTime:iU(e.readTime)}})}saveNamedQuery(e,t){return tM(e,tf).put({name:t.name,readTime:iq(im(t.readTime)),bundledQuery:t.bundledQuery})}}
4class iH{constructor(e,t){this.serializer=e,this.userId=t}static yt(e,t){return new iH(e,t.uid||"")}getOverlay(e,t){return tM(e,tE).get(iG(this.userId,t)).next(e=>e?ij(this.serializer,e):null)}getOverlays(e,t){let n=rm();return eS.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){let r=[];return n.forEach((n,i)=>{let s=new rH(t,i);r.push(this.wt(e,s))}),eS.waitFor(r)}removeOverlaysForBatchId(e,t,n){let r=new Set;t.forEach(e=>r.add(eK(e.getCollectionPath())));let i=[];return r.forEach(t=>{let r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(tM(e,tE).Y(tx,r))}),eS.waitFor(i)}getOverlaysForCollection(e,t,n){let r=rm(),i=eK(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,1/0],!0);return tM(e,tE).j(tx,s).next(e=>{for(let t of e){let e=ij(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){let i,s=rm(),a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,1/0],!0);return tM(e,tE).X({index:tC,range:a},(e,t,n)=>{let a=ij(this.serializer,t);s.size()<r||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):n.done()}).next(()=>s)}wt(e,t){return tM(e,tE).put(function(e,t,n){let[r,i,s]=iG(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:ix(e.gt,n.mutation)}}(this.serializer,this.userId,t))}}class iJ{St(e){return tM(e,tA)}getSessionToken(e){return this.St(e).get("sessionToken").next(e=>{let t=null==e?void 0:e.value;return t?tX.fromUint8Array(t):tX.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.St(e).put({name:"sessionToken",value:t.toUint8Array()})}}class iX{constructor(){}bt(e,t){this.Dt(e,t),t.vt()}Dt(e,t){if("nullValue"in e)this.Ct(t,5);else if("booleanValue"in e)this.Ct(t,10),t.Ft(+!!e.booleanValue);else if("integerValue"in e)this.Ct(t,15),t.Ft(t0(e.integerValue));else if("doubleValue"in e){let n=t0(e.doubleValue);isNaN(n)?this.Ct(t,13):(this.Ct(t,15),ez(n)?t.Ft(0):t.Ft(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Ct(t,20),"string"==typeof n&&(n=tZ(n)),t.Mt(`${n.seconds||""}`),t.Ft(n.nanos||0)}else if("stringValue"in e)this.xt(e.stringValue,t),this.Ot(t);else if("bytesValue"in e)this.Ct(t,30),t.Nt(t1(e.bytesValue)),this.Ot(t);else if("referenceValue"in e)this.Bt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Ct(t,45),t.Ft(n.latitude||0),t.Ft(n.longitude||0)}else"mapValue"in e?nT(e)?this.Ct(t,Number.MAX_SAFE_INTEGER):nI(e)?this.Lt(e.mapValue,t):(this.kt(e.mapValue,t),this.Ot(t)):"arrayValue"in e?(this.qt(e.arrayValue,t),this.Ot(t)):x(19022,{Qt:e})}xt(e,t){this.Ct(t,25),this.$t(e,t)}$t(e,t){t.Mt(e)}kt(e,t){let n=e.fields||{};for(let e of(this.Ct(t,55),Object.keys(n)))this.xt(e,t),this.Dt(n[e],t)}Lt(e,t){var n,r;let i=e.fields||{};this.Ct(t,53);let s=(null==(r=null==(n=i[na].arrayValue)?void 0:n.values)?void 0:r.length)||0;this.Ct(t,15),t.Ft(t0(s)),this.xt(na,t),this.Dt(i[na],t)}qt(e,t){let n=e.values||[];for(let e of(this.Ct(t,50),n))this.Dt(e,t)}Bt(e,t){this.Ct(t,37),Z.fromName(e).path.forEach(e=>{this.Ct(t,60),this.$t(e,t)})}Ct(e,t){e.Ft(t)}Ot(e){e.Ft(2)}}function iY(e){return Math.ceil((64-function(e){let t=0;for(let n=0;n<8;++n){let r=function(e){if(0===e)return 8;let t=0;return e>>4||(t+=4,e<<=4),e>>6||(t+=2,e<<=2),e>>7||(t+=1),t}(255&e[n]);if(t+=r,8!==r)break}return t}(e))/8)}iX.Ut=new iX;class iZ{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Kt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.Wt(n.value),n=t.next();this.Gt()}zt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.jt(n.value),n=t.next();this.Jt()}Ht(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Wt(e);else if(e<2048)this.Wt(960|e>>>6),this.Wt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Wt(480|e>>>12),this.Wt(128|63&e>>>6),this.Wt(128|63&e);else{let e=t.codePointAt(0);this.Wt(240|e>>>18),this.Wt(128|63&e>>>12),this.Wt(128|63&e>>>6),this.Wt(128|63&e)}}this.Gt()}Yt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.jt(e);else if(e<2048)this.jt(960|e>>>6),this.jt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.jt(480|e>>>12),this.jt(128|63&e>>>6),this.jt(128|63&e);else{let e=t.codePointAt(0);this.jt(240|e>>>18),this.jt(128|63&e>>>12),this.jt(128|63&e>>>6),this.jt(128|63&e)}}this.Jt()}
4Zt(e){let t=this.Xt(e),n=iY(t);this.en(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}tn(e){let t=this.Xt(e),n=iY(t);this.en(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}nn(){this.rn(255),this.rn(255)}sn(){this._n(255),this._n(255)}reset(){this.position=0}seed(e){this.en(e.length),this.buffer.set(e,this.position),this.position+=e.length}an(){return this.buffer.slice(0,this.position)}Xt(e){let t=function(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=!!(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=255*!!n;return t}Wt(e){let t=255&e;0===t?(this.rn(0),this.rn(255)):255===t?(this.rn(255),this.rn(0)):this.rn(t)}jt(e){let t=255&e;0===t?(this._n(0),this._n(255)):255===t?(this._n(255),this._n(0)):this._n(e)}Gt(){this.rn(0),this.rn(1)}Jt(){this._n(0),this._n(1)}rn(e){this.en(1),this.buffer[this.position++]=e}_n(e){this.en(1),this.buffer[this.position++]=~e}en(e){let t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);let r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class i0{constructor(e){this.un=e}Nt(e){this.un.Kt(e)}Mt(e){this.un.Ht(e)}Ft(e){this.un.Zt(e)}vt(){this.un.nn()}}class i1{constructor(e){this.un=e}Nt(e){this.un.zt(e)}Mt(e){this.un.Yt(e)}Ft(e){this.un.tn(e)}vt(){this.un.sn()}}class i2{constructor(){this.un=new iZ,this.cn=new i0(this.un),this.ln=new i1(this.un)}seed(e){this.un.seed(e)}hn(e){return 0===e?this.cn:this.ln}an(){return this.un.an()}reset(){this.un.reset()}}class i5{constructor(e,t,n,r){this.Pn=e,this.Tn=t,this.In=n,this.dn=r}En(){let e=this.dn.length,t=0===e||255===this.dn[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.dn,0),t!==e?n.set([0],this.dn.length):++n[n.length-1],new i5(this.Pn,this.Tn,this.In,n)}An(e,t,n){return{indexId:this.Pn,uid:e,arrayValue:i3(this.In),directionalValue:i3(this.dn),orderedDocumentKey:i3(t),documentKey:n.path.toArray()}}Rn(e,t,n){let r=this.An(e,t,n);return[r.indexId,r.uid,r.arrayValue,r.directionalValue,r.orderedDocumentKey,r.documentKey]}}function i6(e,t){let n=e.Pn-t.Pn;return 0!==n||0!==(n=i4(e.In,t.In))||0!==(n=i4(e.dn,t.dn))?n:Z.comparator(e.Tn,t.Tn)}function i4(e,t){for(let n=0;n<e.length&&n<t.length;++n){let r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}function i3(e){return(0,c.Ov)()?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}(e):e}function i8(e){return"string"!=typeof e?e:function(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(e)}class i9{constructor(e){for(let t of(this.Vn=new tj((e,t)=>Y.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.mn=e.orderBy,this.fn=[],e.filters))t.isInequality()?this.Vn=this.Vn.add(t):this.fn.push(t)}get gn(){return this.Vn.size>1}pn(e){if(C(e.collectionGroup===this.collectionId,49279),this.gn)return!1;let t=ef(e);if(void 0!==t&&!this.yn(t))return!1;let n=em(e),r=new Set,i=0,s=0;for(;i<n.length&&this.yn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.Vn.size>0){let e=this.Vn.getIterator().getNext();if(!r.has(e.field.canonicalString())){let t=n[i];if(!this.wn(e,t)||!this.Sn(this.mn[s++],t))return!1}++i}for(;i<n.length;++i){let e=n[i];if(s>=this.mn.length||!this.Sn(this.mn[s++],e))return!1}return!0}bn(){if(this.gn)return null;let e=new tj(Y.comparator),t=[];for(let n of this.fn)if(!n.field.isKeyField())if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new ep(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new ep(n.field,0))}for(let n of this.mn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new ep(n.field,+("asc"!==n.dir))));return new ed(ed.UNKNOWN_ID,this.collectionId,t,ey.empty())}yn(e){for(let t of this.fn)if(this.wn(t,e))return!0;return!1}wn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;let n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}Sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function i7(e){return e instanceof nO}function se(e){return e instanceof nV&&nL(e)}function st(e){return i7(e)||se(e)||function(e){if(e instanceof nV&&nM(e)){for(let t of e.getFilters())if(!i7(t)&&!se(t))return!1;return!0}return!1}(e)}function sn(e,t){return C(e instanceof nO||e instanceof nV,38388),C(t instanceof nO||t instanceof nV,25473),si(e instanceof nO?t instanceof nO?nV.create([e,t],"and"):sr(e,t):t instanceof nO?sr(t,e):function(e,t){if(C(e.filters.length>0&&t.filters.length>0,48005),nP(e)&&nP(t))return nU(e,t.getFilters());let n=nM(e)?e:t,r=nM(e)?t:e,i=n.filters.map(e=>sn(e,r));return nV.create(i,"or")}(e,t))}function sr(e,t){if(nP(t))return nU(t,e.getFilters());{let n=t.filters.map(t=>sn(e,t));return nV.create(n,"or")}}function si(e){if(C(e instanceof nO||e instanceof nV,11850),e instanceof nO)return e;let t=e.getFilters();if(1===t.length)return si(t[0]);if(nq(e))return e;let n=t.map(e=>si(e)),r=[];
4return n.forEach(t=>{t instanceof nO?r.push(t):t instanceof nV&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:nV.create(r,e.op)}class ss{constructor(){this.Dn=new sa}addToCollectionParentIndex(e,t){return this.Dn.add(t),eS.resolve()}getCollectionParents(e,t){return eS.resolve(this.Dn.getEntries(t))}addFieldIndex(e,t){return eS.resolve()}deleteFieldIndex(e,t){return eS.resolve()}deleteAllFieldIndexes(e){return eS.resolve()}createTargetIndexes(e,t){return eS.resolve()}getDocumentsMatchingTarget(e,t){return eS.resolve(null)}getIndexType(e,t){return eS.resolve(0)}getFieldIndexes(e,t){return eS.resolve([])}getNextCollectionGroupToUpdate(e){return eS.resolve(null)}getMinOffset(e,t){return eS.resolve(eb.min())}getMinOffsetFromCollectionGroup(e,t){return eS.resolve(eb.min())}updateCollectionGroup(e,t,n){return eS.resolve()}updateIndexEntries(e,t){return eS.resolve()}}class sa{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new tj(J.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new tj(J.comparator)).toArray()}}let so="IndexedDbIndexManager",sl=new Uint8Array(0);class su{constructor(e,t){this.databaseId=t,this.vn=new sa,this.Cn=new ru(e=>nX(e),(e,t)=>nY(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.vn.has(t)){let n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.vn.add(t)});let i={collectionId:n,parent:eK(r)};return tM(e,tu).put(i)}return eS.resolve()}getCollectionParents(e,t){let n=[],r=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return tM(e,tu).j(r).next(e=>{for(let r of e){if(r.collectionId!==t)break;n.push(ej(r.parent))}return n})}addFieldIndex(e,t){let n=tM(e,tm),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;let i=n.add(r);if(t.indexState){let n=tM(e,tp);return i.next(e=>{n.put(iQ(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let n=tM(e,tm),r=tM(e,tp),i=tM(e,tb);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=tM(e,tm),n=tM(e,tb),r=tM(e,tp);return t.Y().next(()=>n.Y()).next(()=>r.Y())}
4createTargetIndexes(e,t){return eS.forEach(this.Fn(t),t=>this.getIndexType(e,t).next(n=>{if(0===n||1===n){let n=new i9(t).bn();if(null!=n)return this.addFieldIndex(e,n)}}))}getDocumentsMatchingTarget(e,t){let n=tM(e,tb),r=!0,i=new Map;return eS.forEach(this.Fn(t),t=>this.Mn(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>{if(r){let e=ry(),r=[];return eS.forEach(i,(i,s)=>{_(so,`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${nX(t)}`);let a=function(e,t){let n=ef(t);if(void 0===n)return null;for(let t of n0(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),o=function(e,t){let n=new Map;for(let r of em(t))for(let t of n0(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(s,i),l=function(e,t){let n=[],r=!0;for(let i of em(t)){let t=0===i.kind?n1(e,i.fieldPath,e.startAt):n2(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new nN(n,r)}(s,i),u=function(e,t){let n=[],r=!0;for(let i of em(t)){let t=0===i.kind?n2(e,i.fieldPath,e.endAt):n1(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new nN(n,r)}(s,i),c=this.xn(i,s,l),h=this.xn(i,s,u),d=this.On(i,s,o),f=this.Nn(i.indexId,a,c,l.inclusive,h,u.inclusive,d);
4return eS.forEach(f,i=>n.H(i,t.limit).next(t=>{t.forEach(t=>{let n=Z.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return eS.resolve(null)})}Fn(e){let t=this.Cn.get(e);return t||(t=0===e.filters.length?[e]:(function(e){if(0===e.getFilters().length)return[];let t=function e(t){if(C(t instanceof nO||t instanceof nV,34018),t instanceof nO)return t;if(1===t.filters.length)return e(t.filters[0]);let n=t.filters.map(t=>e(t)),r=nV.create(n,t.op);return st(r=si(r))?r:(C(r instanceof nV,64498),C(nP(r),40251),C(r.filters.length>1,57927),r.filters.reduce((e,t)=>sn(e,t)))}(function e(t){var n,r;if(C(t instanceof nO||t instanceof nV,20012),t instanceof nO){if(t instanceof nG){let e=(null==(r=null==(n=t.value.arrayValue)?void 0:n.values)?void 0:r.map(e=>nO.create(t.field,"==",e)))||[];return nV.create(e,"or")}return t}let i=t.filters.map(t=>e(t));return nV.create(i,t.op)}(e));return C(st(t),7391),i7(t)||se(t)?[t]:t.getFilters()})(nV.create(e.filters,"and")).map(t=>nJ(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.Cn.set(e,t)),t}Nn(e,t,n,r,i,s,a){let o=(null!=t?t.length:1)*Math.max(n.length,i.length),l=o/(null!=t?t.length:1),u=[];for(let c=0;c<o;++c){let o=t?this.Bn(t[c/l]):sl,h=this.Ln(e,o,n[c%l],r),d=this.kn(e,o,i[c%l],s),f=a.map(t=>this.Ln(e,o,t,!0));u.push(...this.createRange(h,d,f))}return u}Ln(e,t,n,r){let i=new i5(e,Z.empty(),t,n);return r?i:i.En()}kn(e,t,n,r){let i=new i5(e,Z.empty(),t,n);return r?i.En():i}Mn(e,t){let n=new i9(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{let t=null;for(let r of e)n.pn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let n=2,r=this.Fn(t);
4return eS.forEach(r,t=>this.Mn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new tj(Y.comparator),n=!1;for(let r of e.filters)for(let e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(let n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+ +!!n}(t)&&(n=1):n=0})).next(()=>null!==t.limit&&r.length>1&&2===n?1:n)}qn(e,t){let n=new i2;for(let r of em(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;let i=n.hn(r.kind);iX.Ut.bt(e,i)}return n.an()}Bn(e){let t=new i2;return iX.Ut.bt(e,t.hn(0)),t.an()}Qn(e,t){let n=new i2;return iX.Ut.bt(ng(this.databaseId,t),n.hn(function(e){let t=em(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.an()}On(e,t,n){if(null===n)return[];let r=[];r.push(new i2);let i=0;for(let s of em(e)){let e=n[i++];for(let n of r)if(this.$n(t,s.fieldPath)&&ny(e))r=this.Un(r,s,e);else{let t=n.hn(s.kind);iX.Ut.bt(e,t)}}return this.Kn(r)}xn(e,t,n){return this.On(e,t,n.position)}Kn(e){let t=[];for(let n=0;n<e.length;++n)t[n]=e[n].an();return t}Un(e,t,n){let r=[...e],i=[];for(let e of n.arrayValue.values||[])for(let n of r){let r=new i2;r.seed(n.an()),iX.Ut.bt(e,r.hn(t.kind)),i.push(r)}return i}$n(e,t){return!!e.filters.find(e=>e instanceof nO&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let n=tM(e,tm),r=tM(e,tp);return(t?n.j(tg,IDBKeyRange.bound(t,t)):n.j()).next(e=>{let t=[];
4return eS.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){let n=t?new ey(t.sequenceNumber,new eb(iU(t.readTime),new Z(ej(t.documentKey)),t.largestBatchId)):ey.empty(),r=e.fields.map(([e,t])=>new ep(Y.fromServerFormat(e),t));return new ed(e.indexId,e.collectionGroup,r,n)}(e,n))})).next(()=>t)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{let n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:K(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){let r=tM(e,tm),i=tM(e,tp);return this.Wn(e).next(e=>r.j(tg,IDBKeyRange.bound(t,t)).next(t=>eS.forEach(t,t=>i.put(iQ(t.indexId,this.uid,e,n)))))}updateIndexEntries(e,t){let n=new Map;return eS.forEach(t,(t,r)=>{let i=n.get(t.collectionGroup);return(i?eS.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),eS.forEach(i,n=>this.Gn(e,t,n).next(t=>{let i=this.zn(r,n);return t.isEqual(i)?eS.resolve():this.jn(e,r,n,t,i)}))))})}Jn(e,t,n,r){return tM(e,tb).put(r.An(this.uid,this.Qn(n,t.key),t.key))}Hn(e,t,n,r){return tM(e,tb).delete(r.Rn(this.uid,this.Qn(n,t.key),t.key))}Gn(e,t,n){let r=tM(e,tb),i=new tj(i6);return r.X({index:t_,range:IDBKeyRange.only([n.indexId,this.uid,i3(this.Qn(n,t))])},(e,r)=>{i=i.add(new i5(n.indexId,t,i8(r.arrayValue),i8(r.directionalValue)))}).next(()=>i)}zn(e,t){let n=new tj(i6),r=this.qn(t,e);if(null==r)return n;let i=ef(t);if(null!=i){let s=e.data.field(i.fieldPath);if(ny(s))for(let i of s.arrayValue.values||[])n=n.add(new i5(t.indexId,e.key,this.Bn(i),r))}else n=n.add(new i5(t.indexId,e.key,sl,r));return n}jn(e,t,n,r,i){_(so,"Updating index entries for document '%s'",t.key);let s=[];return function(e,t,n,r,i){let s=e.getIterator(),a=t.getIterator(),o=tQ(s),l=tQ(a);for(;o||l;){let e=!1,t=!1;if(o&&l){let r=n(o,l);r<0?t=!0:r>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(l),l=tQ(a)):t?(i(o),o=tQ(s)):(o=tQ(s),l=tQ(a))}}(r,i,i6,r=>{s.push(this.Jn(e,t,n,r))},r=>{s.push(this.Hn(e,t,n,r))}),eS.waitFor(s)}Wn(e){let t=1;return tM(e,tp).X({index:tw,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,n,r)=>{r.done(),t=n.sequenceNumber+1}).next(()=>t)}createRange(e,t,n){n=n.sort((e,t)=>i6(e,t)).filter((e,t,n)=>!t||0!==i6(e,n[t-1]));let r=[];for(let i of(r.push(e),n)){let n=i6(i,e),s=i6(i,t);if(0===n)r[0]=e.En();else if(n>0&&s<0)r.push(i),r.push(i.En());else if(s>0)break}r.push(t);let i=[];for(let e=0;e<r.length;e+=2){if(this.Yn(r[e],r[e+1]))return[];let t=r[e].Rn(this.uid,sl,Z.empty()),n=r[e+1].Rn(this.uid,sl,Z.empty());i.push(IDBKeyRange.bound(t,n))}return i}Yn(e,t){return i6(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(sc)}getMinOffset(e,t){return eS.mapArray(this.Fn(t),t=>this.Mn(e,t).next(e=>e||x(44426))).next(sc)}}function sc(e){C(0!==e.length,28825);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){let i=e[r].indexState.offset;0>eI(i,t)&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new eb(t.readTime,t.documentKey,n)}let sh={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class sd{static withCacheSize(e){return new sd(e,sd.DEFAULT_COLLECTION_PERCENTILE,sd.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function sf(e,t,n){let r=e.store(eJ),i=e.store(e1),s=[],a=IDBKeyRange.only(n.batchId),o=0,l=r.X({range:a},(e,t,n)=>(o++,n.delete()));s.push(l.next(()=>{C(1===o,47070,{batchId:n.batchId})}));let u=[];for(let e of n.mutations){var c,h;let r=(c=e.key.path,h=n.batchId,[t,eK(c),h]);s.push(i.delete(r)),u.push(e.key)}return eS.waitFor(s).next(()=>u)}function sm(e){let t;if(!e)return 0;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw x(14731);t=e.noDocument}return JSON.stringify(t).length}sd.DEFAULT_COLLECTION_PERCENTILE=10,sd.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,sd.DEFAULT=new sd(0x2800000,sd.DEFAULT_COLLECTION_PE
4RCENTILE,sd.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),sd.DISABLED=new sd(-1,0,0);class sg{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Zn={}}static yt(e,t,n,r){return C(""!==e.uid,64387),new sg(e.isAuthenticated()?e.uid:"",t,n,r)}checkEmpty(e){let t=!0,n=IDBKeyRange.bound([this.userId,-1/0],[this.userId,1/0]);return sy(e).X({index:eY,range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){let i=tM(e,e1),s=sy(e);return s.add({}).next(a=>{C("number"==typeof a,49019);let o=new rQ(a,t,n,r),l=function(e,t,n){let r=n.baseMutations.map(t=>ix(e.gt,t)),i=n.mutations.map(t=>ix(e.gt,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,o),u=[],c=new tj((e,t)=>K(e.canonicalString(),t.canonicalString()));for(let e of r){var h,d;let t=(h=this.userId,d=e.key.path,[h,eK(d),a]);c=c.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,e0))}return c.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.Zn[a]=o.keys()}),eS.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return sy(e).get(t).next(e=>e?(C(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),iB(this.serializer,e)):null)}Xn(e,t){return this.Zn[t]?eS.resolve(this.Zn[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){let n=e.keys();return this.Zn[t]=n,n}return null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return sy(e).X({index:eY,range:r},(e,t,r)=>{t.userId===this.userId&&(C(t.batchId>=n,47524,{er:n}),i=iB(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,1/0]),n=-1;return sy(e).X({index:eY,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,1/0]);return sy(e).j(eY,t).next(e=>e.map(e=>iB(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let n=[this.userId,eK(t.path)],r=IDBKeyRange.lowerBound(n),i=[];return tM(e,e1).X({range:r},(n,r,s)=>{let[a,o,l]=n,u=ej(o);if(a===this.userId&&t.path.isEqual(u))return sy(e).get(l).next(e=>{if(!e)throw x(61480,{tr:n,batchId:l});C(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:l}),i.push(iB(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tj(K),r=[];return t.forEach(t=>{let i=[this.userId,eK(t.path)],s=IDBKeyRange.lowerBound(i),a=tM(e,e1).X({range:s},(e,r,i)=>{let[s,a,o]=e,l=ej(a);s===this.userId&&t.path.isEqual(l)?n=n.add(o):i.done()});r.push(a)}),eS.waitFor(r).next(()=>this.nr(e,n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=[this.userId,eK(n)],s=IDBKeyRange.lowerBound(i),a=new tj(K);return tM(e,e1).X({range:s},(e,t,i)=>{let[s,o,l]=e,u=ej(o);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(a=a.add(l)):i.done()}).next(()=>this.nr(e,a))}nr(e,t){let n=[],r=[];return t.forEach(t=>{r.push(sy(e).get(t).next(e=>{if(null===e)throw x(35274,{batchId:t});C(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),n.push(iB(this.serializer,e))}))}),eS.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return sf(e.ce,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.rr(t.batchId)}),eS.forEach(n,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}rr(e){delete this.Zn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>{if(!t)return eS.resolve();let n=IDBKeyRange.lowerBound([this.userId]),r=[];return tM(e,e1).X({range:n},(e,t,n)=>{if(e[0]===this.userId){let t=ej(e[1]);r.push(t)}else n.done()}).next(()=>{C(0===r.length,56720,{ir:r.map(e=>e.canonicalString())})})})}containsKey(e,t){return sp(e,this.userId,t)}sr(e){return tM(e,eH).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}
4function sp(e,t,n){let r=[t,eK(n.path)],i=r[1],s=IDBKeyRange.lowerBound(r),a=!1;return tM(e,e1).X({range:s,Z:!0},(e,n,r)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),r.done()}).next(()=>a)}function sy(e){return tM(e,eJ)}class sw{constructor(e){this._r=e}next(){return this._r+=2,this._r}static ar(){return new sw(0)}static ur(){return new sw(-1)}}class sv{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.cr(e).next(t=>{let n=new sw(t.highestTargetId);return t.highestTargetId=n.next(),this.lr(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.cr(e).next(e=>eh.fromTimestamp(new ec(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.cr(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,n){return this.cr(e).next(r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.lr(e,r)))}addTargetData(e,t){return this.hr(e,t).next(()=>this.cr(e).next(n=>(n.targetCount+=1,this.Pr(t,n),this.lr(e,n))))}updateTargetData(e,t){return this.hr(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>tM(e,te).delete(t.targetId)).next(()=>this.cr(e)).next(t=>(C(t.targetCount>0,8065),t.targetCount-=1,this.lr(e,t)))}removeTargets(e,t,n){let r=0,i=[];return tM(e,te).X((s,a)=>{let o=iz(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,i.push(this.removeTargetData(e,o)))}).next(()=>eS.waitFor(i)).next(()=>r)}forEachTarget(e,t){return tM(e,te).X((e,n)=>{t(iz(n))})}cr(e){return tM(e,tl).get(to).next(e=>(C(null!==e,2888),e))}lr(e,t){return tM(e,tl).put(to,t)}hr(e,t){return tM(e,te).put(i$(this.serializer,t))}Pr(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.cr(e).next(e=>e.targetCount)}getTargetData(e,t){let n=nX(t),r=IDBKeyRange.bound([n,-1/0],[n,1/0]),i=null;return tM(e,te).X({range:r,index:tt},(e,n,r)=>{let s=iz(n);nY(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){let r=[],i=sb(e);return t.forEach(t=>{let s=eK(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),eS.waitFor(r)}removeMatchingKeys(e,t,n){let r=sb(e);
4return eS.forEach(t,t=>{let i=eK(t.path);return eS.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){let n=sb(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){let n=IDBKeyRange.bound([t],[t+1],!1,!0),r=sb(e),i=ry();return r.X({range:n,Z:!0},(e,t,n)=>{let r=new Z(ej(e[1]));i=i.add(r)}).next(()=>i)}containsKey(e,t){let n=eK(t.path),r=IDBKeyRange.bound([n],[n+"\0"],!1,!0),i=0;return sb(e).X({index:ts,Z:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}Et(e,t){return tM(e,te).get(t).next(e=>e?iz(e):null)}}function sb(e){return tM(e,tr)}let sI="LruGarbageCollector";function s_([e,t],[n,r]){let i=K(e,n);return 0===i?K(t,r):i}class sT{constructor(e){this.Tr=e,this.buffer=new tj(s_),this.Ir=0}dr(){return++this.Ir}Er(e){let t=[e,this.dr()];if(this.buffer.size<this.Tr)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>s_(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class sE{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Ar=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Rr(6e4)}stop(){this.Ar&&(this.Ar.cancel(),this.Ar=null)}get started(){return null!==this.Ar}Rr(e){_(sI,`Garbage collection scheduled in ${e}ms`),this.Ar=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Ar=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){eR(e)?_(sI,"Ignoring IndexedDB error during garbage collection: ",e):await eE(e)}await this.Rr(3e5)})}}class sS{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.mr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return eS.resolve(eU.ue);let n=new sT(t);return this.Vr.forEachTarget(e,e=>n.Er(e.sequenceNumber)).next(()=>this.Vr.gr(e,e=>n.Er(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Vr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(_("LruGarbageCollector","Garbage collection skipped; disabled"),eS.resolve(sh)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(_("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),sh):this.pr(e,t))}getCacheSize(e){return this.Vr.getCacheSize(e)}pr(e,t){let n,r,i,s,a,o,l,c=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(_("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,s=Date.now(),this.nthSequenceNumber(e,r))).next(r=>(n=r,a=Date.now(),this.removeTargets(e,n,t))).next(t=>(i=t,o=Date.now(),this.removeOrphanedDocuments(e,n))).next(e=>(l=Date.now(),b()<=u.$b.DEBUG&&_("LruGarbageCollector",`LRU Garbage Collection
5	Counted targets in ${s-c}ms
6	Determined least recently used ${r} in `+(a-s)+"ms\n"+`	Removed ${i} targets in `+(o-a)+"ms\n"+`	Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-c}ms`),eS.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class sx{constructor(e,t){this.db=e,this.garbageCollector=new sS(this,t)}mr(e){let t=this.yr(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}yr(e){let t=0;return this.gr(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}gr(e,t){return this.wr(e,(e,n)=>t(n))}addReference(e,t,n){return sD(e,n)}removeReference(e,t,n){return sD(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return sD(e,t)}Sr(e,t){let n;return n=!1,tM(e,eH).ee(r=>sp(e,r,t).next(e=>(e&&(n=!0),eS.resolve(!e)))).next(()=>n)}removeOrphanedDocuments(e,t){let n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[],i=0;return this.wr(e,(s,a)=>
6{if(a<=t){let t=this.Sr(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,eh.min()),sb(e).delete([0,eK(s.path)])))});r.push(t)}}).next(()=>eS.waitFor(r)).next(()=>n.apply(e)).next(()=>i)}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return sD(e,t)}wr(e,t){let n=sb(e),r,i=eU.ue;return n.X({index:ts},([e,n],{path:s,sequenceNumber:a})=>{0===e?(i!==eU.ue&&t(new Z(ej(r)),i),i=a,r=s):i=eU.ue}).next(()=>{i!==eU.ue&&t(new Z(ej(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function sD(e,t){var n;return sb(e).put((n=e.currentSequenceNumber,{targetId:0,path:eK(t.path),sequenceNumber:n}))}class sC{constructor(){this.changes=new ru(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,nC.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?eS.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class sN{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return tM(e,e2).put(n)}removeEntry(e,t,n){return tM(e,e2).delete(function(e,t){let n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],iL(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next(n=>(n.byteSize+=t,this.br(e,n)))}getEntry(e,t){let n=nC.newInvalidDocument(t);return tM(e,e2).X({index:e6,range:IDBKeyRange.only(sk(t))},(e,r)=>{n=this.Dr(t,r)}).next(()=>n)}vr(e,t){let n={size:0,document:nC.newInvalidDocument(t)};return tM(e,e2).X({index:e6,range:IDBKeyRange.only(sk(t))},(e,r)=>{n={document:this.Dr(t,r),size:sm(r)}}).next(()=>n)}getEntries(e,t){let n=rc;return this.Cr(e,t,(e,t)=>{let r=this.Dr(e,t);n=n.insert(e,r)}).next(()=>n)}Fr(e,t){let n=rc,r=new tz(Z.comparator);return this.Cr(e,t,(e,t)=>{let i=this.Dr(e,t);n=n.insert(e,i),r=r.insert(e,sm(t))}).next(()=>({documents:n,Mr:r}))}Cr(e,t,n){if(t.isEmpty())return eS.resolve();let r=new tj(sF);t.forEach(e=>r=r.add(e));let i=IDBKeyRange.bound(sk(r.first()),sk(r.last())),s=r.getIterator(),a=s.getNext();return tM(e,e2).X({index:e6,range:i},(e,t,r)=>{let i=Z.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>sF(a,i);)n(a,null),a=s.getNext();a&&a.isEqual(i)&&(n(a,t),a=s.hasNext()?s.getNext():null),a?r.G(sk(a)):r.done()}).next(()=>{for(;a;)n(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,t,n,r,i){let s=t.path,a=[s.popLast().toArray(),s.lastSegment(),iL(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return tM(e,e2).j(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let n=rc;for(let i of e){let e=this.Dr(Z.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(ra(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=rc,s=sR(t,n),a=sR(t,eb.max());return tM(e,e2).X({index:e3,range:IDBKeyRange.bound(s,a,!0)},(e,t,n)=>{let s=this.Dr(Z.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(i=i.insert(s.key,s)).size===r&&n.done()}).next(()=>i)}newChangeBuffer(e){return new sA(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return tM(e,e9).get(e7).next(e=>(C(!!e,20021),e))}br(e,t){return tM(e,e9).put(e7,t)}Dr(e,t){if(t){let e=function(e,t){let n;if(t.document)n=iS(e.gt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=Z.fromSegments(t.noDocument.path),r=iU(t.noDocument.readTime);n=nC.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return x(56709);{let e=Z.fromSegments(t.unknownDocument.path),r=iU(t.unknownDocument.version);n=nC.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){let t=new ec(e[0],e[1]);return eh.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual(eh.min())))return e}return nC.newInvalidDocument(e)}}class sA extends sC{constructor(e,t){super(),this.Or=e,this.trackRemovals=t,this.Nr=new ru(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],n=0,r=new tj((e,t)=>K(e.canonicalString(),t.canonicalString()));
6return this.changes.forEach((i,s)=>{let a=this.Nr.get(i);if(t.push(this.Or.removeEntry(e,i,a.readTime)),s.isValidDocument()){let o=iM(this.Or.serializer,s);r=r.add(i.path.popLast());let l=sm(o);n+=l-a.size,t.push(this.Or.addEntry(e,i,o))}else if(n-=a.size,this.trackRemovals){let n=iM(this.Or.serializer,s.convertToNoDocument(eh.min()));t.push(this.Or.addEntry(e,i,n))}}),r.forEach(n=>{t.push(this.Or.indexManager.addToCollectionParentIndex(e,n))}),t.push(this.Or.updateMetadata(e,n)),eS.waitFor(t)}getFromCache(e,t){return this.Or.vr(e,t).next(e=>(this.Nr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Or.Fr(e,t).next(({documents:e,Mr:t})=>(t.forEach((t,n)=>{this.Nr.set(t,{size:n,readTime:e.get(t).readTime})}),e))}}function sk(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function sR(e,t){let n=t.documentKey.path.toArray();return[e,iL(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function sF(e,t){let n=e.path.toArray(),r=t.path.toArray(),i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=K(n[e],r[e]))return i;return(i=K(n.length,r.length))||(i=K(n[n.length-2],r[r.length-2]))||K(n[n.length-1],r[r.length-1])}class sO{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class sV{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(r=>(n=r,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==n&&rL(n.mutation,e,tW.empty(),ec.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,ry()).next(()=>t))}getLocalViewOfDocuments(e,t,n=ry()){let r=rm();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=rd();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=rm();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,ry()))}populateOverlays(e,t,n){let r=[];return n.forEach(e=>{t.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,n)=>{t.set(e,n)})})}computeViews(e,t,n,r){let i=rc,s=rm(),a=rm();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof rB)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),rL(a.mutation,t,a.mutation.getFieldMask(),ec.now())):s.set(t.key,tW.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>{var n;return a.set(e,new sO(t,null!=(n=s.get(e))?n:null))}),a))}recalculateAndSaveOverlays(e,t){let n=rm(),r=new tz((e,t)=>e-t),i=ry();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let i of e)i.keys().forEach(e=>{let s=t.get(e);if(null===s)return;let a=n.get(e)||tW.empty();a=i.applyToLocalView(s,a),n.set(e,a);let o=(r.get(i.batchId)||ry()).add(e);r=r.insert(i.batchId,o)})}).next(()=>{let s=[],a=r.getReverseIterator();for(;a.hasNext();){let r=a.getNext(),o=r.key,l=r.value,u=rm();l.forEach(e=>{if(!i.has(e)){let r=rM(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,o,u))}return eS.waitFor(s)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,n,r){return Z.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):n3(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(i=>{let s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):eS.resolve(rm()),a=-1,o=i;return s.next(t=>eS.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?eS.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,o,t,ry())).next(e=>({batchId:a,changes:rf(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new Z(t)).next(e=>{let t=rd();
6return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let i=t.collectionGroup,s=rd();return this.indexManager.getCollectionParents(e,i).next(a=>eS.forEach(a,a=>{let o=new n5(a.child(i),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r))).next(e=>{i.forEach((t,n)=>{let r=n.getKey();null===e.get(r)&&(e=e.insert(r,nC.newInvalidDocument(r)))});let n=rd();return e.forEach((e,r)=>{let s=i.get(e);void 0!==s&&rL(s.mutation,r,tW.empty(),ec.now()),ra(t,r)&&(n=n.insert(e,r))}),n})}}class sP{constructor(e){this.serializer=e,this.Br=new Map,this.Lr=new Map}getBundleMetadata(e,t){return eS.resolve(this.Br.get(t))}saveBundleMetadata(e,t){return this.Br.set(t.id,{id:t.id,version:t.version,createTime:im(t.createTime)}),eS.resolve()}getNamedQuery(e,t){return eS.resolve(this.Lr.get(t))}saveNamedQuery(e,t){return this.Lr.set(t.name,{name:t.name,query:iK(t.bundledQuery),readTime:im(t.readTime)}),eS.resolve()}}class sM{constructor(){this.overlays=new tz(Z.comparator),this.kr=new Map}getOverlay(e,t){return eS.resolve(this.overlays.get(t))}getOverlays(e,t){let n=rm();
6return eS.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){return n.forEach((n,r)=>{this.wt(e,t,r)}),eS.resolve()}removeOverlaysForBatchId(e,t,n){let r=this.kr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.kr.delete(n)),eS.resolve()}getOverlaysForCollection(e,t,n){let r=rm(),i=t.length+1,s=new Z(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){let e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return eS.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new tz((e,t)=>e-t),s=this.overlays.getIterator();for(;s.hasNext();){let e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=rm(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=rm(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return eS.resolve(a)}wt(e,t,n){let r=this.overlays.get(n.key);if(null!==r){let e=this.kr.get(r.largestBatchId).delete(n.key);this.kr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new rH(t,n));let i=this.kr.get(t);void 0===i&&(i=ry(),this.kr.set(t,i)),this.kr.set(t,i.add(n.key))}}class sL{constructor(){this.sessionToken=tX.EMPTY_BYTE_STRING}getSessionToken(e){return eS.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,eS.resolve()}}class sq{constructor(){this.qr=new tj(sU.Qr),this.$r=new tj(sU.Ur)}isEmpty(){return this.qr.isEmpty()}addReference(e,t){let n=new sU(e,t);this.qr=this.qr.add(n),this.$r=this.$r.add(n)}Kr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Wr(new sU(e,t))}Gr(e,t){e.forEach(e=>this.removeReference(e,t))}zr(e){let t=new Z(new J([])),n=new sU(t,e),r=new sU(t,e+1),i=[];return this.$r.forEachInRange([n,r],e=>{this.Wr(e),i.push(e.key)}),i}jr(){this.qr.forEach(e=>this.Wr(e))}Wr(e){this.qr=this.qr.delete(e),this.$r=this.$r.delete(e)}Jr(e){let t=new Z(new J([])),n=new sU(t,e),r=new sU(t,e+1),i=ry();return this.$r.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new sU(e,0),n=this.qr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class sU{constructor(e,t){this.key=e,this.Hr=t}static Qr(e,t){return Z.comparator(e.key,t.key)||K(e.Hr,t.Hr)}static Ur(e,t){return K(e.Hr,t.Hr)||Z.comparator(e.key,t.key)}}class sB{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.er=1,this.Yr=new tj(sU.Qr)}checkEmpty(e){return eS.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let i=this.er;this.er++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new rQ(i,t,n,r);for(let t of(this.mutationQueue.push(s),r))this.Yr=this.Yr.add(new sU(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return eS.resolve(s)}lookupMutationBatch(e,t){return eS.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.Xr(t+1),r=n<0?0:n;return eS.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return eS.resolve(0===this.mutationQueue.length?-1:this.er-1)}getAllMutationBatches(e){return eS.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new sU(t,0),r=new sU(t,1/0),i=[];return this.Yr.forEachInRange([n,r],e=>{let t=this.Zr(e.Hr);i.push(t)}),eS.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tj(K);return t.forEach(e=>{let t=new sU(e,0),r=new sU(e,1/0);this.Yr.forEachInRange([t,r],e=>{n=n.add(e.Hr)})}),eS.resolve(this.ei(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=n;Z.isDocumentKey(i)||(i=i.child(""));let s=new sU(new Z(i),0),a=new tj(K);return this.Yr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Hr)),!0)},s),eS.resolve(this.ei(a))}ei(e){let t=[];return e.forEach(e=>{let n=this.Zr(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){C(0===this.ti(t.batchId,"removed"),55003),this.mutation
6Queue.shift();let n=this.Yr;return eS.forEach(t.mutations,r=>{let i=new sU(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.Yr=n})}rr(e){}containsKey(e,t){let n=new sU(t,0),r=this.Yr.firstAfterOrEqual(n);return eS.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,eS.resolve()}ti(e,t){return this.Xr(e)}Xr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Zr(e){let t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class sz{constructor(e){this.ni=e,this.docs=new tz(Z.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.ni(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let n=this.docs.get(t);return eS.resolve(n?n.document.mutableCopy():nC.newInvalidDocument(t))}getEntries(e,t){let n=rc;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():nC.newInvalidDocument(e))}),eS.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=rc,s=t.path,a=new Z(s.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){let{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||0>=eI(ev(a),n)||(r.has(a.key)||ra(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return eS.resolve(i)}getAllFromCollectionGroup(e,t,n,r){x(9500)}
vendor: 4,249 bytes, line 6
6ri(e,t){return eS.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new s$(this)}getSize(e){return eS.resolve(this.size)}}class s$ extends sC{constructor(e){super(),this.Or=e}applyChanges(e){let t=[];return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.Or.addEntry(e,r)):this.Or.removeEntry(n)}),eS.waitFor(t)}getFromCache(e,t){return this.Or.getEntry(e,t)}getAllFromCache(e,t){return this.Or.getEntries(e,t)}}class sK{constructor(e){this.persistence=e,this.ii=new ru(e=>nX(e),nY),this.lastRemoteSnapshotVersion=eh.min(),this.highestTargetId=0,this.si=0,this.oi=new sq,this.targetCount=0,this._i=sw.ar()}forEachTarget(e,t){return this.ii.forEach((e,n)=>t(n)),eS.resolve()}getLastRemoteSnapshotVersion(e){return eS.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return eS.resolve(this.si)}allocateTargetId(e){return this.highestTargetId=this._i.next(),eS.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.si&&(this.si=t),eS.resolve()}hr(e){this.ii.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this._i=new sw(t),this.highestTargetId=t),e.sequenceNumber>this.si&&(this.si=e.sequenceNumber)}addTargetData(e,t){return this.hr(t),this.targetCount+=1,eS.resolve()}updateTargetData(e,t){return this.hr(t),eS.resolve()}removeTargetData(e,t){return this.ii.delete(t.target),this.oi.zr(t.targetId),this.targetCount-=1,eS.resolve()}removeTargets(e,t,n){let r=0,i=[];return this.ii.forEach((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.ii.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)}),eS.waitFor(i).next(()=>r)}getTargetCount(e){return eS.resolve(this.targetCount)}getTargetData(e,t){let n=this.ii.get(t)||null;return eS.resolve(n)}addMatchingKeys(e,t,n){return this.oi.Kr(t,n),eS.resolve()}removeMatchingKeys(e,t,n){this.oi.Gr(t,n);let r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(t=>{i.push(r.markPotentiallyOrphaned(e,t))}),eS.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.oi.zr(t),eS.resolve()}getMatchingKeysForTargetId(e,t){let n=this.oi.Jr(t);return eS.resolve(n)}containsKey(e,t){return eS.resolve(this.oi.containsKey(t))}}class sj{constructor(e,t){this.ai={},this.overlays={},this.ui=new eU(0),this.ci=!1,this.ci=!0,this.li=new sL,this.referenceDelegate=e(this),this.hi=new sK(this),this.indexManager=new ss,this.remoteDocumentCache=new sz(e=>this.referenceDelegate.Pi(e)),this.serializer=new iP(t),this.Ti=new sP(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ci=!1,Promise.resolve()}get started(){return this.ci}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new sM,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ai[e.toKey()];return n||(n=new sB(t,this.referenceDelegate),this.ai[e.toKey()]=n),n}getGlobalsCache(){return this.li}getTargetCache(){return this.hi}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ti}runTransaction(e,t,n){_("MemoryPersistence","Starting transaction:",e);let r=new sG(this.ui.next());return this.referenceDelegate.Ii(),n(r).next(e=>this.referenceDelegate.di(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ei(e,t){return eS.or(Object.values(this.ai).map(n=>()=>n.containsKey(e,t)))}}class sG extends eT{constructor(e){super(),this.currentSequenceNumber=e}}class sQ{constructor(e){this.persistence=e,this.Ai=new sq,this.Ri=null}static Vi(e){return new sQ(e)}get mi(){if(this.Ri)return this.Ri;throw x(60996)}addReference(e,t,n){return this.Ai.addReference(n,t),this.mi.delete(n.toString()),eS.resolve()}removeReference(e,t,n){return this.Ai.removeReference(n,t),this.mi.add(n.toString()),eS.resolve()}markPotentiallyOrphaned(e,t){return this.mi.add(t.toString()),eS.resolve()}removeTarget(e,t){this.Ai.zr(t.targetId).forEach(e=>this.mi.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.mi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ii(){this.Ri=new Set}di(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();
6return eS.forEach(this.mi,n=>{let r=Z.fromPath(n);return this.fi(e,r).next(e=>{e||t.removeEntry(r,eh.min())})}).next(()=>(this.Ri=null,t.apply(e)))}updateLimboDocument(e,t){return this.fi(e,t).next(e=>{e?this.mi.delete(t.toString()):this.mi.add(t.toString())})}Pi(e){return 0}fi(e,t){return eS.or([()=>eS.resolve(this.Ai.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}}class sW{constructor(e,t){this.persistence=e,this.gi=new ru(e=>eK(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new sS(this,t)}static Vi(e,t){return new sW(e,t)}Ii(){}di(e){return eS.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}mr(e){let t=this.yr(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}yr(e){let t=0;return this.gr(e,e=>{t++}).next(()=>t)}gr(e,t){return eS.forEach(this.gi,(n,r)=>this.Sr(e,n,r).next(e=>e?eS.resolve():t(r)))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0,r=this.persistence.getRemoteDocumentCache(),i=r.newChangeBuffer();return r.ri(e,r=>this.Sr(e,r,t).next(e=>{e||(n++,i.removeEntry(r,eh.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.gi.set(t,e.currentSequenceNumber),eS.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),eS.resolve()}removeReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),eS.resolve()}updateLimboDocument(e,t){return this.gi.set(t,e.currentSequenceNumber),eS.resolve()}Pi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(nl(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let n=t8(t);return n?16+e(n):16;case 5:return 2*t.stringValue.length;case 6:return t1(t.bytesValue).approximateByteSize();case 7:return t.referenceValue.length;case 9:return(t.arrayValue.values||[]).reduce((t,n)=>t+e(n),0);case 10:case 11:var r;let i;return r=t.mapValue,i=0,tq(r.fields,(t,n)=>{i+=t.length+e(n)}),i;default:throw x(13486,{value:t})}}(e.data.value)),t}Sr(e,t,n){return eS.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.gi.get(t);return eS.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class sH{constructor(e){this.serializer=e}q(e,t,n,r){let i=new eD("createOrUpgrade",t);n<1&&r>=1&&(e.createObjectStore(eQ),e.createObjectStore(eH,{keyPath:"userId"}),e.createObjectStore(eJ,{keyPath:eX,autoIncrement:!0}).createIndex(eY,eZ,{unique:!0}),e.createObjectStore(e1),sJ(e),e.createObjectStore(eG));let s=eS.resolve();return n<3&&r>=3&&(0!==n&&(e.deleteObjectStore(tr),e.deleteObjectStore(te),e.deleteObjectStore(tl),sJ(e)),s=s.next(()=>(function(e){let t=e.store(tl),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:eh.min().toTimestamp(),targetCount:0};return t.put(to,n)})(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>i.store(eJ).j().next(t=>{e.deleteObjectStore(eJ),e.createObjectStore(eJ,{keyPath:eX,autoIncrement:!0}).createIndex(eY,eZ,{unique:!0});let n=i.store(eJ),r=t.map(e=>n.put(e));return eS.waitFor(r)}))),s=s.next(()=>{e.createObjectStore(th,{keyPath:"clientId"})})),n<5&&r>=5&&(s=s.next(()=>this.pi(i))),n<6&&r>=6&&(s=s.next(()=>(e.createObjectStore(e9),this.yi(i)))),n<7&&r>=7&&(s=s.next(()=>this.wi(i))),n<8&&r>=8&&(s=s.next(()=>this.Si(e,i))),n<9&&r>=9&&(s=s.next(()=>{e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&r>=10&&(s=s.next(()=>this.bi(i))),n<11&&r>=11&&(s=s.next(()=>{e.createObjectStore(td,{keyPath:"bundleId"}),e.createObjectStore(tf,{keyPath:"name"})})),n<12&&r>=12&&(s=s.next(()=>{let t=e.createObjectStore(tE,{keyPath:tS});t.createIndex(tx,tD,{unique:!1}),t.createIndex(tC,tN,{unique:!1})})),n<13&&r>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore(e2,{keyPath:e5});t.createIndex(e6,e4),t.createIndex(e3,e8)})(e)).next(()=>this.Di(e,i)).next(()=>e.deleteObjectStore(eG))),n<14&&r>=14&&(s=s.next(()=>this.Ci(e,i))),n<15&&r>=15&&(s=s.next(()=>{e.createObjectStore(tm,{keyPath:"indexId",autoIncrement:!0}).createIndex(tg,"collectionGroup",{unique:!1}),e.createObjectStore(tp,{keyPath:ty}).createIndex(tw,tv,{unique:!1}),e.createObjectStore(tb,{keyPath:tI}).createIndex(t_,tT,{unique:!1})}
6)),n<16&&r>=16&&(s=s.next(()=>{t.objectStore(tp).clear()}).next(()=>{t.objectStore(tb).clear()})),n<17&&r>=17&&(s=s.next(()=>{e.createObjectStore(tA,{keyPath:"name"})})),n<18&&r>=18&&(0,c.Ov)()&&(s=s.next(()=>{t.objectStore(tp).clear()}).next(()=>{t.objectStore(tb).clear()})),s}yi(e){let t=0;return e.store(eG).X((e,n)=>{t+=sm(n)}).next(()=>{let n={byteSize:t};return e.store(e9).put(e7,n)})}pi(e){let t=e.store(eH),n=e.store(eJ);return t.j().next(t=>eS.forEach(t,t=>{let r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.j(eY,r).next(n=>eS.forEach(n,n=>{C(n.userId===t.userId,18650,"Cannot process batch from unexpected user",{batchId:n.batchId});let r=iB(this.serializer,n);return sf(e,t.userId,r).next(()=>{})}))}))}wi(e){let t=e.store(tr),n=e.store(eG);return e.store(tl).get(to).next(e=>{let r=[];return n.X((n,i)=>{let s=new J(n),a=[0,eK(s)];r.push(t.get(a).next(n=>n?eS.resolve():t.put({targetId:0,path:eK(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>eS.waitFor(r))})}Si(e,t){e.createObjectStore(tu,{keyPath:tc});let n=t.store(tu),r=new sa,i=e=>{if(r.add(e)){let t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:eK(r)})}};return t.store(eG).X({Z:!0},(e,t)=>i(new J(e).popLast())).next(()=>t.store(e1).X({Z:!0},([e,t,n],r)=>i(ej(t).popLast())))}bi(e){let t=e.store(te);return t.X((e,n)=>{let r=iz(n),i=i$(this.serializer,r);return t.put(i)})}Di(e,t){let n=t.store(eG),r=[];return n.X((e,n)=>{let i=t.store(e2),s=(n.document?new Z(J.fromString(n.document.name).popFirst(5)):n.noDocument?Z.fromSegments(n.noDocument.path):n.unknownDocument?Z.fromSegments(n.unknownDocument.path):x(36783)).path.toArray(),a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))}).next(()=>eS.waitFor(r))}Ci(e,t){let n=t.store(eJ),r=new sN(this.serializer),i=new sj(sQ.Vi,this.serializer.gt);return n.j().next(e=>{let n=new Map;return e.forEach(e=>{var t;let r=null!=(t=n.get(e.userId))?t:ry();iB(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),eS.forEach(n,(e,n)=>{let s=new y(n),a=iH.yt(this.serializer,s),o=i.getIndexManager(s);return new sV(r,sg.yt(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new tP(t,eU.ue),e).next()})})}}function sJ(e){e.createObjectStore(tr,{keyPath:ti}).createIndex(ts,ta,{unique:!0}),e.createObjectStore(te,{keyPath:"targetId"}).createIndex(tt,tn,{unique:!0}),e.createObjectStore(tl)}let sX="IndexedDbPersistence",sY="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.",sZ="main";class s0{constructor(e,t,n,r,i,s,a,o,l,u,c=18){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Fi=i,this.window=s,this.document=a,this.Mi=l,this.xi=u,this.Oi=c,this.ui=null,this.ci=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ni=null,this.inForeground=!1,this.Bi=null,this.Li=null,this.ki=-1/0,this.qi=e=>Promise.resolve(),!s0.C())throw new k(A.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new sx(this,r),this.Qi=t+sZ,this.serializer=new iP(o),this.$i=new eC(this.Qi,this.Oi,new sH(this.serializer)),this.li=new iJ,this.hi=new sv(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new sN(this.serializer),this.Ti=new iW,this.window&&this.window.localStorage?this.Ui=this.window.localStorage:(this.Ui=null,!1===u&&T(sX,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Ki().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new k(A.FAILED_PRECONDITION,sY);return this.Wi(),this.Gi(),this.zi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.hi.getHighestSequenceNumber(e))}).then(e=>{this.ui=new eU(e,this.Mi)}).then(()=>{this.ci=!0}).catch(e=>(this.$i&&this.$i.close(),Promise.reject(e)))}ji(e){return this.qi=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.$i.setDatabaseDeletedListener(e)}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Fi.enqueueAndForget(async()=>{this.started&&await this.Ki()}))}Ki(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>tM(e,th).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Ji(e).next(e=>{e||(this.isPrimary=!1,this.Fi.enqueueRetryable(()=>this.qi(!1)))})}).next(()=>this.Hi(e)).next(t=>this.isPrimary&&!t?this.Yi(e).next(()=>!1):!!t&&this.Zi(e).next(()=>!0))).catch(e=>{if(eR(e))return _(sX,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return _(sX,"Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Fi.enqueueRetryable(()=>this.qi(e)),this.isPrimary=e})}Ji(e){return tM(e,eQ).get(eW).next(e=>eS.resolve(this.Xi(e)))}es(e){return tM(e,th).delete(this.clientId)}async ts(){if(this.isPrimary&&!this.ns(this.ki,18e5)){this.ki=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let t=tM(e,th);return t.j().next(e=>{let n=this.rs(e,18e5),r=e.filter(e=>-1===n.indexOf(e));
6return eS.forEach(r,e=>t.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.Ui)for(let t of e)this.Ui.removeItem(this.ss(t.clientId))}}zi(){this.Li=this.Fi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ki().then(()=>this.ts()).then(()=>this.zi()))}Xi(e){return!!e&&e.ownerId===this.clientId}Hi(e){return this.xi?eS.resolve(!0):tM(e,eQ).get(eW).next(t=>{if(null!==t&&this.ns(t.leaseTimestampMs,5e3)&&!this._s(t.ownerId)){if(this.Xi(t)&&this.networkEnabled)return!0;if(!this.Xi(t)){if(!t.allowTabSynchronization)throw new k(A.FAILED_PRECONDITION,sY);return!1}}return!(!this.networkEnabled||!this.inForeground)||tM(e,th).j().next(e=>void 0===this.rs(e,5e3).find(e=>{if(this.clientId!==e.clientId){let t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&_(sX,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.ci=!1,this.us(),this.Li&&(this.Li.cancel(),this.Li=null),this.cs(),this.ls(),await this.$i.runTransaction("shutdown","readwrite",[eQ,th],e=>{let t=new tP(e,eU.ue);return this.Yi(t).next(()=>this.es(t))}),this.$i.close(),this.hs()}rs(e,t){return e.filter(e=>this.ns(e.updateTimeMs,t)&&!this._s(e.clientId))}Ps(){return this.runTransaction("getActiveClients","readonly",e=>tM(e,th).j().next(e=>this.rs(e,18e5).map(e=>e.clientId)))}get started(){return this.ci}getGlobalsCache(){return this.li}getMutationQueue(e,t){return sg.yt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.hi}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new su(e,this.serializer.gt.databaseId)}getDocumentOverlayCache(e){return iH.yt(this.serializer,e)}getBundleCache(){return this.Ti}runTransaction(e,t,n){var r;let i;_(sX,"Starting transaction:",e);let s=18===(r=this.Oi)||17===r?tV:16===r||15===r?tO:14===r||13===r?tF:12===r?tR:11===r?tk:void x(60245);return this.$i.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,r=>(i=new tP(r,this.ui?this.ui.next():eU.ue),"readwrite-primary"===t?this.Ji(i).next(e=>!!e||this.Hi(i)).next(t=>{if(!t)throw T(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.Fi.enqueueRetryable(()=>this.qi(!1)),new k(A.FAILED_PRECONDITION,e_);return n(i)}).next(e=>this.Zi(i).next(()=>e)):this.Ts(i).next(()=>n(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Ts(e){return tM(e,eQ).get(eW).next(e=>{if(null!==e&&this.ns(e.leaseTimestampMs,5e3)&&!this._s(e.ownerId)&&!this.Xi(e)&&!(this.xi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new k(A.FAILED_PRECONDITION,sY)})}Zi(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return tM(e,eQ).put(eW,t)}static C(){return eC.C()}Yi(e){let t=tM(e,eQ);return t.get(eW).next(e=>
6this.Xi(e)?(_(sX,"Releasing primary lease."),t.delete(eW)):eS.resolve())}ns(e,t){let n=Date.now();return!(e<n-t)&&(!(e>n)||(T(`Detected an update time that is in the future: ${e} > ${n}`),!1))}Wi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Bi=()=>{this.Fi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ki()))},this.document.addEventListener("visibilitychange",this.Bi),this.inForeground="visible"===this.document.visibilityState)}cs(){this.Bi&&(this.document.removeEventListener("visibilitychange",this.Bi),this.Bi=null)}Gi(){var e;"function"==typeof(null==(e=this.window)?void 0:e.addEventListener)&&(this.Ni=()=>{this.us();let e=/(?:Version|Mobile)\/1[456]/;(0,c.nr)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.Fi.enterRestrictedMode(!0),this.Fi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ni))}ls(){this.Ni&&(this.window.removeEventListener("pagehide",this.Ni),this.Ni=null)}_s(e){var t;try{let n=null!==(null==(t=this.Ui)?void 0:t.getItem(this.ss(e)));return _(sX,`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return T(sX,"Failed to get zombied client id.",e),!1}}us(){if(this.Ui)try{this.Ui.setItem(this.ss(this.clientId),String(Date.now()))}catch(e){T("Failed to set zombie client id.",e)}}hs(){if(this.Ui)try{this.Ui.removeItem(this.ss(this.clientId))}catch(e){}}ss(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function s1(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class s2{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Is=n,this.ds=r}static Es(e,t){let n=ry(),r=ry();for(let e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new s2(e,t.fromCache,n,r)}}class s5{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class s6{constructor(){this.As=!1,this.Rs=!1,this.Vs=100,this.fs=(0,c.nr)()?8:eN((0,c.ZQ)())>0?6:4}initialize(e,t){this.gs=e,this.indexManager=t,this.As=!0}getDocumentsMatchingQuery(e,t,n,r){let i={result:null};return this.ps(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.ys(e,t,r,n).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let n=new s5;return this.ws(e,t,n).next(r=>{if(i.result=r,this.Rs)return this.Ss(e,t,n,r.size)})}).next(()=>i.result)}Ss(e,t,n,r){return n.documentReadCount<this.Vs?(b()<=u.$b.DEBUG&&_("QueryEngine","SDK will not create cache indexes for query:",rs(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),eS.resolve()):(b()<=u.$b.DEBUG&&_("QueryEngine","Query:",rs(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.fs*r?(b()<=u.$b.DEBUG&&_("QueryEngine","The SDK decides to create cache indexes for query:",rs(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,n9(t))):eS.resolve())}ps(e,t){if(n4(t))return eS.resolve(null);let n=n9(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=n9(t=rn(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let i=ry(...r);return this.gs.getDocuments(e,i).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{let s=this.bs(t,r);return this.Ds(t,s,i,n.readTime)?this.ps(e,rn(t,null,"F")):this.vs(e,s,t,n)}))})))}ys(e,t,n,r){return n4(t)||r.isEqual(eh.min())?eS.resolve(null):this.gs.getDocuments(e,n).next(i=>{let s=this.bs(t,i);return this.Ds(t,s,n,r)?eS.resolve(null):(b()<=u.$b.DEBUG&&_("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),rs(t)),this.vs(e,s,t,ew(r,-1)).next(e=>e))})}bs(e,t){let n=new tj(rl(e));return t.forEach((t,r)=>{ra(e,r)&&(n=n.add(r))}),n}Ds(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;let i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}ws(e,t,n){return b()<=u.$b.DEBUG&&_("QueryEngine","Using full collection scan to execute query:",rs(t)),this.gs.getDocumentsMatchingQuery(e,t,eb.min(),n)}vs(e,t,n,r){return this.gs.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let s4="LocalStore";class s3{constructor(e,t,n,r){this.persistence=e,this.Cs=t,this.serializer
6=r,this.Fs=new tz(K),this.Ms=new ru(e=>nX(e),nY),this.xs=new Map,this.Os=e.getRemoteDocumentCache(),this.hi=e.getTargetCache(),this.Ti=e.getBundleCache(),this.Ns(n)}Ns(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new sV(this.Os,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Os.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Fs))}}async function s8(e,t){return await e.persistence.runTransaction("Handle user change","readonly",n=>{let r;return e.mutationQueue.getAllMutationBatches(n).next(i=>(r=i,e.Ns(t),e.mutationQueue.getAllMutationBatches(n))).next(t=>{let i=[],s=[],a=ry();for(let e of r)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(n,a).next(e=>({Bs:e,removedBatchIds:i,addedBatchIds:s}))})})}function s9(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.hi.getLastRemoteSnapshotVersion(t))}
6function s7(e,t,n){let r=ry(),i=ry();return n.forEach(e=>r=r.add(e)),t.getEntries(e,r).next(e=>{let r=rc;return n.forEach((n,s)=>{let a=e.get(n);s.isFoundDocument()!==a.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(eh.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!a.isValidDocument()||s.version.compareTo(a.version)>0||0===s.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):_(s4,"Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",s.version)}),{Ls:r,ks:i}})}function ae(e,t){return e.persistence.runTransaction("Allocate target","readwrite",n=>{let r;return e.hi.getTargetData(n,t).next(i=>i?(r=i,eS.resolve(r)):e.hi.allocateTargetId(n).next(i=>(r=new iV(t,i,"TargetPurposeListen",n.currentSequenceNumber),e.hi.addTargetData(n,r).next(()=>r))))}).then(n=>{let r=e.Fs.get(n.targetId);return(null===r||n.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(e.Fs=e.Fs.insert(n.targetId,n),e.Ms.set(t,n.targetId)),n})}async function at(e,t,n){let r=e.Fs.get(t);try{n||await e.persistence.runTransaction("Release target",n?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,r))}catch(e){if(!eR(e))throw e;_(s4,`Failed to update sequence numbers for target ${t}: ${e}`)}e.Fs=e.Fs.remove(t),e.Ms.delete(r.target)}function an(e,t,n){let r=eh.min(),i=ry();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,n){let r=e.Ms.get(n);return void 0!==r?eS.resolve(e.Fs.get(r)):e.hi.getTargetData(t,n)})(e,s,n9(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,e.hi.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e.Cs.getDocumentsMatchingQuery(s,t,n?r:eh.min(),n?i:ry())).next(n=>(as(e,ro(t),n),{documents:n,qs:i})))}function ar(e,t){let n=e.hi,r=e.Fs.get(t);return r?Promise.resolve(r.target):e.persistence.runTransaction("Get target data","readonly",e=>n.Et(e,t).next(e=>e?e.target:null))}function ai(e,t){let n=e.xs.get(t)||eh.min();return e.persistence.runTransaction("Get new document changes","readonly",r=>e.Os.getAllFromCollectionGroup(r,t,ew(n,-1),Number.MAX_SAFE_INTEGER)).then(n=>(as(e,t,n),n))}function as(e,t,n){let r=e.xs.get(t)||eh.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.xs.set(t,r)}async function aa(e,t,n,r){let i=ry(),s=rc;for(let e of n){let n=t.Qs(e.metadata.name);e.document&&(i=i.add(n));let r=t.$s(e);r.setReadTime(t.Us(e.metadata.readTime)),s=s.insert(n,r)}let a=e.Os.newChangeBuffer({trackRemovals:!0}),o=await ae(e,n9(n6(J.fromString(`__bundle__/docs/${r}`))));return e.persistence.runTransaction("Apply bundle documents","readwrite",t=>s7(t,a,s).next(e=>(a.apply(t),e)).next(n=>e.hi.removeMatchingKeysForTargetId(t,o.targetId).next(()=>e.hi.addMatchingKeys(t,i,o.targetId)).next(()=>e.localDocuments.getLocalViewOfDocuments(t,n.Ls,n.ks)).next(()=>n.Ls)))}async function ao(e,t,n=ry()){let r=await ae(e,n9(iK(t.bundledQuery)));return e.persistence.runTransaction("Save named query","readwrite",i=>{let s=im(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return e.Ti.saveNamedQuery(i,t);let a=r.withResumeToken(tX.EMPTY_BYTE_STRING,s);return e.Fs=e.Fs.insert(a.targetId,a),e.hi.updateTargetData(i,a).next(()=>e.hi.removeMatchingKeysForTargetId(i,r.targetId)).next(()=>e.hi.addMatchingKeys(i,n,r.targetId)).next(()=>e.Ti.saveNamedQuery(i,t))})}let al="firestore_clients";function au(e,t){return`${al}_${e}_${t}`}let ac="firestore_mutations";function ah(e,t,n){let r=`${ac}_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}let ad="firestore_targets";function af(e,t){return`${ad}_${e}_${t}`}let am="SharedClientState";class ag{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Ks(e,t,n){let r=JSON.parse(n),i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(i=new k(r.error.code,r.error.message)),s?new ag(e,t,r.state,i):(T(am,`Failed to parse mutation state for ID '${t}': ${n}`),null)}Ws(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class ap{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Ks(e,t){let n=JSON.parse(t),r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(r=new k(n.error.code,n.error.message)),i?new ap(e,n.state,r):(T(am,`Failed to parse target state for ID '${e}': ${t}`),null)}Ws(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class ay{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Ks(e,t){let n=JSON.parse(t),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=rw;for(let e=0;r&&e<n.activeTargetIds.length;++e)r=e$(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new ay(e,i):(T(am,`Failed to parse client data for instance '${e}': ${t}`),null)}}class aw{constructor(e,t){this.clientId=e,this.onlineState=t}static Ks(e){let t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new aw(t.clientId,t.onlineState):(T(am,`Failed to parse online state: ${e}`),null)}}class av{constructor(){this.activeTargetIds=rw}Gs(e){this.activeTargetIds=this.activeTargetIds.add(e)}zs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class ab{constructor(e,t,n,r,i){var s,a,o;this.window=e,this.Fi=t,this.persistenceKey=n,this.js=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Js=this.Hs.bind(this),this.Ys=new tz(K),this.started=!1,this.Zs=[];let l=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Xs=au(this.persistenceKey,this.js),this.eo=(s=this.persistenceKey,`firestore_sequence_number_${s}`),this.Ys=this.Ys.insert(this.js,new av),this.no=RegExp(`^${al}_${l}_([^_]*)$`),this.ro=RegExp(`^${ac}_${l}_(\\d+)(?:_(.*))?$`),this.io=RegExp(`^${ad}_${l}_(\\d+)$`),this.so=(a=this.persistenceKey,`firestore_online_state_${a}`),this.oo=(o=this.persistenceKey,`firestore_bundle_loaded_v2_${o}`),this.window.addEventListener("storage",this.Js)}static C(e){return!(!e||!e.localStorage)}async start(){for(let e of(await this.syncEngine.Ps())){if(e===this.js)continue;let t=this.getItem(au(this.persistenceKey,e));if(t){let n=ay.Ks(e,t);n&&(this.Ys=this.Ys.insert(n.clientId,n))}}this._o();let e=this.storage.getItem(this.so);if(e){let t=this.ao(e);t&&this.uo(t)}for(let e of this.Zs)this.Hs(e);this.Zs=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.eo,JSON.stringify(e))}getAllActiveQueryTargets(){return this.co(this.Ys)}isActiveQueryTarget(e){let t=!1;
6return this.Ys.forEach((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.lo(e,"pending")}updateMutationState(e,t,n){this.lo(e,t,n),this.ho(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){let t=this.storage.getItem(af(this.persistenceKey,e));if(t){let r=ap.Ks(e,t);r&&(n=r.state)}}return t&&this.Po.Gs(e),this._o(),n}removeLocalQueryTarget(e){this.Po.zs(e),this._o()}isLocalQueryTarget(e){return this.Po.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(af(this.persistenceKey,e))}updateQueryState(e,t,n){this.To(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.ho(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Io(e)}notifyBundleLoaded(e){this.Eo(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Js),this.removeItem(this.Xs),this.started=!1)}getItem(e){let t=this.storage.getItem(e);return _(am,"READ",e,t),t}setItem(e,t){_(am,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){_(am,"REMOVE",e),this.storage.removeItem(e)}Hs(e){if(e.storageArea===this.storage){if(_(am,"EVENT",e.key,e.newValue),e.key===this.Xs)return void T("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Fi.enqueueRetryable(async()=>{if(this.started){if(null!==e.key){if(this.no.test(e.key)){if(null==e.newValue){let t=this.Ao(e.key);return this.Ro(t,null)}{let t=this.Vo(e.key,e.newValue);if(t)return this.Ro(t.clientId,t)}}else if(this.ro.test(e.key)){if(null!==e.newValue){let t=this.mo(e.key,e.newValue);if(t)return this.fo(t)}}else if(this.io.test(e.key)){if(null!==e.newValue){let t=this.po(e.key,e.newValue);if(t)return this.yo(t)}}else if(e.key===this.so){if(null!==e.newValue){let t=this.ao(e.newValue);if(t)return this.uo(t)}}else if(e.key===this.eo){let t=function(e){let t=eU.ue;if(null!=e)try{let n=JSON.parse(e);C("number"==typeof n,30636,{wo:e}),t=n}catch(e){T(am,"Failed to read sequence number from WebStorage",e)}return t}(e.newValue);t!==eU.ue&&this.sequenceNumberHandler(t)}else if(e.key===this.oo){let t=this.So(e.newValue);await Promise.all(t.map(e=>this.syncEngine.bo(e)))}}}else this.Zs.push(e)})}}get Po(){return this.Ys.get(this.js)}_o(){this.setItem(this.Xs,this.Po.Ws())}lo(e,t,n){let r=new ag(this.currentUser,e,t,n),i=ah(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Ws())}ho(e){let t=ah(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Io(e){let t={clientId:this.js,onlineState:e};this.storage.setItem(this.so,JSON.stringify(t))}To(e,t,n){let r=af(this.persistenceKey,e),i=new ap(e,t,n);this.setItem(r,i.Ws())}Eo(e){let t=JSON.stringify(Array.from(e));this.setItem(this.oo,t)}Ao(e){let t=this.no.exec(e);return t?t[1]:null}Vo(e,t){let n=this.Ao(e);return ay.Ks(n,t)}mo(e,t){let n=this.ro.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return ag.Ks(new y(i),r,t)}po(e,t){let n=Number(this.io.exec(e)[1]);return ap.Ks(n,t)}ao(e){return aw.Ks(e)}So(e){return JSON.parse(e)}async fo(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Do(e.batchId,e.state,e.error);_(am,`Ignoring mutation for non-active user ${e.user.uid}`)}yo(e){return this.syncEngine.vo(e.targetId,e.state,e.error)}Ro(e,t){let n=t?this.Ys.insert(e,t):this.Ys.remove(e),r=this.co(this.Ys),i=this.co(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Co(s,a).then(()=>{this.Ys=n})}uo(e){this.Ys.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}co(e){let t=rw;return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class aI{constructor(){this.Fo=new av,this.Mo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.Fo.Gs(e),this.Mo[e]||"not-current"}updateQueryState(e,t,n){this.Mo[e]=t}removeLocalQueryTarget(e){this.Fo.zs(e)}isLocalQueryTarget(e){return this.Fo.activeTargetIds.has(e)}clearQueryState(e){delete this.Mo[e]}getAllActiveQueryTargets(){return this.Fo.activeTargetIds}isActiveQueryTarget(e){return this.Fo.activeTargetIds.has(e)}start(){return this.Fo=new av,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class a_{xo(e){}shutdown(){}}let aT="ConnectivityMonitor";class aE{constructor(){this.Oo=()=>this.No(),this.Bo=()=>this.Lo(),this.ko=[],this.qo()}xo(e){this.ko.push(e)}shutdown(){window.removeEventListener("online",this.Oo),window.removeEventListener("offline",this.Bo)}qo(){window.addEventListener("online",this.Oo),window.addEventListener("offline",this.Bo)}No(){for(let e of(_(aT,"Network connectivity changed: AVAILABLE"),this.ko))e(0)}Lo(){for(let e of(_(aT,"Network connectivity changed: UNAVAILABLE"),this.ko))e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let aS=null;function ax(){return null===aS?aS=0x10000000+Math.round(0x80000000*Math.random()):aS++,"0x"+aS.toString(16)}let aD="RestConnection",aC={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
6Query:"runAggregationQuery"};class aN{get Qo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.$o=t+"://"+e.host,this.Uo=`projects/${n}/databases/${r}`,this.Ko=this.databaseId.database===ne?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Wo(e,t,n,r,i){let s=ax(),a=this.Go(e,t.toUriEncodedString());_(aD,`Sending RPC '${e}' ${s}:`,a,n);let o={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.Ko};this.zo(o,r,i);let{host:l}=new URL(a),u=(0,c.zJ)(l);return this.jo(e,a,o,n,u).then(t=>(_(aD,`Received RPC '${e}' ${s}: `,t),t),t=>{throw E(aD,`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",n),t})}Jo(e,t,n,r,i,s){return this.Wo(e,t,n,r,i)}zo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+w,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,n)=>e[n]=t),n&&n.headers.forEach((t,n)=>e[n]=t)}Go(e,t){let n=aC[e];return`${this.$o}/v1/${t}:${n}`}terminate(){}}class aA{constructor(e){this.Ho=e.Ho,this.Yo=e.Yo}Zo(e){this.Xo=e}e_(e){this.t_=e}n_(e){this.r_=e}onMessage(e){this.i_=e}close(){this.Yo()}send(e){this.Ho(e)}s_(){this.Xo()}o_(){this.t_()}__(e){this.r_(e)}a_(e){this.i_(e)}}let ak="WebChannelConnection";class aR extends aN{constructor(e){super(e),this.u_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}jo(e,t,n,r,i){let s=ax();return new Promise((i,a)=>{let o=new d.ZS;o.setWithCredentials(!0),o.listenOnce(d.Bx.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case d.O4.NO_ERROR:let t=o.getResponseJson();_(ak,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case d.O4.TIMEOUT:_(ak,`RPC '${e}' ${s} timed out`),a(new k(A.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(_(ak,`RPC '${e}' ${s} failed with status:`,n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);let t=null==e?void 0:e.error;if(t&&t.status&&t.message){let e=function(e){let t=e.toLowerCase().replace(/_/g,"-");return Object.values(A).indexOf(t)>=0?t:A.UNKNOWN}(t.status);a(new k(e,t.message))}else a(new k(A.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new k(A.UNAVAILABLE,"Connection failed."));break;default:x(9055,{c_:e,streamId:s,l_:o.getLastErrorCode(),h_:o.getLastError()})}}finally{_(ak,`RPC '${e}' ${s} completed.`)}});let l=JSON.stringify(r);_(ak,`RPC '${e}' ${s} sending request:`,r),o.send(t,"POST",l,n,15)})}P_(e,t,n){let i=ax(),s=[this.$o,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=(0,d.fF)(),o=(0,d.Ao)(),l={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(l.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(l.useFetchStreams=!0),this.zo(l.initMessageHeaders,t,n),l.encodeInitMessageHeaders=!0;let c=s.join("");_(ak,`Creating RPC '${e}' stream ${i}: ${c}`,l);let h=a.createWebChannel(c,l);this.T_(h);let f=!1,m=!1,g=new aA({Ho:t=>{m?_(ak,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(f||(_(ak,`Opening RPC '${e}' stream ${i} transport.`),h.open(),f=!0),_(ak,`RPC '${e}' stream ${i} sending:`,t),h.send(t))},Yo:()=>h.close()}),p=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return p(h,d.iO.EventType.OPEN,()=>{m||(_(ak,`RPC '${e}' stream ${i} transport opened.`),g.s_())}),p(h,d.iO.EventType.CLOSE,()=>{m||(m=!0,_(ak,`RPC '${e}' stream ${i} transport closed`),g.__(),this.I_(h))}),p(h,d.iO.EventType.ERROR,t=>{m||(m=!0,E(ak,`RPC '${e}' stream ${i} transport errored. Name:`,t.name,"Message:",t.message),g.__(new k(A.UNAVAILABLE,"The operation could not be completed")))}),p(h,d.iO.EventType.MESSAGE,t=>{var n;if(!m){let s=t.data[0];C(!!s,16349);let a=(null==s?void 0:s.error)||(null==(n=s[0])?void 0:n.error);if(a){_(ak,`RPC '${e}' stream ${i} received error:`,a);let t=a.status,n=function(e){let t=r[e];if(void 0!==t)return rZ(t)}(t),s=a.message;void 0===n&&(n=A.INTERNAL,s="Unknown error status: "+t+" with message "+a.message),m=!0,g.__(new k(n,s)),h.close()}else _(ak,`RPC '${e}' stream ${i}
6 received:`,s),g.a_(s)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?_(ak,`RPC '${e}' stream ${i} detected buffering proxy`):t.stat===d.ro.NOPROXY&&_(ak,`RPC '${e}' stream ${i} detected no buffering proxy`)}),setTimeout(()=>{g.o_()},0),g}terminate(){this.u_.forEach(e=>e.close()),this.u_=[]}T_(e){this.u_.push(e)}I_(e){this.u_=this.u_.filter(t=>t===e)}}function aF(){return"undefined"!=typeof window?window:null}function aO(){return"undefined"!=typeof document?document:null}function aV(e){return new iu(e,!0)}class aP{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Fi=e,this.timerId=t,this.d_=n,this.E_=r,this.A_=i,this.R_=0,this.V_=null,this.m_=Date.now(),this.reset()}reset(){this.R_=0}f_(){this.R_=this.A_}g_(e){this.cancel();let t=Math.floor(this.R_+this.p_()),n=Math.max(0,Date.now()-this.m_),r=Math.max(0,t-n);r>0&&_("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.R_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.V_=this.Fi.enqueueAfterDelay(this.timerId,r,()=>(this.m_=Date.now(),e())),this.R_*=this.E_,this.R_<this.d_&&(this.R_=this.d_),this.R_>this.A_&&(this.R_=this.A_)}y_(){null!==this.V_&&(this.V_.skipDelay(),this.V_=null)}cancel(){null!==this.V_&&(this.V_.cancel(),this.V_=null)}p_(){return(Math.random()-.5)*this.R_}}let aM="PersistentStream";class aL{constructor(e,t,n,r,i,s,a,o){this.Fi=e,this.w_=n,this.S_=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.b_=0,this.D_=null,this.v_=null,this.stream=null,this.C_=0,this.F_=new aP(e,t)}M_(){return 1===this.state||5===this.state||this.x_()}x_(){return 2===this.state||3===this.state}start(){this.C_=0,4!==this.state?this.auth():this.O_()}async stop(){this.M_()&&await this.close(0)}N_(){this.state=0,this.F_.reset()}B_(){this.x_()&&null===this.D_&&(this.D_=this.Fi.enqueueAfterDelay(this.w_,6e4,()=>this.L_()))}k_(e){this.q_(),this.stream.send(e)}async L_(){if(this.x_())return this.close(0)}q_(){this.D_&&(this.D_.cancel(),this.D_=null)}Q_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.q_(),this.Q_(),this.F_.cancel(),this.b_++,4!==e?this.F_.reset():t&&t.code===A.RESOURCE_EXHAUSTED?(T(t.toString()),T("Using maximum backoff delay to prevent overloading the backend."),this.F_.f_()):t&&t.code===A.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.U_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.n_(t)}U_(){}auth(){this.state=1;let e=this.K_(this.b_),t=this.b_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.b_===t&&this.W_(e,n)},t=>{e(()=>{let e=new k(A.UNKNOWN,"Fetching auth token failed: "+t.message);return this.G_(e)})})}W_(e,t){let n=this.K_(this.b_);this.stream=this.z_(e,t),this.stream.Zo(()=>{n(()=>this.listener.Zo())}),this.stream.e_(()=>{n(()=>(this.state=2,this.v_=this.Fi.enqueueAfterDelay(this.S_,1e4,()=>(this.x_()&&(this.state=3),Promise.resolve())),this.listener.e_()))}),this.stream.n_(e=>{n(()=>this.G_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.C_?this.j_(e):this.onNext(e))})}O_(){this.state=5,this.F_.g_(async()=>{this.state=0,this.start()})}G_(e){return _(aM,`close with error: ${e}`),this.stream=null,this.close(4,e)}K_(e){return t=>{this.Fi.enqueueAndForget(()=>this.b_===e?t():(_(aM,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class aq extends aL{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}z_(e,t){return this.connection.P_("Listen",e,t)}j_(e){return this.onNext(e)}onNext(e){this.F_.reset();let t=function(e,t){let n;if("targetChange"in t){var r,i;t.targetChange;let s="NO_CHANGE"===(r=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===r?1:"REMOVE"===r?2:"CURRENT"===r?3:"RESET"===r?4:x(39313,{state:r}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(C(void 0===i||"string"==typeof i,58123),tX.fromBase64String(i||"")):(C(void 0===i||i instanceof m||i instanceof Uint8Array,16193),tX.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;n=new ie(s,a,o,l&&new k(void 0===l.code?A.UNKNOWN:rZ(l.code),l.message||"")||null)}else if("documentChange"in t){t.documentChange;let r=t.documentChange;r.document,r.document.name,r.document.updateTime;let i=iv(e,r.document.name),s=im(r.document.updateTime),a=r.document.createTime?im(r.document.createTime):eh.min(),o=new nD({mapValue:{fields:r.document.fields}}),l=nC.newFoundDocument(i,s,a,o);n=new r9(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let i=iv(e,r.document),s=r.readTime?im(r.readTime):eh.min(),a=nC.newNoDocument(i,s);n=new r9([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let i=iv(e,r.document);n=new r9([],r.removedTargetIds||[],i,null)}else{if(!("filter"in t))return x(11601,{At:t});{t.filter;let e=t.filter;e.targetId;
6let{count:r=0,unchangedNames:i}=e,s=new rX(r,i);n=new r7(e.targetId,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return eh.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?eh.min():t.readTime?im(t.readTime):eh.min()}(e);return this.listener.J_(t,n)}H_(e){let t={};t.database=i_(this.serializer),t.addTarget=function(e,t){let n,r=t.target;if((n=nZ(r)?{documents:iC(e,r)}:{query:iN(e,r).Vt}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=id(e,t.resumeToken);let r=ic(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(eh.min())>0){n.readTime=ih(e,t.snapshotVersion.toTimestamp());let r=ic(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);let n=function(e,t){let n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return x(28987,{purpose:e})}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.k_(t)}Y_(e){let t={};t.database=i_(this.serializer),t.removeTarget=e,this.k_(t)}}class aU extends aL{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}get Z_(){return this.C_>0}start(){this.lastStreamToken=void 0,super.start()}U_(){this.Z_&&this.X_([])}z_(e,t){return this.connection.P_("Write",e,t)}j_(e){return C(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,C(!e.writeResults||0===e.writeResults.length,55816),this.listener.ea()}onNext(e){var t,n;C(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.F_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(C(void 0!==n,14353),t.map(e=>{let t;return(t=e.updateTime?im(e.updateTime):im(n)).isEqual(eh.min())&&(t=im(n)),new rF(t,e.transformResults||[])})):[]),i=im(e.commitTime);return this.listener.ta(i,r)}na(){let e={};e.database=i_(this.serializer),this.k_(e)}X_(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>ix(this.serializer,e))};this.k_(t)}}class aB{}class az extends aB{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.ra=!1}ia(){if(this.ra)throw new k(A.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,n,r){return this.ia(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.Wo(e,ip(t,n),r,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new k(A.UNKNOWN,e.toString())})}Jo(e,t,n,r,i){return this.ia(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.Jo(e,ip(t,n),r,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new k(A.UNKNOWN,e.toString())})}terminate(){this.ra=!0,this.connection.terminate()}}class a${constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.sa=0,this.oa=null,this._a=!0}aa(){0===this.sa&&(this.ua("Unknown"),this.oa=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.oa=null,this.ca("Backend didn't respond within 10 seconds."),this.ua("Offline"),Promise.resolve())))}la(e){"Online"===this.state?this.ua("Unknown"):(this.sa++,this.sa>=1&&(this.ha(),this.ca(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ua("Offline")))}set(e){this.ha(),this.sa=0,"Online"===e&&(this._a=!1),this.ua(e)}ua(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ca(e){let t=`Could not reach Cloud Firestore backend. ${e}
7This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this._a?(T(t),this._a=!1):_("OnlineStateTracker",t)}ha(){null!==this.oa&&(this.oa.cancel(),this.oa=null)}}let aK="RemoteStore";class aj{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Pa=[],this.Ta=new Map,this.Ia=new Set,this.da=[],this.Ea=i,this.Ea.xo(e=>{n.enqueueAndForget(async()=>
7{a0(this)&&(_(aK,"Restarting streams for network reachability change."),await async function(e){e.Ia.add(4),await aQ(e),e.Aa.set("Unknown"),e.Ia.delete(4),await aG(e)}(this))})}),this.Aa=new a$(n,r)}}async function aG(e){if(a0(e))for(let t of e.da)await t(!0)}async function aQ(e){for(let t of e.da)await t(!1)}function aW(e,t){e.Ta.has(t.targetId)||(e.Ta.set(t.targetId,t),aZ(e)?aY(e):oa(e).x_()&&aJ(e,t))}function aH(e,t){let n=oa(e);e.Ta.delete(t),n.x_()&&aX(e,t),0===e.Ta.size&&(n.x_()?n.B_():a0(e)&&e.Aa.set("Unknown"))}function aJ(e,t){if(e.Ra.$e(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(eh.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}oa(e).H_(t)}function aX(e,t){e.Ra.$e(t),oa(e).Y_(t)}function aY(e){e.Ra=new ir({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Et:t=>e.Ta.get(t)||null,lt:()=>e.datastore.serializer.databaseId}),oa(e).start(),e.Aa.aa()}function aZ(e){return a0(e)&&!oa(e).M_()&&e.Ta.size>0}function a0(e){return 0===e.Ia.size}async function a1(e){e.Aa.set("Online")}async function a2(e){e.Ta.forEach((t,n)=>{aJ(e,t)})}async function a5(e,t){e.Ra=void 0,aZ(e)?(e.Aa.la(t),aY(e)):e.Aa.set("Unknown")}async function a6(e,t,n){if(e.Aa.set("Online"),t instanceof ie&&2===t.state&&t.cause)try{await async function(e,t){let n=t.cause;for(let r of t.targetIds)e.Ta.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Ta.delete(r),e.Ra.removeTarget(r))}(e,t)}catch(n){_(aK,"Failed to remove targets %s: %s ",t.targetIds.join(","),n),await a4(e,n)}else if(t instanceof r9?e.Ra.Ye(t):t instanceof r7?e.Ra.it(t):e.Ra.et(t),!n.isEqual(eh.min()))try{let t=await s9(e.localStore);n.compareTo(t)>=0&&await function(e,t){let n=e.Ra.Pt(t);
7return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){let i=e.Ta.get(r);i&&e.Ta.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{let r=e.Ta.get(t);if(!r)return;e.Ta.set(t,r.withResumeToken(tX.EMPTY_BYTE_STRING,r.snapshotVersion)),aX(e,t);let i=new iV(r.target,t,n,r.sequenceNumber);aJ(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){_(aK,"Failed to raise snapshot:",t),await a4(e,t)}}async function a4(e,t,n){if(!eR(t))throw t;e.Ia.add(1),await aQ(e),e.Aa.set("Offline"),n||(n=()=>s9(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{_(aK,"Retrying IndexedDB access"),await n(),e.Ia.delete(1),await aG(e)})}function a3(e,t){return t().catch(n=>a4(e,n,t))}async function a8(e){var t;let n=oo(e),r=e.Pa.length>0?e.Pa[e.Pa.length-1].batchId:-1;for(;a0(t=e)&&t.Pa.length<10;)try{let t=await function(e,t){return e.persistence.runTransaction("Get next mutation batch","readonly",n=>(void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)))}(e.localStore,r);if(null===t){0===e.Pa.length&&n.B_();break}r=t.batchId,function(e,t){e.Pa.push(t);let n=oo(e);n.x_()&&n.Z_&&n.X_(t.mutations)}(e,t)}catch(t){await a4(e,t)}a9(e)&&a7(e)}function a9(e){return a0(e)&&!oo(e).M_()&&e.Pa.length>0}function a7(e){oo(e).start()}async function oe(e){oo(e).na()}async function ot(e){let t=oo(e);for(let n of e.Pa)t.X_(n.mutations)}async function on(e,t,n){let r=e.Pa.shift(),i=rW.from(r,t,n);await a3(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await a8(e)}async function or(e,t){t&&oo(e).Z_&&await async function(e,t){var n;if(rY(n=t.code)&&n!==A.ABORTED){let n=e.Pa.shift();oo(e).N_(),await a3(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await a8(e)}}(e,t),a9(e)&&a7(e)}async function oi(e,t){e.asyncQueue.verifyOperationInProgress(),_(aK,"RemoteStore received new credentials");let n=a0(e);e.Ia.add(3),await aQ(e),n&&e.Aa.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.Ia.delete(3),await aG(e)}async function os(e,t){t?(e.Ia.delete(2),await aG(e)):t||(e.Ia.add(2),await aQ(e),e.Aa.set("Unknown"))}function oa(e){var t,n,r;return e.Va||(t=e.datastore,n=e.asyncQueue,r={Zo:a1.bind(null,e),e_:a2.bind(null,e),n_:a5.bind(null,e),J_:a6.bind(null,e)},t.ia(),e.Va=new aq(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.Va.N_(),aZ(e)?aY(e):e.Aa.set("Unknown")):(await e.Va.stop(),e.Ra=void 0)})),e.Va}function oo(e){var t,n,r;return e.ma||(t=e.datastore,n=e.asyncQueue,r={Zo:()=>Promise.resolve(),e_:oe.bind(null,e),n_:or.bind(null,e),ea:ot.bind(null,e),ta:on.bind(null,e)},t.ia(),e.ma=new aU(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.ma.N_(),await a8(e)):(await e.ma.stop(),e.Pa.length>0&&(_(aK,`Stopping write stream with ${e.Pa.length} pending writes`),e.Pa=[]))})),e.ma}class ol{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new R,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){let s=new ol(e,t,Date.now()+n,r,i);return s.start(n),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new k(A.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function ou(e,t){if(T("AsyncQueue",`${t}: ${e}`),eR(e))return new k(A.UNAVAILABLE,`${t}: ${e}`);throw e}class oc{static emptySet(e){return new oc(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||Z.comparator(t.key,n.key):(e,t)=>Z.comparator(e.key,t.key),this.keyedMap=rd(),this.sortedSet=new tz(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof oc)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"}copy(e,t){let n=new oc;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class oh{constructor(){this.fa=new tz(Z.comparator)}track(e){let t=e.doc.key,n=this.fa.get(t);n?0!==e.type&&3===n.type?this.fa=this.fa.insert(t,e):3===e.type&&1!==n.type?this.fa=this.fa.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.fa=this.fa.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.fa=this.fa.remove(t):1===e.type&&2===n.type?this.fa=this.fa.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):x(63341,{At:e,ga:n}):this.fa=this.fa.insert(t,e)}pa(){let e=[];return this.fa.inorderTraversal((t,n)=>{e.push(n)}),e}}class od{constructor(e,t,n,r,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,i){let s=[];
7return t.forEach(e=>{s.push({type:0,doc:e})}),new od(e,t,oc.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&rr(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class of{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(e=>e.ba())}}class om{constructor(){this.queries=og(),this.onlineState="Unknown",this.Da=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=og(),n.forEach((e,n)=>{for(let e of n.wa)e.onError(t)})}(this,new k(A.ABORTED,"Firestore shutting down"))}}function og(){return new ru(e=>ri(e),rr)}async function op(e,t){let n=3,r=t.query,i=e.queries.get(r);i?!i.Sa()&&t.ba()&&(n=2):(i=new of,n=+!t.ba());try{switch(n){case 0:i.ya=await e.onListen(r,!0);break;case 1:i.ya=await e.onListen(r,!1);break;case 2:await e.onFirstRemoteStoreListen(r)}}catch(n){let e=ou(n,`Initialization of query '${rs(t.query)}' failed`);return void t.onError(e)}e.queries.set(r,i),i.wa.push(t),t.va(e.onlineState),i.ya&&t.Ca(i.ya)&&ob(e)}async function oy(e,t){let n=t.query,r=3,i=e.queries.get(n);if(i){let e=i.wa.indexOf(t);e>=0&&(i.wa.splice(e,1),0===i.wa.length?r=+!t.ba():!i.Sa()&&t.ba()&&(r=2))}switch(r){case 0:return e.queries.delete(n),e.onUnlisten(n,!0);case 1:return e.queries.delete(n),e.onUnlisten(n,!1);case 2:return e.onLastRemoteStoreUnlisten(n);default:return}}function ow(e,t){let n=!1;for(let r of t){let t=r.query,i=e.queries.get(t);if(i){for(let e of i.wa)e.Ca(r)&&(n=!0);i.ya=r}}n&&ob(e)}function ov(e,t,n){let r=e.queries.get(t);if(r)for(let e of r.wa)e.onError(n);e.queries.delete(t)}
7function ob(e){e.Da.forEach(e=>{e.next()})}(a=s||(s={})).Fa="default",a.Cache="cache";class oI{constructor(e,t,n){this.query=e,this.Ma=t,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=n||{}}Ca(e){if(!this.options.includeMetadataChanges){let t=[];for(let n of e.docChanges)3!==n.type&&t.push(n);e=new od(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.xa?this.Na(e)&&(this.Ma.next(e),t=!0):this.Ba(e,this.onlineState)&&(this.La(e),t=!0),this.Oa=e,t}onError(e){this.Ma.error(e)}va(e){this.onlineState=e;let t=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,e)&&(this.La(this.Oa),t=!0),t}Ba(e,t){return!(e.fromCache&&this.ba())||(!this.options.ka||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Na(e){if(e.docChanges.length>0)return!0;let t=this.Oa&&this.Oa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}La(e){e=od.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.xa=!0,this.Ma.next(e)}ba(){return this.options.source!==s.Cache}}class o_{constructor(e,t){this.qa=e,this.byteLength=t}Qa(){return"metadata"in this.qa}}class oT{constructor(e){this.serializer=e}Qs(e){return iv(this.serializer,e)}$s(e){return e.metadata.exists?iS(this.serializer,e.document,!1):nC.newNoDocument(this.Qs(e.metadata.name),this.Us(e.metadata.readTime))}Us(e){return im(e)}}class oE{constructor(e,t){this.$a=e,this.serializer=t,this.Ua=[],this.Ka=[],this.collectionGroups=new Set,this.progress=oS(e)}get queries(){return this.Ua}get documents(){return this.Ka}Wa(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.qa.namedQuery)this.Ua.push(e.qa.namedQuery);else if(e.qa.documentMetadata){this.Ka.push({metadata:e.qa.documentMetadata}),e.qa.documentMetadata.exists||++t;let n=J.fromString(e.qa.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.qa.document&&(this.Ka[this.Ka.length-1].document=e.qa.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Ga(e){let t=new Map,n=new oT(this.serializer);for(let r of e)if(r.metadata.queries){let e=n.Qs(r.metadata.name);for(let n of r.metadata.queries){let r=(t.get(n)||ry()).add(e);t.set(n,r)}}return t}async za(e){let t=await aa(e,new oT(this.serializer),this.Ka,this.$a.id),n=this.Ga(this.documents);for(let t of this.Ua)await ao(e,t,n.get(t.name));return this.progress.taskState="Success",{progress:this.progress,ja:this.collectionGroups,Ja:t}}}function oS(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class ox{constructor(e){this.key=e}}class oD{constructor(e){this.key=e}}class oC{constructor(e,t){this.query=e,this.Ha=t,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=ry(),this.mutatedKeys=ry(),this.Xa=rl(e),this.eu=new oc(this.Xa)}get tu(){return this.Ha}nu(e,t){let n=t?t.ru:new oh,r=t?t.eu:this.eu,i=t?t.mutatedKeys:this.mutatedKeys,s=r,a=!1,o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal((e,t)=>{let u=r.get(e),c=ra(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!c&&(c.hasLocalMutations||this.mutatedKeys.has(c.key)&&c.hasCommittedMutations),f=!1;u&&c?u.data.isEqual(c.data)?h!==d&&(n.track({type:3,doc:c}),f=!0):this.iu(u,c)||(n.track({type:2,doc:c}),f=!0,(o&&this.Xa(c,o)>0||l&&0>this.Xa(c,l))&&(a=!0)):!u&&c?(n.track({type:0,doc:c}),f=!0):u&&!c&&(n.track({type:1,doc:u}),f=!0,(o||l)&&(a=!0)),f&&(c?(s=s.add(c),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;){let e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{eu:s,ru:n,Ds:a,mutatedKeys:i}}iu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){let i=this.eu;this.eu=e.eu,this.mutatedKeys=e.mutatedKeys;let s=e.ru.pa();s.sort((e,t)=>
7(function(e,t){let n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return x(20277,{At:e})}};return n(e)-n(t)})(e.type,t.type)||this.Xa(e.doc,t.doc)),this.su(n),r=null!=r&&r;let a=t&&!r?this.ou():[],o=0===this.Za.size&&this.current&&!r?1:0,l=o!==this.Ya;return(this.Ya=o,0!==s.length||l)?{snapshot:new od(this.query,e.eu,i,s,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),_u:a}:{_u:a}}va(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({eu:this.eu,ru:new oh,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(e){return!this.Ha.has(e)&&!!this.eu.has(e)&&!this.eu.get(e).hasLocalMutations}su(e){e&&(e.addedDocuments.forEach(e=>this.Ha=this.Ha.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ha=this.Ha.delete(e)),this.current=e.current)}ou(){if(!this.current)return[];let e=this.Za;this.Za=ry(),this.eu.forEach(e=>{this.au(e.key)&&(this.Za=this.Za.add(e.key))});let t=[];return e.forEach(e=>{this.Za.has(e)||t.push(new oD(e))}
7),this.Za.forEach(n=>{e.has(n)||t.push(new ox(n))}),t}uu(e){this.Ha=e.qs,this.Za=ry();let t=this.nu(e.documents);return this.applyChanges(t,!0)}cu(){return od.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,0===this.Ya,this.hasCachedResults)}}let oN="SyncEngine";class oA{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class ok{constructor(e){this.key=e,this.lu=!1}}class oR{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.hu={},this.Pu=new ru(e=>ri(e),rr),this.Tu=new Map,this.Iu=new Set,this.du=new tz(Z.comparator),this.Eu=new Map,this.Au=new sq,this.Ru={},this.Vu=new Map,this.mu=sw.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return!0===this.fu}}async function oF(e,t,n=!0){let r,i=le(e),s=i.Pu.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),r=s.view.cu()):r=await oV(i,t,n,!0),r}async function oO(e,t){let n=le(e);await oV(n,t,!0,!1)}async function oV(e,t,n,r){let i,s=await ae(e.localStore,n9(t)),a=s.targetId,o=e.sharedCl
7ientState.addLocalQueryTarget(a,n);return r&&(i=await oP(e,t,a,"current"===o,s.resumeToken)),e.isPrimaryClient&&n&&aW(e.remoteStore,s),i}async function oP(e,t,n,r,i){e.gu=(t,n,r)=>(async function(e,t,n,r){let i=t.view.nu(n);i.Ds&&(i=await an(e.localStore,t.query,!1).then(({documents:e})=>t.view.nu(e,i)));let s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s,a);return oJ(e,t.targetId,o._u),o.snapshot})(e,t,n,r);let s=await an(e.localStore,t,!0),a=new oC(t,s.qs),o=a.nu(s.documents),l=r8.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);oJ(e,n,u._u);let c=new oA(t,n,a);return e.Pu.set(t,c),e.Tu.has(n)?e.Tu.get(n).push(t):e.Tu.set(n,[t]),u.snapshot}async function oM(e,t,n){let r=e.Pu.get(t),i=e.Tu.get(r.targetId);if(i.length>1)return e.Tu.set(r.targetId,i.filter(e=>!rr(e,t))),void e.Pu.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(r.targetId),e.sharedClientState.isActiveQueryTarget(r.targetId)||await at(e.localStore,r.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(r.targetId),n&&aH(e.remoteStore,r.targetId),oW(e,r.targetId)}).catch(eE)):(oW(e,r.targetId),await at(e.localStore,r.targetId,!0))}async function oL(e,t){let n=e.Pu.get(t),r=e.Tu.get(n.targetId);e.isPrimaryClient&&1===r.length&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),aH(e.remoteStore,n.targetId))}async function oq(e,t,n){let r=lt(e);try{var i;let e,s=await function(e,t){let n,r,i=ec.now(),s=t.reduce((e,t)=>e.add(t.key),ry());return e.persistence.runTransaction("Locally write mutations","readwrite",a=>{let o=rc,l=ry();return e.Os.getEntries(a,s).next(e=>{(o=e).forEach((e,t)=>{t.isValidDocument()||(l=l.add(e))})}).next(()=>e.localDocuments.getOverlayedDocuments(a,o)).next(r=>{n=r;let s=[];for(let e of t){let t=function(e,t){let n=null;for(let r of e.fieldTransforms){let e=t.data.field(r.field),i=rT(r.transform,e||null);null!=i&&(null===n&&(n=nD.empty()),n.set(r.field,i))}return n||null}(e,n.get(e.key).overlayedDocument);null!=t&&s.push(new rB(e.key,t,function e(t){let n=[];return tq(t.fields,(t,r)=>{let i=new Y([t]);if(nb(r)){let t=e(r.mapValue).fields;if(0===t.length)n.push(i);else for(let e of t)n.push(i.child(e))}else n.push(i)}),new tW(n)}(t.value.mapValue),rO.exists(!0)))}return e.mutationQueue.addMutationBatch(a,i,s,t)}).next(t=>{r=t;let i=t.applyToLocalDocumentSet(n,l);return e.documentOverlayCache.saveOverlays(a,t.batchId,i)})}).then(()=>({batchId:r.batchId,changes:rf(n)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(s.batchId),i=s.batchId,(e=r.Ru[r.currentUser.toKey()])||(e=new tz(K)),e=e.insert(i,n),r.Ru[r.currentUser.toKey()]=e,await oY(r,s.changes),await a8(r.remoteStore)}catch(t){let e=ou(t,"Failed to persist write");n.reject(e)}}async function oU(e,t){try{let n=await function(e,t){let n=t.snapshotVersion,r=e.Fs;return e.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{let s=e.Os.newChangeBuffer({trackRemovals:!0});r=e.Fs;let a=[];
7t.targetChanges.forEach((s,o)=>{var l;let u=r.get(o);if(!u)return;a.push(e.hi.removeMatchingKeys(i,s.removedDocuments,o).next(()=>e.hi.addMatchingKeys(i,s.addedDocuments,o)));let c=u.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(o)?c=c.withResumeToken(tX.EMPTY_BYTE_STRING,eh.min()).withLastLimboFreeSnapshotVersion(eh.min()):s.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(s.resumeToken,n)),r=r.insert(o,c),l=c,(0===u.resumeToken.approximateByteSize()||l.snapshotVersion.toMicroseconds()-u.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&a.push(e.hi.updateTargetData(i,c))});let o=rc,l=ry();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&a.push(e.persistence.referenceDelegate.updateLimboDocument(i,n))}),a.push(s7(i,s,t.documentUpdates).next(e=>{o=e.Ls,l=e.ks})),!n.isEqual(eh.min())){let t=e.hi.getLastRemoteSnapshotVersion(i).next(t=>e.hi.setTargetsMetadata(i,i.currentSequenceNumber,n));a.push(t)}return eS.waitFor(a).next(()=>s.apply(i)).next(()=>e.localDocuments.getLocalViewOfDocuments(i,o,l)).next(()=>o)}).then(t=>(e.Fs=r,t))}(e.localStore,t);
7t.targetChanges.forEach((t,n)=>{let r=e.Eu.get(n);r&&(C(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?r.lu=!0:t.modifiedDocuments.size>0?C(r.lu,14607):t.removedDocuments.size>0&&(C(r.lu,42227),r.lu=!1))}),await oY(e,n,t)}catch(e){await eE(e)}}function oB(e,t,n){var r;if(e.isPrimaryClient&&0===n||!e.isPrimaryClient&&1===n){let n,i=[];e.Pu.forEach((e,n)=>{let r=n.view.va(t);r.snapshot&&i.push(r.snapshot)}),(r=e.eventManager).onlineState=t,n=!1,r.queries.forEach((e,r)=>{for(let e of r.wa)e.va(t)&&(n=!0)}),n&&ob(r),i.length&&e.hu.J_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function oz(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Eu.get(t),i=r&&r.key;if(i){let n=new tz(Z.comparator);n=n.insert(i,nC.newNoDocument(i,eh.min()));let r=ry().add(i),s=new r3(eh.min(),new Map,new tz(K),n,r);await oU(e,s),e.du=e.du.remove(i),e.Eu.delete(t),oX(e)}else await at(e.localStore,t,!1).then(()=>oW(e,t,n)).catch(eE)}async function o$(e,t){var n;let r=t.batch.batchId;try{let i=await (n=e.localStore,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),i=n.Os.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let i=n.batch,s=i.keys(),a=eS.resolve();return s.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let s=n.docVersions.get(e);C(null!==s,48541),0>t.version.compareTo(s)&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))})(n,e,t,i).next(()=>i.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=ry();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))).next(()=>n.localDocuments.getDocuments(e,r))}));oQ(e,r,null),oG(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await oY(e,i)}catch(e){await eE(e)}}async function oK(e,t,n){var r;try{let i=await (r=e.localStore,r.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(C(null!==t,37113),n=t.keys(),r.mutationQueue.removeMutationBatch(e,t))).next(()=>r.mutationQueue.performConsistencyCheck(e)).next(()=>r.documentOverlayCache.removeOverlaysForBatchId(e,n,t)).next(()=>r.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,n)).next(()=>r.localDocuments.getDocuments(e,n))}));oQ(e,t,n),oG(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await oY(e,i)}catch(e){await eE(e)}}async function oj(e,t){var n;a0(e.remoteStore)||_(oN,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{let r=await (n=e.localStore).persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>n.mutationQueue.getHighestUnacknowledgedBatchId(e));if(-1===r)return void t.resolve();let i=e.Vu.get(r)||[];i.push(t),e.Vu.set(r,i)}catch(n){let e=ou(n,"Initialization of waitForPendingWrites() operation failed");t.reject(e)}}function oG(e,t){(e.Vu.get(t)||[]).forEach(e=>{e.resolve()}),e.Vu.delete(t)}function oQ(e,t,n){let r=e.Ru[e.currentUser.toKey()];if(r){let i=r.get(t);i&&(n?i.reject(n):i.resolve(),r=r.remove(t)),e.Ru[e.currentUser.toKey()]=r}}function oW(e,t,n=null){for(let r of(e.sharedClientState.removeLocalQueryTarget(t),e.Tu.get(t)))e.Pu.delete(r),n&&e.hu.pu(r,n);e.Tu.delete(t),e.isPrimaryClient&&e.Au.zr(t).forEach(t=>{e.Au.containsKey(t)||oH(e,t)})}function oH(e,t){e.Iu.delete(t.path.canonicalString());let n=e.du.get(t);null!==n&&(aH(e.remoteStore,n),e.du=e.du.remove(t),e.Eu.delete(n),oX(e))}function oJ(e,t,n){for(let r of n)r instanceof ox?(e.Au.addReference(r.key,t),function(e,t){let n=t.key,r=n.path.canonicalString();e.du.get(n)||e.Iu.has(r)||(_(oN,"New document in limbo: "+n),e.Iu.add(r),oX(e))}(e,r)):r instanceof oD?(_(oN,"Document no longer in limbo: "+r.key),e.Au.removeReference(r.key,t),e.Au.containsKey(r.key)||oH(e,r.key)):x(19791,{yu:r})}function oX(e){for(;e.Iu.size>0&&e.du.size<e.maxConcurrentLimboResolutions;){let t=e.Iu.values().next().value;e.Iu.delete(t);let n=new Z(J.fromString(t)),r=e.mu.next();e.Eu.set(r,new ok(n)),e.du=e.du.insert(n,r),aW(e.remoteStore,new iV(n9(n6(n.path)),r,"TargetPurposeLimboResolution",eU.ue))}}async function oY(e,t,n){let r=[],i=[],s=[];e.Pu.isEmpty()||(e.Pu.forEach((a,o)=>{s.push(e.gu(o,t,n).then(t=>{var s;if((t||n)&&e.isPrimaryClient){let r=t?!t.fromCache:null==(s=null==n?void 0:n.targetChanges.get(o.targetId))?void 0:s.current;
7e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=s2.Es(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.hu.J_(r),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>eS.forEach(t,t=>eS.forEach(t.Is,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>eS.forEach(t.ds,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!eR(e))throw e;_(s4,"Failed to update sequence numbers: "+e)}for(let n of t){let t=n.targetId;if(!n.fromCache){let n=e.Fs.get(t),r=n.snapshotVersion,i=n.withLastLimboFreeSnapshotVersion(r);e.Fs=e.Fs.insert(t,i)}}}(e.localStore,i))}async function oZ(e,t){if(!e.currentUser.isEqual(t)){_(oN,"User change. New user:",t.toKey());let n=await s8(e.localStore,t);e.currentUser=t,e.Vu.forEach(e=>{e.forEach(e=>{e.reject(new k(A.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Vu.clear(),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await oY(e,n.Bs)}}function o0(e,t){let n=e.Eu.get(t);if(n&&n.lu)return ry().add(n.key);{let n=ry(),r=e.Tu.get(t);if(!r)return n;for(let t of r){let r=e.Pu.get(t);n=n.unionWith(r.view.tu)}return n}}async function o1(e,t){let n=await an(e.localStore,t.query,!0),r=t.view.uu(n);return e.isPrimaryClient&&oJ(e,t.targetId,r._u),r}async function o2(e,t){return ai(e.localStore,t).then(t=>oY(e,t))}async function o5(e,t,n,r){var i;let s=await function(e,t){let n=e.mutationQueue;return e.persistence.runTransaction("Lookup mutation documents","readonly",r=>n.Xn(r,t).next(t=>t?e.localDocuments.getDocuments(r,t):eS.resolve(null)))}(e.localStore,t);null!==s?("pending"===n?await a8(e.remoteStore):"acknowledged"===n||"rejected"===n?(oQ(e,t,r||null),oG(e,t),i=e.localStore,i.mutationQueue.rr(t)):x(6720,"Unknown batchState",{wu:n}),await oY(e,s)):_(oN,"Cannot apply mutation batch with id: "+t)}async function o6(e,t){if(le(e),lt(e),!0===t&&!0!==e.fu){let t=e.sharedClientState.getAllActiveQueryTargets(),n=await o4(e,t.toArray());for(let t of(e.fu=!0,await os(e.remoteStore,!0),n))aW(e.remoteStore,t)}else if(!1===t&&!1!==e.fu){let t=[],n=Promise.resolve();e.Tu.forEach((r,i)=>{e.sharedClientState.isLocalQueryTarget(i)?t.push(i):n=n.then(()=>(oW(e,i),at(e.localStore,i,!0))),aH(e.remoteStore,i)}),await n,await o4(e,t),e.Eu.forEach((t,n)=>{aH(e.remoteStore,n)}),e.Au.jr(),e.Eu=new Map,e.du=new tz(Z.comparator),e.fu=!1,await os(e.remoteStore,!1)}}async function o4(e,t,n){let r=[],i=[];for(let n of t){let t,s=e.Tu.get(n);if(s&&0!==s.length)for(let n of(t=await ae(e.localStore,n9(s[0])),s)){let t=e.Pu.get(n),r=await o1(e,t);r.snapshot&&i.push(r.snapshot)}else{let r=await ar(e.localStore,n);t=await ae(e.localStore,r),await oP(e,o3(r),n,!1,t.resumeToken)}r.push(t)}return e.hu.J_(i),r}function o3(e){var t,n,r,i,s;return t=e.path,n=e.collectionGroup,r=e.orderBy,i=e.filters,s=e.limit,new n5(t,n,r,i,s,"F",e.startAt,e.endAt)}function o8(e){return e.localStore.persistence.Ps()}async function o9(e,t,n,r){if(e.fu)return void _(oN,"Ignoring unexpected query state notification.");let i=e.Tu.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{let r=await ai(e.localStore,ro(i[0])),s=r3.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,tX.EMPTY_BYTE_STRING);await oY(e,r,s);break}case"rejected":await at(e.localStore,t,!0),oW(e,t,r);break;default:x(64155,n)}}async function o7(e,t,n){let r=le(e);if(r.fu){for(let e of t){if(r.Tu.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){_(oN,"Adding an already active target "+e);continue}let t=await ar(r.localStore,e),n=await ae(r.localStore,t);await oP(r,o3(t),n.targetId,!1,n.resumeToken),aW(r.remoteStore,n)}for(let e of n)r.Tu.has(e)&&await at(r.localStore,e,!1).then(()=>{aH(r.remoteStore,e),oW(r,e)}).catch(eE)}}function le(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=oU.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=o0.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=oz.bind(null,e),e.hu.J_=ow.bind(null,e.eventManager),e.hu.pu=ov.bind(null,e.eventManager),e}function lt(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=o$.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=oK.bind(null,e),e}class ln{constructor(){this.kind="memory",this.synchronizeTabs=!1}
7async initialize(e){this.serializer=aV(e.databaseInfo.databaseId),this.sharedClientState=this.bu(e),this.persistence=this.Du(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Cu(e,this.localStore),this.indexBackfillerScheduler=this.Fu(e,this.localStore)}Cu(e,t){return null}Fu(e,t){return null}vu(e){var t,n;return t=this.persistence,n=new s6,new s3(t,n,e.initialUser,this.serializer)}Du(e){return new sj(sQ.Vi,this.serializer)}bu(e){return new aI}async terminate(){var e,t;null==(e=this.gcScheduler)||e.stop(),null==(t=this.indexBackfillerScheduler)||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}ln.provider={build:()=>new ln};class lr extends ln{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,t){return C(this.persistence.referenceDelegate instanceof sW,46915),new sE(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Du(e){let t=void 0!==this.cacheSizeBytes?sd.withCacheSize(this.cacheSizeBytes):sd.DEFAULT;return new sj(e=>sW.Vi(e,t),this.serializer)}}class li extends ln{constructor(e,t,n){super(),this.Mu=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Mu.initialize(this,e),await lt(this.Mu.syncEngine),await a8(this.Mu.remoteStore),await this.persistence.ji(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}vu(e){var t,n;return t=this.persistence,n=new s6,new s3(t,n,e.initialUser,this.serializer)}Cu(e,t){return new sE(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Fu(e,t){let n=new eq(t,this.persistence);return new eL(e.asyncQueue,n)}Du(e){let t=s1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?sd.withCacheSize(this.cacheSizeBytes):sd.DEFAULT;return new s0(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,aF(),aO(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(e){return new aI}}class ls extends li{constructor(e,t){super(e,t,!1),this.Mu=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);let t=this.Mu.syncEngine;this.sharedClientState instanceof ab&&(this.sharedClientState.syncEngine={Do:o5.bind(null,t),vo:o9.bind(null,t),Co:o7.bind(null,t),Ps:o8.bind(null,t),bo:o2.bind(null,t)},await this.sharedClientState.start()),await this.persistence.ji(async e=>{await o6(this.Mu.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}bu(e){let t=aF();if(!ab.C(t))throw new k(A.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let n=s1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ab(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class la{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>oB(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=oZ.bind(null,this.syncEngine),await os(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new om}createDatastore(e){var t;let n=aV(e.databaseInfo.databaseId),r=new aR(e.databaseInfo);return t=e.authCredentials,new az(t,e.appCheckCredentials,r,n)}createRemoteStore(e){var t,n;return t=this.localStore,n=this.datastore,new aj(t,n,e.asyncQueue,e=>oB(this.syncEngine,e,0),aE.C()?new aE:new a_)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){let o=new oR(e,t,n,r,i,s);return a&&(o.fu=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedCl
7ientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){_(aK,"RemoteStore shutting down."),e.Ia.add(5),await aQ(e),e.Ea.shutdown(),e.Aa.set("Unknown")}(this.remoteStore),null==(e=this.datastore)||e.terminate(),null==(t=this.eventManager)||t.terminate()}}function lo(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){let r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}la.provider={build:()=>new la};class ll{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.xu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.xu(this.observer.error,e):T("Uncaught Error in snapshot listener:",e.toString()))}Ou(){this.muted=!0}xu(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class lu{constructor(e,t){this.Nu=e,this.serializer=t,this.metadata=new R,this.buffer=new Uint8Array,this.Bu=new TextDecoder("utf-8"),this.Lu().then(e=>{e&&e.Qa()?this.metadata.resolve(e.qa.metadata):this.metadata.reject(Error(`The first element of the bundle is not a metadata, it is
8             ${JSON.stringify(null==e?void 0:e.qa)}`))},e=>this.metadata.reject(e))}close(){return this.Nu.cancel()}async getMetadata(){return this.metadata.promise}async Su(){return await this.getMetadata(),this.Lu()}async Lu(){let e=await this.ku();if(null===e)return null;let t=this.Bu.decode(e),n=Number(t);return isNaN(n)&&this.qu(`length string (${t}) is not valid number`),new o_(JSON.parse(await this.Qu(n)),e.length+n)}$u(){return this.buffer.findIndex(e=>123===e)}async ku(){for(;0>this.$u()&&!await this.Uu(););if(0===this.buffer.length)return null;let e=this.$u();e<0&&this.qu("Reached the end of bundle when a length string is expected.");let t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Qu(e){for(;this.buffer.length<e;)await this.Uu()&&this.qu("Reached the end of bundle when more is expected.");let t=this.Bu.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}qu(e){throw this.Nu.cancel(),Error(`Invalid bundle format: ${e}`)}async Uu(){let e=await this.Nu.read();if(!e.done){let t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class lc{constructor(e,t){this.bundleData=e,this.serializer=t,this.cursor=0,this.elements=[];let n=this.Su();if(!n||!n.Qa())throw Error(`The first element of the bundle is not a metadata object, it is
9         ${JSON.stringify(null==n?void 0:n.qa)}`);this.metadata=n;do null!==(n=this.Su())&&this.elements.push(n);while(null!==n)}getMetadata(){return this.metadata}Ku(){return this.elements}Su(){if(this.cursor===this.bundleData.length)return null;let e=this.ku();return new o_(JSON.parse(this.Qu(e)),e)}Qu(e){if(this.cursor+e>this.bundleData.length)throw new k(A.INTERNAL,"Reached the end of bundle when more is expected.");return this.bundleData.slice(this.cursor,this.cursor+=e)}ku(){let e=this.cursor,t=this.cursor;for(;t<this.bundleData.length;){if("{"===this.bundleData[t]){if(t===e)throw Error("First character is a bracket and not a number");return this.cursor=t,Number(this.bundleData.slice(e,t))}t++}throw Error("Reached the end of bundle when more is expected.")}}class lh{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new k(A.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let t=await async function(e,t){let n={documents:t.map(t=>iw(e.serializer,t))},r=await e.Jo("BatchGetDocuments",e.serializer.databaseId,J.emptyPath(),n,t.length),i=new Map;r.forEach(t=>{var n;let r=(n=e.serializer,"found"in t?function(e,t){C(!!t.found,43571),t.found.name,t.found.updateTime;let n=iv(e,t.found.name),r=im(t.found.updateTime),i=t.found.createTime?im(t.found.createTime):eh.min(),s=new nD({mapValue:{fields:t.found.fields}});return nC.newFoundDocument(n,r,i,s)}(n,t):"missing"in t?function(e,t){C(!!t.missing,3894),C(!!t.readTime,22933);let n=iv(e,t.missing),r=im(t.readTime);return nC.newNoDocument(n,r)}(n,t):x(7234,{result:t}));i.set(r.key.toString(),r)});let s=[];
9return t.forEach(e=>{let t=i.get(e.toString());C(!!t,55234,{key:e}),s.push(t)}),s}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new rj(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let e=this.readVersions;this.mutations.forEach(t=>{e.delete(t.key.toString())}),e.forEach((e,t)=>{let n=Z.fromPath(t);this.mutations.push(new rG(n,this.precondition(n)))}),await async function(e,t){let n={writes:t.map(t=>ix(e.serializer,t))};await e.Wo("Commit",e.serializer.databaseId,J.emptyPath(),n)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw x(50498,{Wu:e.constructor.name});t=eh.min()}let n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new k(A.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){let t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(eh.min())?rO.exists(!1):rO.updateTime(t):rO.none()}preconditionForUpdate(e){let t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(eh.min()))throw new k(A.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return rO.updateTime(t)}return rO.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class ld{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Gu=n.maxAttempts,this.F_=new aP(this.asyncQueue,"transaction_retry")}zu(){this.Gu-=1,this.ju()}ju(){this.F_.g_(async()=>{let e=new lh(this.datastore),t=this.Ju(e);t&&t.then(t=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(t)}).catch(e=>{this.Hu(e)}))}).catch(e=>{this.Hu(e)})})}Ju(e){try{let t=this.updateFunction(e);return!eB(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Hu(e){this.Gu>0&&this.Yu(e)?(this.Gu-=1,this.asyncQueue.enqueueAndForget(()=>(this.ju(),Promise.resolve()))):this.deferred.reject(e)}Yu(e){if("FirebaseError"===e.name){let t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!rY(t)}return!1}}let lf="FirestoreClient";class lm{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=y.UNAUTHENTICATED,this.clientId=$.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async e=>{_(lf,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(_(lf,"Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new R;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(n){let t=ou(n,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function lg(e,t){e.asyncQueue.verifyOperationInProgress(),_(lf,"Initializing OfflineComponentProvider");let n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await s8(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>{E("Terminating Firestore due to IndexedDb database deletion"),e.terminate().then(()=>{_("Terminating Firestore due to IndexedDb database deletion completed successfully")}).catch(e=>{E("Terminating Firestore due to IndexedDb database deletion failed",e)})}),e._offlineComponents=t}async function lp(e,t){e.asyncQueue.verifyOperationInProgress();let n=await ly(e);_(lf,"Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>oi(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>oi(t.remoteStore,n)),e._onlineComponents=t}async function ly(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){_(lf,"Using user provided OfflineComponentProvider");try{await lg(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===A.FAILED_PRECONDITION||t.code===A.UNIMPLEMENT
9ED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;E("Error using user provided cache. Falling back to memory cache: "+t),await lg(e,new ln)}}else _(lf,"Using default OfflineComponentProvider"),await lg(e,new lr(void 0));return e._offlineComponents}async function lw(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(_(lf,"Using user provided OnlineComponentProvider"),await lp(e,e._uninitializedComponentsProvider._online)):(_(lf,"Using default OnlineComponentProvider"),await lp(e,new la))),e._onlineComponents}function lv(e){return ly(e).then(e=>e.persistence)}function lb(e){return ly(e).then(e=>e.localStore)}function lI(e){return lw(e).then(e=>e.remoteStore)}function l_(e){return lw(e).then(e=>e.syncEngine)}function lT(e){return lw(e).then(e=>e.datastore)}async function lE(e){let t=await lw(e),n=t.eventManager;return n.onListen=oF.bind(null,t.syncEngine),n.onUnlisten=oM.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=oO.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=oL.bind(null,t.syncEngine),n}function lS(e,t,n={}){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new ll({next:o=>{s.Ou(),t.enqueueAndForget(()=>oy(e,a));let l=o.docs.has(n);!l&&o.fromCache?i.reject(new k(A.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&o.fromCache&&r&&"server"===r.source?i.reject(new k(A.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):i.resolve(o)},error:e=>i.reject(e)}),a=new oI(n6(n.path),s,{includeMetadataChanges:!0,ka:!0});return op(e,a)})(await lE(e),e.asyncQueue,t,n,r)),r.promise}function lx(e,t,n={}){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new ll({next:n=>{s.Ou(),t.enqueueAndForget(()=>oy(e,a)),n.fromCache&&"server"===r.source?i.reject(new k(A.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:e=>i.reject(e)}),a=new oI(n,s,{includeMetadataChanges:!0,ka:!0});return op(e,a)})(await lE(e),e.asyncQueue,t,n,r)),r.promise}function lD(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let lC=new Map,lN="firestore.googleapis.com";class lA{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new k(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=lN,this.ssl=!0}else this.host=e.host,this.ssl=null==(t=e.ssl)||t;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new k(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}et("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=lD(null!=(n=e.experimentalLongPollingOptions)?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new k(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new k(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new k(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var t,n;return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class lk{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new lA({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new k(A.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new k(A.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new lA(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new O;switch(e.type){case"firstParty":return new L(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new k(A.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
9d credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){let t=lC.get(e);t&&(_("ComponentProvider","Removing Datastore"),lC.delete(e),t.terminate())}(this),Promise.resolve()}}function lR(e,t,n,r={}){var i;e=ea(e,lk);let s=(0,c.zJ)(t),a=e._getSettings(),o=Object.assign(Object.assign({},a),{emulatorOptions:e._getEmulatorOptions()}),l=`${t}:${n}`;s&&((0,c.gE)(`https://${l}`),(0,c.P1)("Firestore",!0)),a.host!==lN&&a.host!==l&&E("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let u=Object.assign(Object.assign({},a),{host:l,ssl:s,emulatorOptions:r});if(!(0,c.bD)(u,o)&&(e._setSettings(u),r.mockUserToken)){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=y.MOCK_USER;else{t=(0,c.Fy)(r.mockUserToken,null==(i=e._app)?void 0:i.options.projectId);let s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new k(A.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new y(s)}e._authCredentials=new V(new F(t,n))}}class lF{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new lF(this.firestore,e,this._query)}}class lO{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new lV(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new lO(this.firestore,e,this._key)}toJSON(){return{type:lO._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,n){if(eu(t,lO._jsonSchema))return new lO(e,n||null,new Z(J.fromString(t.referencePath)))}}lO._jsonSchemaVersion="firestore/documentReference/1.0",lO._jsonSchema={type:el("string",lO._jsonSchemaVersion),referencePath:el("string")};class lV extends lF{constructor(e,t,n){super(e,t,n6(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new lO(this.firestore,null,new Z(e))}withConverter(e){return new lV(this.firestore,e,this._path)}}function lP(e,t,...n){if(e=(0,c.Ku)(e),ee("collection","path",t),e instanceof lk){let r=J.fromString(t,...n);return er(r),new lV(e,null,r)}{if(!(e instanceof lO||e instanceof lV))throw new k(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(J.fromString(t,...n));return er(r),new lV(e.firestore,null,r)}}function lM(e,t){if(e=ea(e,lk),ee("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new k(A.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new lF(e,null,new n5(J.emptyPath(),t))}function lL(e,t,...n){if(e=(0,c.Ku)(e),1==arguments.length&&(t=$.newId()),ee("doc","path",t),e instanceof lk){let r=J.fromString(t,...n);return en(r),new lO(e,null,new Z(r))}{if(!(e instanceof lO||e instanceof lV))throw new k(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(J.fromString(t,...n));return en(r),new lO(e.firestore,e instanceof lV?e.converter:null,new Z(r))}}function lq(e,t){return e=(0,c.Ku)(e),t=(0,c.Ku)(t),(e instanceof lO||e instanceof lV)&&(t instanceof lO||t instanceof lV)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function lU(e,t){return e=(0,c.Ku)(e),t=(0,c.Ku)(t),e instanceof lF&&t instanceof lF&&e.firestore===t.firestore&&rr(e._query,t._query)&&e.converter===t.converter}let lB="AsyncQueue";class lz{constructor(e=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new aP(this,"async_queue_retry"),this.oc=()=>{let e=aO();e&&_(lB,"Visibility state changed to "+e.visibilityState),this.F_.y_()},this._c=e;let t=aO();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ac(),this.uc(e)}enterRestrictedMode(e){if(!this.Xu){this.Xu=!0,this.rc=e||!1;let t=aO();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise(()=>{});let t=new R;return this.uc(()=>this.Xu&&this.rc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Zu.push(e),this.cc()))}async cc(){if(0!==this.Zu.length){try{await this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(e){if(!eR(e))throw e;_(lB,"Operation failed with retryable error: "+e)}this.Zu.length>0&&this.F_.g_(()=>this.cc())}}uc(e){let t=this._c.then(()=>(this.nc=!0,e().catch(e=>{throw this.tc=e,this.nc=!1,T("INTERNAL UNHANDLED ERROR: ",l$(e)),e}).then(e=>(this.nc=!1,e))));return this._c=t,t}enqueueAfterDelay(e,t,n){this.ac(),this.sc.indexOf(e)>-1&&(t=0);let r=ol.createAndSchedule(this,e,t,n,e=>this.lc(e));return this.ec.push(r),r}ac(){this.tc&&x(47125,{hc:l$(this.tc)})}verifyOperationInProgress(){}async Pc(){let e;do e=this._c,await e;while(e!==this._c)}Tc(e){for(let t of this.ec)if(t.timerId===e)return!0;return!1}Ic(e){return this.Pc().then(()=>{for(let t of(this.ec.sort((e,t)=>
9e.targetTimeMs-t.targetTimeMs),this.ec))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Pc()})}dc(e){this.sc.push(e)}lc(e){let t=this.ec.indexOf(e);this.ec.splice(t,1)}}function l$(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}function lK(e){if("object"!=typeof e||null===e)return!1;for(let t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}class lj{constructor(){this._progressObserver={},this._taskCompletionResolver=new R,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}let lG=-1;class lQ extends lk{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new lz,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new lz(e),this._firestoreClient=void 0,await e}}}function lW(e,t,n){n||(n=ne);let r=(0,o.j6)(e,"firestore");if(r.isInitialized(n)){let e=r.getImmediate({identifier:n}),i=r.getOptions(n);if((0,c.bD)(i,t))return e;throw new k(A.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&void 0!==t.localCache)throw new k(A.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new k(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return t.host&&(0,c.zJ)(t.host)&&(0,c.gE)(t.host),r.initialize({options:t,instanceIdentifier:n})}function lH(e,t){let n="object"==typeof e?e:(0,o.Sx)(),r="string"==typeof e?e:t||ne,i=(0,o.j6)(n,"firestore").getImmediate({identifier:r});if(!i._initialized){let e=(0,c.yU)("firestore");e&&lR(i,...e)}return i}function lJ(e){if(e._terminated)throw new k(A.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||lX(e),e._firestoreClient}function lX(e){var t,n,r,i,s;let a=e._freezeSettings(),o=(i=e._databaseId,s=(null==(t=e._app)?void 0:t.options.appId)||"",new t7(i,s,e._persistenceKey,a.host,a.ssl,a.experimentalForceLongPolling,a.experimentalAutoDetectLongPolling,lD(a.experimentalLongPollingOptions),a.useFetchStreams,a.isUsingEmulator));e._componentsProvider||(null==(n=a.localCache)?void 0:n._offlineComponentProvider)&&(null==(r=a.localCache)?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider}),e._firestoreClient=new lm(e._authCredentials,e._appCheckCredentials,e._queue,o,e._componentsProvider&&function(e){let t=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(t),_online:t}}(e._componentsProvider))}function lY(e,t){E("enableIndexedDbPersistence() will be deprecated 
9in the future, you can use `FirestoreSettings.cache` instead.");let n=e._freezeSettings();return l0(e,la.provider,{build:e=>new li(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()}async function lZ(e){E("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=e._freezeSettings();l0(e,la.provider,{build:e=>new ls(e,t.cacheSizeBytes)})}function l0(e,t,n){if((e=ea(e,lQ))._firestoreClient||e._terminated)throw new k(A.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new k(A.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:n},lX(e)}function l1(e){if(e._initialized&&!e._terminated)throw new k(A.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let t=new R;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!eC.C())return Promise.resolve();await eC.delete(e+sZ)}(s1(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}function l2(e){var t=lJ(e=ea(e,lQ));let n=new R;return t.asyncQueue.enqueueAndForget(async()=>oj(await l_(t),n)),n.promise}function l5(e){var t;return(t=lJ(e=ea(e,lQ))).asyncQueue.enqueue(async()=>{let e=await lv(t),n=await lI(t);return e.setNetworkEnabled(!0),n.Ia.delete(0),aG(n)})}function l6(e){var t;return(t=lJ(e=ea(e,lQ))).asyncQueue.enqueue(async()=>{let e=await lv(t),n=await lI(t);return e.setNetworkEnabled(!1),async function(e){e.Ia.add(0),await aQ(e),e.Aa.set("Offline")}(n)})}function l4(e){return(0,o.Us)(e.app,"firestore",e._databaseId.database),e._delete()}function l3(e,t){let n=lJ(e=ea(e,lQ)),r=new lj;return function(e,t,n,r){var i;let s=(i=aV(t),new lu(function(e,t){if(e instanceof Uint8Array)return lo(e,void 0);if(e instanceof ArrayBuffer)return lo(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}("string"==typeof n?z().encode(n):n),i));e.asyncQueue.enqueueAndForget(async()=>{var t;(async function(e,t,n){try{var r;let i=await t.getMetadata();if(await function(e,t){let n=im(t.createTime);return e.persistence.runTransaction("hasNewerBundle","readonly",n=>e.Ti.getBundleMetadata(n,t.id)).then(e=>!!e&&e.createTime.compareTo(n)>=0)}(e.localStore,i))return await t.close(),n._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);n._updateProgress(oS(i));let s=new oE(i,t.serializer),a=await t.Su();for(;a;){let e=await s.Wa(a);e&&n._updateProgress(e),a=await t.Su()}let o=await s.za(e.localStore);return await oY(e,o.Ja,void 0),await (r=e.localStore,r.persistence.runTransaction("Save bundle","readwrite",e=>r.Ti.saveBundleMetadata(e,i))),n._completeWith(o.progress),Promise.resolve(o.ja)}catch(e){return E(oN,`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(t=await l_(e),s,r).then(e=>{t.sharedClientState.notifyBundleLoaded(e)})})}(n,e._databaseId,t,r),r}function l8(e,t){var n;return(n=lJ(e=ea(e,lQ)),n.asyncQueue.enqueue(async()=>{var e;return e=await lb(n),e.persistence.runTransaction("Get named query","readonly",n=>e.Ti.getNamedQuery(n,t))})).then(t=>t?new lF(e,null,t.query):null)}class l9{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class l7{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class ue{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ue(tX.fromBase64String(e))}catch(e){throw new k(A.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new ue(tX.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:ue._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(eu(e,ue._jsonSchema))return ue.fromBase64String(e.bytes)}}
9ue._jsonSchemaVersion="firestore/bytes/1.0",ue._jsonSchema={type:el("string",ue._jsonSchemaVersion),bytes:el("string")};class ut{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new k(A.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Y(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}function un(){return new ut(W)}class ur{constructor(e){this._methodName=e}}class ui{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new k(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new k(A.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return K(this._lat,e._lat)||K(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:ui._jsonSchemaVersion}}static fromJSON(e){if(eu(e,ui._jsonSchema))return new ui(e.latitude,e.longitude)}}ui._jsonSchemaVersion="firestore/geoPoint/1.0",ui._jsonSchema={type:el("string",ui._jsonSchemaVersion),latitude:el("number"),longitude:el("number")};class us{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}toJSON(){return{type:us._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(eu(e,us._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new us(e.vectorValues);throw new k(A.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}us._jsonSchemaVersion="firestore/vectorValue/1.0",us._jsonSchema={type:el("string",us._jsonSchemaVersion),vectorValues:el("object")};let ua=/^__.*__$/;class uo{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new rB(e,this.data,this.fieldMask,t,this.fieldTransforms):new rU(e,this.data,t,this.fieldTransforms)}}class ul{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new rB(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function uu(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw x(40011,{Ec:e})}}class uc{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Ac(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new uc(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var t;let n=null==(t=this.path)?void 0:t.child(e),r=this.Rc({path:n,mc:!1});return r.fc(e),r}gc(e){var t;let n=null==(t=this.path)?void 0:t.child(e),r=this.Rc({path:n,mc:!1});return r.Ac(),r}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return uA(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(0===e.length)throw this.wc("Document fields must not be empty");if(uu(this.Ec)&&ua.test(e))throw this.wc('Document fields cannot begin and end with "__"')}}class uh{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||aV(e)}Dc(e,t,n,r=!1){return new uc({Ec:e,methodName:t,bc:n,path:Y.emptyPath(),mc:!1,Sc:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ud(e){let t=e._freezeSettings(),n=aV(e._databaseId);return new uh(e._databaseId,!!t.ignoreUndefinedProperties,n)}function uf(e,t,n,r,i,s={}){let a,o,l=e.Dc(s.merge||s.mergeFields?2:0,t,n,i);ux("Data must be an object, but it was:",l,r);let u=uE(r,l);if(s.merge)a=new tW(l.fieldMask),o=l.fieldTransforms;else if(s.mergeFields){let e=[];for(let r of s.mergeFields){let i=uD(t,r,n);if(!l.contains(i))throw new k(A.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);uk(e,i)||e.push(i)}a=new tW(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new uo(new nD(u),a,o)}class um extends ur{_toFieldTransform(e){if(2!==e.Ec)throw 1===e.Ec?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof um}}function ug(e,t,n){return new uc({Ec:3,bc:t.settings.bc,methodName:e._methodName,m
9c:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class up extends ur{_toFieldTransform(e){return new rR(e.path,new rE)}isEqual(e){return e instanceof up}}class uy extends ur{constructor(e,t){super(e),this.vc=t}_toFieldTransform(e){let t=ug(this,e,!0),n=new rS(this.vc.map(e=>uT(e,t)));return new rR(e.path,n)}isEqual(e){return e instanceof uy&&(0,c.bD)(this.vc,e.vc)}}class uw extends ur{constructor(e,t){super(e),this.vc=t}_toFieldTransform(e){let t=ug(this,e,!0),n=new rD(this.vc.map(e=>uT(e,t)));return new rR(e.path,n)}isEqual(e){return e instanceof uw&&(0,c.bD)(this.vc,e.vc)}}class uv extends ur{constructor(e,t){super(e),this.Cc=t}_toFieldTransform(e){let t=new rN(e.serializer,rI(e.serializer,this.Cc));return new rR(e.path,t)}isEqual(e){return e instanceof uv&&this.Cc===e.Cc}}function ub(e,t,n,r){let i=e.Dc(1,t,n);ux("Data must be an object, but it was:",i,r);let s=[],a=nD.empty();return tq(r,(e,r)=>{let o=uN(t,e,n);r=(0,c.Ku)(r);let l=i.gc(o);if(r instanceof um)s.push(o);else{let e=uT(r,l);null!=e&&(s.push(o),a.set(o,e))}}),new ul(a,new tW(s),i.fieldTransforms)}function uI(e,t,n,r,i,s){let a=e.Dc(1,t,n),o=[uD(t,r,n)],l=[i];if(s.length%2!=0)throw new k(A.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)o.push(uD(t,s[e])),l.push(s[e+1]);let u=[],h=nD.empty();for(let e=o.length-1;e>=0;--e)if(!uk(u,o[e])){let t=o[e],n=l[e];n=(0,c.Ku)(n);let r=a.gc(t);if(n instanceof um)u.push(t);else{let e=uT(n,r);null!=e&&(u.push(t),h.set(t,e))}}return new ul(h,new tW(u),a.fieldTransforms)}function u_(e,t,n,r=!1){return uT(n,e.Dc(r?4:3,t))}function uT(e,t){if(uS(e=(0,c.Ku)(e)))return ux("Unsupported field value:",t,e),uE(e,t);if(e instanceof ur)return function(e,t){if(!uu(t.Ec))throw t.wc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.wc(`${e._methodName}() is not currently supported inside arrays`);let n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.mc&&4!==t.Ec)throw t.wc("Nested arrays are not supported");let n=[],r=0;for(let i of e){let e=uT(i,t.yc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}return function(e,t){if(null===(e=(0,c.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return rI(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let n=ec.fromDate(e);return{timestampValue:ih(t.serializer,n)}}if(e instanceof ec){let n=new ec(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ih(t.serializer,n)}}if(e instanceof ui)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof ue)return{bytesValue:id(t.serializer,e._byteString)};if(e instanceof lO){let n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.wc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:ig(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof us)return{mapValue:{fields:{[nn]:{stringValue:ns},[na]:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw t.wc("VectorValues must only contain numeric values.");return rv(t.serializer,e)})}}}}};throw t.wc(`Unsupported field value: ${es(e)}`)}(e,t)}function uE(e,t){let n={};return tB(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):tq(e,(e,r)=>{let i=uT(r,t.Vc(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function uS(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ec||e instanceof ui||e instanceof ue||e instanceof lO||e instanceof ur||e instanceof us)}function ux(e,t,n){if(!uS(n)||!ei(n)){let r=es(n);throw"an object"===r?t.wc(e+" a custom object"):t.wc(e+" "+r)}}function uD(e,t,n){if((t=(0,c.Ku)(t))instanceof ut)return t._internalPath;if("string"==typeof t)return uN(e,t);throw uA("Field path arguments must be of type string or ",e,!1,void 0,n)}let uC=RegExp("[~\\*/\\[\\]]");
9function uN(e,t,n){if(t.search(uC)>=0)throw uA(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new ut(...t.split("."))._internalPath}catch(r){throw uA(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function uA(e,t,n,r,i){let s=r&&!r.isEmpty(),a=void 0!==i,o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${r}`),a&&(l+=` in document ${i}`),l+=")"),new k(A.INVALID_ARGUMENT,o+e+l)}function uk(e,t){return e.some(e=>e.isEqual(t))}class uR{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new lO(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new uF(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let t=this._document.data.field(uO("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class uF extends uR{data(){return super.data()}}function uO(e,t){return"string"==typeof t?uN(e,t):t instanceof ut?t._internalPath:t._delegate._internalPath}function uV(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new k(A.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class uP{}class uM extends uP{}function uL(e,t,...n){let r=[];for(let i of(t instanceof uP&&r.push(t),function(e){let t=e.filter(e=>e instanceof uB).length,n=e.filter(e=>e instanceof uq).length;if(t>1||t>0&&n>0)throw new k(A.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r=r.concat(n)),r))e=i._apply(e);return e}class uq extends uM{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new uq(e,t,n)}_apply(e){let t=this._parse(e);return u6(e._query,t),new lF(e.firestore,e.converter,rt(e._query,t))}_parse(e){let t=ud(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new k(A.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){u5(a,s);let t=[];for(let n of a)t.push(u2(r,e,n));o={arrayValue:{values:t}}}else o=u2(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||u5(a,s),o=u_(n,t,a,"in"===s||"not-in"===s);return nO.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function uU(e,t,n){let r=uO("where",e);return uq._create(r,t,n)}class uB extends uP{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new uB(e,t)}_parse(e){let t=this._queryConstraints.map(t=>t._parse(e)).filter(e=>e.getFilters().length>0);return 1===t.length?t[0]:nV.create(t,this._getOperator())}_apply(e){let t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(let e of t.getFlattenedFilters())u6(n,e),n=rt(n,e)}(e._query,t),new lF(e.firestore,e.converter,rt(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function uz(...e){return e.forEach(e=>u4("or",e)),uB._create("or",e)}function u$(...e){return e.forEach(e=>u4("and",e)),uB._create("and",e)}class uK extends uM{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new uK(e,t)}_apply(e){let t=function(e,t,n){if(null!==e.startAt)throw new k(A.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new k(A.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new nR(t,n)}(e._query,this._field,this._direction);return new lF(e.firestore,e.converter,function(e,t){let n=e.explicitOrderBy.concat([t]);return new n5(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}function uj(e,t="asc"){let n=uO("orderBy",e);return uK._create(n,t)}class uG extends uM{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new uG(e,t,n)}_apply(e){return new lF(e.firestore,e.converter,rn(e._query,this._limit,this._limitType))}}function uQ(e){return eo("limit",e),uG._create("limit",e,"F")}function uW(e){return eo("limitToLast",e),uG._create("limitToLast",e,"L")}class uH extends uM{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uH(e,t,n)}_apply(e){var t;let n=u1(e,this.type,this._docOrFields,this._inclusive);return new lF(e.firestore,e.converter,(t=e._query,new n5(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,n,t.endAt)))}}function uJ(...e){return uH._create("startAt",e,!0)}function uX(...e){return uH._create("startAfter",e,!1)}class uY extends uM{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uY(e,t,n)}_apply(e){var t;let n=u1(e,this.type,this._docOrFields,this._inclusive);return new lF(e.firestore,e.converter,(t=e._query,new n5(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,n)))}}function uZ(...e){return uY._create("endBefore",e,!1)}function u0(...e){return uY._create("endAt",e,!0)}function u1(e,t,n,r){if(n[0]=(0,c.Ku)(n[0]),n[0]instanceof uR)return function(e,t,n,r,i){if(!r)throw new k(A.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);let s=[];for(let n of n8(e))if(n.field.isKeyField())s.push(ng(t,r.key));else{let e=r.data.field(n.field);if(t3(e))throw new k(A.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){let e=n.field.canonicalString();throw new k(A.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new nN(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{let i=ud(e.firestore);return function(e,t,n,r,i,s){let a=e.explicitOrderBy;if(i.length>a.length)throw new k(A.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let o=[];for(let s=0;s<i.length;s++){let l=i[s];
9if(a[s].field.isKeyField()){if("string"!=typeof l)throw new k(A.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!n3(e)&&-1!==l.indexOf("/"))throw new k(A.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);let n=e.path.child(J.fromString(l));if(!Z.isDocumentKey(n))throw new k(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);let i=new Z(n);o.push(ng(t,i))}else{let e=u_(n,r,l);o.push(e)}}return new nN(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function u2(e,t,n){if("string"==typeof(n=(0,c.Ku)(n))){if(""===n)throw new k(A.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!n3(t)&&-1!==n.indexOf("/"))throw new k(A.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let r=t.path.child(J.fromString(n));if(!Z.isDocumentKey(r))throw new k(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return ng(e,new Z(r))}if(n instanceof lO)return ng(e,n._key);throw new k(A.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${es(n)}.`)}function u5(e,t){if(!Array.isArray(e)||0===e.length)throw new k(A.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function u6(e,t){let n=function(e,t){for(let n of e)for(let e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new k(A.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new k(A.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function u4(e,t){if(!(t instanceof uq||t instanceof uB))throw new k(A.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class u3{convertValue(e,t="none"){switch(nl(e)){case 0:return null;case 1:return e.booleanValue;case 2:return t0(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(t1(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw x(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return tq(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertVectorValue(e){var t,n,r;return new us(null==(r=null==(n=null==(t=e.fields)?void 0:t[na].arrayValue)?void 0:n.values)?void 0:r.map(e=>t0(e.doubleValue)))}convertGeoPoint(e){return new ui(t0(e.latitude),t0(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=t8(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(t9(e));default:return null}}convertTimestamp(e){let t=tZ(e);return new ec(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=J.fromString(e);C(iO(n),9688,{name:e});let r=new nt(n.get(1),n.get(3)),i=new Z(n.popFirst(5));return r.isEqual(t)||T(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function u8(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class u9 extends u3{constructor(e){super(),this.firestore=e}convertBytes(e){return new ue(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);
9return new lO(this.firestore,null,t)}}function u7(e){return new l9("sum",uD("sum",e))}function ce(e){return new l9("avg",uD("average",e))}function ct(){return new l9("count")}function cn(e,t){var n,r;return e instanceof l9&&t instanceof l9&&e.aggregateType===t.aggregateType&&(null==(n=e._internalFieldPath)?void 0:n.canonicalString())===(null==(r=t._internalFieldPath)?void 0:r.canonicalString())}function cr(e,t){return lU(e.query,t.query)&&(0,c.bD)(e.data(),t.data())}let ci="NOT SUPPORTED";class cs{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class ca extends uR{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new cl(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let n=this._document.data.field(uO("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new k(A.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,t={};return t.type=ca._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),e&&e.isValidDocument()&&e.isFoundDocument()&&(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),this._firestore,this.ref.path,t.bundle="NOT SUPPORTED"),t}}function co(e,t,n){if(eu(t,ca._jsonSchema)){var r;if(t.bundle===ci)throw new k(A.INVALID_ARGUMENT,"The provided JSON object was created in a client environment, which is not supported.");let i=aV(e._databaseId),s=(r=t.bundle,new lc(r,i)),a=s.Ku(),o=new oE(s.getMetadata(),i);for(let e of a)o.Wa(e);let l=o.documents;if(1!==l.length)throw new k(A.INVALID_ARGUMENT,`Expected bundle data to contain 1 document, but it contains ${l.length} documents.`);let u=iS(i,l[0].document),c=new Z(J.fromString(t.bundleName));return new ca(e,new u9(e),c,u,new cs(!1,!1),n||null)}}ca._jsonSchemaVersion="firestore/documentSnapshot/1.0",ca._jsonSchema={type:el("string",ca._jsonSchemaVersion),bundleSource:el("string","DocumentSnapshot"),bundleName:el("string"),bundle:el("string")};class cl extends ca{data(e={}){return super.data(e)}}class cu{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new cs(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){let e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach(n=>{e.call(t,new cl(this._firestore,this._userDataWriter,n.key,n,new cs(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new k(A.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map(n=>{let r=new cl(e._firestore,e._userDataWriter,n.doc.key,n.doc,new cs(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}})}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>t||3!==e.type).map(t=>{let r=new cl(e._firestore,e._userDataWriter,t.doc.key,t.doc,new cs(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(s=(n=n.add(t.doc)).indexOf(t.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return x(61501,{type:e})}}(t.type),doc:r,oldIndex:i,newIndex:s}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new k(A.FAILED_PRECONDITION,"QuerySnapsh
9ot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=cu._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=$.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let t=[],n=[],r=[];return this.docs.forEach(e=>{null!==e._document&&(t.push(e._document),n.push(this._userDataWriter.convertObjectMap(e._document.data.value.mapValue.fields,"previous")),r.push(e.ref.path))}),this._firestore,this.query._query,e.bundleName,e.bundle="NOT SUPPORTED",e}}function cc(e,t,n){if(eu(t,cu._jsonSchema)){var r;if(t.bundle===ci)throw new k(A.INVALID_ARGUMENT,"The provided JSON object was created in a client environment, which is not supported.");let i=aV(e._databaseId),s=(r=t.bundle,new lc(r,i)),a=s.Ku(),o=new oE(s.getMetadata(),i);for(let e of a)o.Wa(e);if(1!==o.queries.length)throw new k(A.INVALID_ARGUMENT,`Snapshot data expected 1 query but found ${o.queries.length} queries.`);let l=iK(o.queries[0].bundledQuery),u=o.documents,c=new oc;u.map(e=>{let t=iS(i,e.document);c=c.add(t)});let h=od.fromInitialDocuments(l,c,ry(),!1,!1),d=new lF(e,n||null,l);return new cu(e,new u9(e),d,h)}}function ch(e,t){return e instanceof ca&&t instanceof ca?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof cu&&t instanceof cu&&e._firestore===t._firestore&&lU(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function cd(e){e=ea(e,lO);let t=ea(e.firestore,lQ);return lS(lJ(t),e._key).then(n=>cD(t,e,n))}cu._jsonSchemaVersion="firestore/querySnapshot/1.0",cu._jsonSchema={type:el("string",cu._jsonSchemaVersion),bundleSource:el("string","QuerySnapshot"),bundleName:el("string"),bundle:el("string")};class cf extends u3{constructor(e){super(),this.firestore=e}convertBytes(e){return new ue(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new lO(this.firestore,null,t)}}function cm(e){e=ea(e,lO);let t=ea(e.firestore,lQ),n=lJ(t),r=new cf(t);return(function(e,t){let n=new R;return e.asyncQueue.enqueueAndForget(async()=>(async function(e,t,n){try{let r=await e.persistence.runTransaction("read document","readonly",n=>e.localDocuments.getDocument(n,t));r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new k(A.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(r){let e=ou(r,`Failed to get document '${t} from cache`);n.reject(e)}})(await lb(e),t,n)),n.promise})(n,e._key).then(n=>new ca(t,r,e._key,n,new cs(null!==n&&n.hasLocalMutations,!0),e.converter))}function cg(e){e=ea(e,lO);let t=ea(e.firestore,lQ);return lS(lJ(t),e._key,{source:"server"}).then(n=>cD(t,e,n))}function cp(e){e=ea(e,lF);let t=ea(e.firestore,lQ),n=lJ(t),r=new cf(t);return uV(e._query),lx(n,e._query).then(n=>new cu(t,r,e,n))}function cy(e){e=ea(e,lF);let t=ea(e.firestore,lQ),n=lJ(t),r=new cf(t);return(function(e,t){let n=new R;return e.asyncQueue.enqueueAndForget(async()=>(async function(e,t,n){try{let r=await an(e,t,!0),i=new oC(t,r.qs),s=i.nu(r.documents),a=i.applyChanges(s,!1);n.resolve(a.snapshot)}catch(r){let e=ou(r,`Failed to execute query '${t} against cache`);n.reject(e)}})(await lb(e),t,n)),n.promise})(n,e._query).then(n=>new cu(t,r,e,n))}function cw(e){e=ea(e,lF);let t=ea(e.firestore,lQ),n=lJ(t),r=new cf(t);return lx(n,e._query,{source:"server"}).then(n=>new cu(t,r,e,n))}function cv(e,t,n){e=ea(e,lO);let r=ea(e.firestore,lQ),i=u8(e.converter,t,n);return cx(r,[uf(ud(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,rO.none())])}function cb(e,t,n,...r){e=ea(e,lO);let i=ea(e.firestore,lQ),s=ud(i);return cx(i,[("string"==typeof(t=(0,c.Ku)(t))||t instanceof ut?uI(s,"updateDoc",e._key,t,n,r):ub(s,"updateDoc",e._key,t)).toMutation(e._key,rO.exists(!0))])}function cI(e){return cx(ea(e.firestore,lQ),[new rj(e._key,rO.none())])}function c_(e,t){let n=ea(e.firestore,lQ),r=lL(e),i=u8(e.converter,t);return cx(n,[uf(ud(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,rO.exists(!1))]).then(()=>r)}function cT(e,...t){let n,r,i;
9e=(0,c.Ku)(e);let s={includeMetadataChanges:!1,source:"default"},a=0;"object"!=typeof t[0]||lK(t[a])||(s=t[a++]);let o={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(lK(t[a])){let e=t[a];t[a]=null==(l=e.next)?void 0:l.bind(e),t[a+1]=null==(u=e.error)?void 0:u.bind(e),t[a+2]=null==(h=e.complete)?void 0:h.bind(e)}if(e instanceof lO)r=ea(e.firestore,lQ),i=n6(e._key.path),n={next:n=>{t[a]&&t[a](cD(r,e,n))},error:t[a+1],complete:t[a+2]};else{let s=ea(e,lF);r=ea(s.firestore,lQ),i=s._query;let o=new cf(r);n={next:e=>{t[a]&&t[a](new cu(r,o,s,e))},error:t[a+1],complete:t[a+2]},uV(e._query)}var l,u,h,d=lJ(r),f=i;let m=new ll(n),g=new oI(f,m,o);return d.asyncQueue.enqueueAndForget(async()=>op(await lE(d),g)),()=>{m.Ou(),d.asyncQueue.enqueueAndForget(async()=>oy(await lE(d),g))}}function cE(e,t,...n){var r,i,s,a,o,l;let u=(0,c.Ku)(e),h=function(e){let t={bundle:"",bundleName:"",bundleSource:""};for(let n of["bundle","bundleName","bundleSource"]){if(!(n in e)){t.error=`snapshotJson missing required field: ${n}`;break}let r=e[n];if("string"!=typeof r){t.error=`snapshotJson field '${n}' must be a string.`;break}if(0===r.length){t.error=`snapshotJson field '${n}' cannot be an empty string.`;break}"bundle"===n?t.bundle=r:"bundleName"===n?t.bundleName=r:"bundleSource"===n&&(t.bundleSource=r)}return t}(t);if(h.error)throw new k(A.INVALID_ARGUMENT,h.error);let d,f=0;if("object"!=typeof n[0]||lK(n[f])||(d=n[f++]),"QuerySnapshot"===h.bundleSource){let e,t,a=null;if("object"==typeof n[f]&&lK(n[f])){let e=n[f++];a={next:e.next,error:e.error,complete:e.complete}}else a={next:n[f++],error:n[f++],complete:n[f++]};return r=d,i=a,s=n[f],t=!1,l3(u,h.bundle).then(()=>l8(u,h.bundleName)).then(n=>{n&&!t&&(s&&n.withConverter(s),e=cT(n,r||{},i))}).catch(e=>(i.error&&i.error(e),()=>{})),()=>{t||(t=!0,e&&e())}}if("DocumentSnapshot"===h.bundleSource){let e,t,r=null;if("object"==typeof n[f]&&lK(n[f])){let e=n[f++];r={next:e.next,error:e.error,complete:e.complete}}else r={next:n[f++],error:n[f++],complete:n[f++]};return a=d,o=r,l=n[f],t=!1,l3(u,h.bundle).then(()=>{t||(e=cT(new lO(u,l||null,Z.fromPath(h.bundleName)),a||{},o))}).catch(e=>(o.error&&o.error(e),()=>{})),()=>{t||(t=!0,e&&e())}}throw new k(A.INVALID_ARGUMENT,`unsupported bundle source: ${h.bundleSource}`)}function cS(e,t){return function(e,t){let n=new ll(t);return e.asyncQueue.enqueueAndForget(async()=>{var t;return t=await lE(e),void(t.Da.add(n),n.next())}),()=>{n.Ou(),e.asyncQueue.enqueueAndForget(async()=>{var t;return t=await lE(e),void t.Da.delete(n)})}}(lJ(e=ea(e,lQ)),lK(t)?t:{next:t})}function cx(e,t){var n=lJ(e);let r=new R;return n.asyncQueue.enqueueAndForget(async()=>oq(await l_(n),t,r)),r.promise}function cD(e,t,n){let r=n.docs.get(t._key),i=new cf(e);return new ca(e,i,t._key,r,new cs(n.hasPendingWrites,n.fromCache),t.converter)}function cC(e){return cN(e,{count:ct()})}function cN(e,t){let n=ea(e.firestore,lQ),r=lJ(n),i=tU(t,(e,t)=>new rJ(t,e.aggregateType,e._internalFieldPath));return(function(e,t,n){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>{try{let i=await lT(e);r.resolve(async function(e,t,n){var r;let{request:i,ft:s,parent:a}=iA(e.serializer,n7(t),n);e.connection.Qo||delete i.parent;let o=(await e.Jo("RunAggregationQuery",e.serializer.databaseId,a,i,1)).filter(e=>!!e.result);C(1===o.length,64727);let l=null==(r=o[0].result)?void 0:r.aggregateFields;return Object.keys(l).reduce((e,t)=>(e[s[t]]=l[t],e),{})}(i,t,n))}catch(e){r.reject(e)}}),r.promise})(r,e._query,i).then(t=>new l7(e,new cf(n),t))}class cA{constructor(e){this.kind="memory",this._onlineComponentProvider=la.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new lr(void 0)}}toJSON(){return{kind:this.kind}}}class ck{constructor(e){let t;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),t=e.tabManager):(t=cU(void 0))._initialize(e),this._onlineComponentProvider=t._onlineComponentProvider,this._offlineComponentProvider=t._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class cR{constructor(){this.kind="memoryEager",this._offlineComponentProvider=ln.provider}toJSON(){return{kind:this.kind}}}class cF{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new lr(e)}}toJSON(){return{kind:this.kind}}}function cO(){return new cR}function cV(e){return new cF(null==e?void 0:e.cacheSizeBytes)}function cP(e){return new cA(e)}function cM(e){return new ck(e)}class cL{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=la.provider,this._offlineComponentProvider={build:t=>new li(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class cq{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=la.provider,this._offlineComponentProvider={build:t=>new ls(t,null==e?void 0:e.cacheSizeBytes)}}}function cU(e){return new cL(null==e?void 0:e.forceOwnership)}function cB(){return new cq}let cz={maxAttempts:5};class c${constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ud(e)}set(e,t,n){this._verifyNotCommitted();let r=cK(e,this._firestore),i=u8(r.converter,t,n),s=uf(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,rO.none())),this}update(e,t,n,...r){let i;this._verifyNotCommitted();let s=cK(e,this._firestore);return i="string"==typeof(t=(0,c.Ku)(t))||t instanceof ut?uI(this._dataReader,"WriteBatch.update",s._key,t,n,r):ub(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,rO.exists(!0))),this}delete(e){this._verifyNotCommitted();let t=cK(e,this._firestore);return this._mutations=this._mutations.concat(new rj(t._key,rO.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new k(A.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function cK(e,t){if((e=(0,c.Ku)(e)).firestore!==t)throw new k(A.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class cj{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=ud(e)}get(e){let t=cK(e,this._firestore),n=new u9(this._firestore);return this._transaction.lookup([t._key]).then(e=>{if(!e||1!==e.length)return x(24041);let r=e[0];
9if(r.isFoundDocument())return new uR(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new uR(this._firestore,n,t._key,null,t.converter);throw x(18433,{doc:r})})}set(e,t,n){let r=cK(e,this._firestore),i=u8(r.converter,t,n),s=uf(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){let i,s=cK(e,this._firestore);return i="string"==typeof(t=(0,c.Ku)(t))||t instanceof ut?uI(this._dataReader,"Transaction.update",s._key,t,n,r):ub(this._dataReader,"Transaction.update",s._key,t),this._transaction.update(s._key,i),this}delete(e){let t=cK(e,this._firestore);return this._transaction.delete(t._key),this}}class cG extends cj{constructor(e,t){super(e,t),this._firestore=e}get(e){let t=cK(e,this._firestore),n=new cf(this._firestore);return super.get(e).then(e=>new ca(this._firestore,n,t._key,e._document,new cs(!1,!1),t.converter))}}function cQ(e,t,n){e=ea(e,lQ);let r=Object.assign(Object.assign({},cz),n);if(r.maxAttempts<1)throw new k(A.INVALID_ARGUMENT,"Max attempts must be at least 1");return function(e,t,n){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>{let i=await lT(e);new ld(e.asyncQueue,i,n,t,r).zu()}),r.promise}(lJ(e),n=>t(new cG(e,n)),r)}function cW(){return new um("deleteField")}function cH(){return new up("serverTimestamp")}function cJ(...e){return new uy("arrayUnion",e)}function cX(...e){return new uw("arrayRemove",e)}function cY(e){return new uv("increment",e)}function cZ(e){return new us(e)}function c0(e){return lJ(e=ea(e,lQ)),new c$(e,t=>cx(e,t))}function c1(e,t){let n=lJ(e=ea(e,lQ));if(!n._uninitializedComponentsProvider||"memory"===n._uninitializedComponentsProvider._offline.kind)return E("Cannot enable indexes when persistence is disabled"),Promise.resolve();let r=function(e){let t="string"==typeof e?function(e){try{return JSON.parse(e)}catch(e){throw new k(A.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,n=[];if(Array.isArray(t.indexes))for(let e of t.indexes){let t=c2(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(let t of e.fields){let e=uN("setIndexConfiguration",c2(t,"fieldPath"));"CONTAINS"===t.arrayConfig?r.push(new ep(e,2)):"ASCENDING"===t.order?r.push(new ep(e,0)):"DESCENDING"===t.order&&r.push(new ep(e,1))}n.push(new ed(ed.UNKNOWN_ID,t,r,ey.empty()))}return n}(t);return n.asyncQueue.enqueue(async()=>(async function(e,t){let n=e.indexManager,r=[];return e.persistence.runTransaction("Configure indexes","readwrite",e=>n.getFieldIndexes(e).next(i=>(function(e,t,n,r,i){t=[...t],(e=[...e]).sort(n),t.sort(n);let s=e.length,a=t.length,o=0,l=0;for(;o<a&&l<s;){let s=n(e[l],t[o]);s<0?i(e[l++]):s>0?r(t[o++]):(o++,l++)}for(;o<a;)r(t[o++]);for(;l<s;)i(e[l++])})(i,t,eg,t=>{r.push(n.addFieldIndex(e,t))},t=>{r.push(n.deleteFieldIndex(e,t))})).next(()=>eS.waitFor(r)))})(await lb(n),r))}function c2(e,t){if("string"!=typeof e[t])throw new k(A.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}class c5{constructor(e){this._firestore=e,this.type="PersistentCacheIndexManager"}}function c6(e){var t;e=ea(e,lQ);let n=c7.get(e);if(n)return n;if("persistent"!==(null==(t=lJ(e)._uninitializedComponentsProvider)?void 0:t._offline.kind))return null;let r=new c5(e);return c7.set(e,r),r}function c4(e){c9(e,!0)}function c3(e){c9(e,!1)}function c8(e){var t;(t=lJ(e._firestore)).asyncQueue.enqueue(async()=>(function(e){let t=e.indexManager;return e.persistence.runTransaction("Delete All Indexes","readwrite",e=>t.deleteAllFieldIndexes(e))})(await lb(t))).then(e=>_("deleting all persistent cache indexes succeeded")).catch(e=>E("deleting all persistent cache indexes failed",e))}function c9(e,t){var n;(n=lJ(e._firestore),n.asyncQueue.enqueue(async()=>{var e;return e=await lb(n),void(e.Cs.Rs=t)})).then(e=>_(`setting persistent cache index auto creation isEnabled=${t} succeeded`)).catch(e=>E(`setting persistent cache index auto creation isEnabled=${t} failed`,e))}let c7=new WeakMap;function he(e){var t;let n=null==(t=lJ(ea(e.firestore,lQ))._onlineComponents)?void 0:t.datastore.serializer;return void 0===n?null:iN(n,n9(e._query)).Vt}function ht(e,t){var n;let r=tU(t,(e,t)=>new rJ(t,e.aggregateType,e._internalFieldPath)),i=null==(n=lJ(ea(e.firestore,lQ))._onlineComponents)?void 0:n.datastore.serializer;return void 0===i?null:iA(i,n7(e._query),r,!0).request}class hn{constructor(){throw Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return hr.instance.onExistenceFilterMismatch(e)}}class hr{constructor(){this.Fc=new Map}static get instance(){return hi||function(e){if(r0)throw Error("a TestingHooksSpi instance is already set");r0=e}(hi=new hr),hi}ct(e){this.Fc.forEach(t=>t(e))}onExistenceFilterMismatch(e){let t=Symbol(),n=this.Fc;return n.set(t,e),()=>n.delete(t)}}let hi=null;!function(e,t=!0){w=o.MF,(0,o.om)(new l.uA("firestore",(e,{instanceIdentifier:n,options:r})=>{let i=e.getProvider("app").getImmediate(),s=new lQ(new P(e.getProvider("auth-internal")),new U(i,e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new k(A.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new nt(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:t},r),s._setSettings(r),s},"PUBLIC").setMultipleInstances(!0)),(0,o.KO)(g,p,void 0),(0,o.KO)(g,p,"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.