PageSourceSearch

https://growithjane.com/_next/static/chunks/bc9e92e6-c5e7130199ffc9bb.js

js growithjane.com collected 2026-10-01 16:30:49 UTC 267,693 bytes, 9 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2992],{87015:(e,t,n)=>{n.d(t,{AB:()=>us,GG:()=>uI,H9:()=>lg,My:()=>ur,P:()=>l9,_M:()=>ue,aU:()=>lT,gS:()=>uE,kd:()=>uT,mZ:()=>ub,rJ:()=>lm});var r,i,s,a,o=n(42612),l=n(56391),u=n(10796),h=n(49887),c=n(2107),d=n(80927),f=n(87358),m=n(49641).Buffer;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 I(){return v.logLevel}function b(e,...t){if(v.logLevel<=u.$b.DEBUG){let n=t.map(_);v.debug(`Firestore (${w}): ${e}`,...n)}}function T(e,...t){if(v.logLevel<=u.$b.ERROR){let n=t.map(_);v.error(`Firestore (${w}): ${e}`,...n)}}function E(e,...t){if(v.logLevel<=u.$b.WARN){let n=t.map(_);v.warn(`Firestore (${w}): ${e}`,...n)}}function _(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function S(e,t,n){let r="Unexpected state";"string"==typeof t?r=t:n=t,x(e,r,n)}function x(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 D(e,t,n,r){let i="Unexpected state";"string"==typeof n?i=n:r=n,e||x(t,i,r)}let N={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 C extends h.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class k{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class A{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class V{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(y.UNAUTHENTICATED))}shutdown(){}}class R{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class O{constructor(e){this.t=e,this.currentUser=y.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){D(void 0===this.o,42304);let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),i=new k;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new k,e.enqueueRetryable(()=>r(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},a=e=>{b("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):(b("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new k)}},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?(b("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(D("string"==typeof t.accessToken,31837,{l:t}),new A(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 D(null===e||"string"==typeof e,2055,{h:e}),new y(e)}}class F{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 P{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new F(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(y.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class M{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 L{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){D(void 0===this.o,3512);let n=e=>{null!=e.error&&b("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,b("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>{b("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):b("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new M(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>
1e?(D("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new M(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function U(){return new TextEncoder}class q{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;e++)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 B(e,t){return e<t?-1:+(e>t)}function z(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 B(r,i);{let s=U(),a=function(e,t){for(let n=0;n<e.length&&n<t.length;++n)if(e[n]!==t[n])return B(e[n],t[n]);return B(e.length,t.length)}(s.encode($(e,n)),s.encode($(t,n)));return 0!==a?a:B(r,i)}}n+=r>65535?2:1}return B(e.length,t.length)}function $(e,t){return e.codePointAt(t)>65535?e.substring(t,t+2):e.substring(t,t+1)}function K(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}let j="__name__";class G{constructor(e,t,n){void 0===t?t=0:t>e.length&&S(637,{offset:t,range:e.length}),void 0===n?n=e.length-t:n>e.length-t&&S(1746,{length:n,range:e.length-t}),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===G.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof G?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=G.compareSegments(e.get(r),t.get(r));if(0!==n)return n}return B(e.length,t.length)}static compareSegments(e,t){let n=G.isNumericId(e),r=G.isNumericId(t);return n&&!r?-1:!n&&r?1:n&&r?G.extractNumericId(e).compare(G.extractNumericId(t)):z(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return c.jz.fromString(e.substring(4,e.length-2))}}class Q extends G{construct(e,t,n){return new Q(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 C(N.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new Q(t)}static emptyPath(){return new Q([])}}let W=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class H extends G{construct(e,t,n){return new H(e,t,n)}static isValidIdentifier(e){return W.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),H.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===j}static keyField(){return new H([j])}static fromServerFormat(e){let t=[],n="",r=0,i=()=>{if(0===n.length)throw new C(N.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 C(N.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new C(N.INVALID_ARGUMENT,"Path has invali
1d escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new C(N.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new H(t)}static emptyPath(){return new H([])}}class X{constructor(e){this.path=e}static fromPath(e){return new X(Q.fromString(e))}static fromName(e){return new X(Q.fromString(e).popFirst(5))}static empty(){return new X(Q.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===Q.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Q.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new X(new Q(e.slice()))}}function Y(e,t,n){if(!n)throw new C(N.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function J(e){if(!X.isDocumentKey(e))throw new C(N.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Z(e){if(X.isDocumentKey(e))throw new C(N.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function ee(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function et(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var t;let n=(t=e).constructor?t.constructor.name:null;return n?`a custom ${n} object`:"an object"}}return"function"==typeof e?"a function":S(12329,{type:typeof e})}function en(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new C(N.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=et(e);throw new C(N.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function er(e,t){let n={typeString:e};return t&&(n.value=t),n}function ei(e,t){let n;if(!ee(e))throw new C(N.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 C(N.INVALID_ARGUMENT,n);return!0}class es{static now(){return es.fromMillis(Date.now())}static fromDate(e){return es.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*1e6);return new es(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new C(N.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new C(N.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?B(this.nanoseconds,e.nanoseconds):B(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:es._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(ei(e,es._jsonSchema))return new es(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}es._jsonSchemaVersion="firestore/timestamp/1.0",es._jsonSchema={type:er("string",es._jsonSchemaVersion),seconds:er("number"),nanoseconds:er("number")};class ea{static fromTimestamp(e){return new ea(e)}static min(){return new ea(new es(0,0))}static max(){return new ea(new es(0x3afff4417f,0x3b9ac9ff))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class eo{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function el(e){return e.fields.find(e=>2===e.kind)}function eu(e){return e.fields.filter(e=>2!==e.kind)}eo.UNKNOWN_ID=-1;class eh{constructor(e,t){this.fieldPath=e,this.kind=t}}class ec{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new ec(0,em.min())}}function ed(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;
1return new em(ea.fromTimestamp(1e9===r?new es(n+1,0):new es(n,r)),X.empty(),t)}function ef(e){return new em(e.readTime,e.key,-1)}class em{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new em(ea.min(),X.empty(),-1)}static max(){return new em(ea.max(),X.empty(),-1)}}function eg(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:0!==(n=X.comparator(e.documentKey,t.documentKey))?n:B(e.largestBatchId,t.largestBatchId)}let ep="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ey{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function ew(e){if(e.code!==N.FAILED_PRECONDITION||e.message!==ep)throw e;b("LocalStore","Unexpectedly lost primary lease")}class ev{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&S(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new ev((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 ev?t:ev.resolve(t)}catch(e){return ev.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):ev.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):ev.reject(t)}static resolve(e){return new ev((t,n)=>{t(e)})}static reject(e){return new ev((t,n)=>{n(e)})}static waitFor(e){return new ev((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=ev.resolve(!1);for(let n of e)t=t.next(e=>e?ev.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 ev((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 ev((n,r)=>{let i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}let eI="SimpleDb";class eb{static open(e,t,n,r){try{return new eb(t,e.transaction(r,n))}catch(e){throw new eS(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.S=new k,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{t.error?this.S.reject(new eS(e,t.error)):this.S.resolve()},this.transaction.onerror=t=>{let n=ek(t.target.error);this.S.reject(new eS(e,n))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(b(eI,"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 eD(this.transaction.objectStore(e))}}class eT{static delete(e){return b(eI,"Removing database:",e),eN((0,h.mS)().indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!(0,h.zW)())return!1;if(eT.F())return!0;let e=(0,h.ZQ)(),t=eT.M(e),n=eE(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?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===eT.M((0,h.ZQ)())&&T("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async k(e){return this.db||(b(eI,"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 eS(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 C(N.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 C(N.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 eS(e,r))},r.onupgradeneeded=e=>{b(eI,'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(()=>{b(eI,"Database upgrade to version "+this.version+" complete")}
1)}}),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)||void 0===t||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=eb.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.v(),e)).catch(e=>(t.abort(e),ev.reject(e))).toPromise();return s.catch(()=>{}),await t.D,s}catch(t){let e="FirebaseError"!==t.name&&s<3;if(b(eI,"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 eE(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class e_{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 eN(this.$.delete())}}class eS extends C{constructor(e,t){super(N.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function ex(e){return"IndexedDbTransactionError"===e.name}class eD{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(b(eI,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(b(eI,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),eN(n)}add(e){return b(eI,"ADD",this.store.name,e,e),eN(this.store.add(e))}get(e){return eN(this.store.get(e)).next(t=>(void 0===t&&(t=null),b(eI,"GET",this.store.name,e,t),t))}delete(e){return b(eI,"DELETE",this.store.name,e),eN(this.store.delete(e))}count(){return b(eI,"COUNT",this.store.name),eN(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 ev((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 ev((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}Y(e,t){b(eI,"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 ev((n,r)=>{t.onerror=e=>{r(ek(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 ev((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 e_(i),a=t(i.primaryKey,i.value,s);if(a instanceof ev){let e=a.catch(e=>(s.done(),ev.reject(e)));n.push(e)}s.isDone?r():null===s.W?i.continue():i.continue(s.W)}}).next(()=>ev.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 eN(e){return new ev((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{n(ek(e.target.error))}})}let eC=!1;function ek(e){let t=eT.M((0,h.ZQ)());if(t>=12.2&&t<13){let t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){let e=new C("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 eC||(eC=!0,setTimeout(()=>{throw e},0)),e}}return e}let eA="IndexBackfiller";class eV{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){b(eA,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let e=await this.te.re();b(eA,`Documents written: ${e}`)}catch(e){ex(e)?b(eA,"Ignoring IndexedDB error during index backfill: ",e):await ew(e)}await this.ne(6e4)})}}class eR{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;return ev.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>
1{if(null!==t&&!n.has(t))return b(eA,`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=>(b(eA,`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=ef(t);eg(r,n)>0&&(n=r)}),new em(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class eO{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 eF(e){return null==e}function eP(e){return 0===e&&1/e==-1/0}function eM(e){return"number"==typeof e&&Number.isInteger(e)&&!eP(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function eL(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"}eO.ue=-1;function eU(e){let t=e.length;if(D(t>=2,64408,{path:e}),2===t)return D("\x01"===e.charAt(0)&&"\x01"===e.charAt(1),56145,{path:e}),Q.emptyPath();let n=t-2,r=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>n)&&S(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:S(61167,{path:e})}s=t+2}return new Q(r)}let eq="remoteDocuments",eB="owner",ez="owner",e$="mutationQueues",eK="mutations",ej="batchId",eG="userMutationsIndex",eQ=["userId","batchId"],eW={},eH="documentMutations",eX="remoteDocumentsV14",eY=["prefixPath","collectionGroup","readTime","documentId"],eJ="documentKeyIndex",eZ=["prefixPath","collectionGroup","documentId"],e0="collectionGroupIndex",e1=["collectionGroup","readTime","prefixPath","documentId"],e2="remoteDocumentGlobal",e5="remoteDocumentGlobalKey",e4="targets",e3="queryTargetsIndex",e6=["canonicalId","targetId"],e8="targetDocuments",e9=["targetId","path"],e7="documentTargetsIndex",te=["path","targetId"],tt="targetGlobalKey",tn="targetGlobal",tr="collectionParents",ti=["collectionId","parent"],ts="clientMetadata",ta="bundles",to="namedQueries",tl="indexConfiguration",tu="collectionGroupIndex",th="indexState",tc=["indexId","uid"],td="sequenceNumberIndex",tf=["uid","sequenceNumber"],tm="indexEntries",tg=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],tp="documentKeyIndex",ty=["indexId","uid","orderedDocumentKey"],tw="documentOverlays",tv=["userId","collectionPath","documentId"],tI="collectionPathOverlayIndex",tb=["userId","collectionPath","largestBatchId"],tT="collectionGroupOverlayIndex",tE=["userId","collectionGroup","largestBatchId"],t_="globals",tS=[e$,eK,eH,eq,e4,eB,tn,e8,ts,e2,tr,ta,to],tx=[...tS,tw],tD=[e$,eK,eH,eX,e4,eB,tn,e8,ts,e2,tr,ta,to,tw],tN=[...tD,tl,th,tm],tC=[...tN,t_];class tk extends ey{constructor(e,t){super(),this.ce=e,this.currentSequenceNumber=t}}function tA(e,t){return eT.N(e.ce,t)}function tV(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tR(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function tO(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class tF{constructor(e,t){this.comparator=e,this.root=t||tM.EMPTY}insert(e,t){return new tF(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,tM.BLACK,null,null))}remove(e){return new tF(this.comparator,this.root.remove(e,this.comparator).copy(null,null,tM.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();
1){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 tP(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new tP(this.root,e,this.comparator,!1)}getReverseIterator(){return new tP(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new tP(this.root,e,this.comparator,!0)}}class tP{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 tM{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:tM.RED,this.left=null!=r?r:tM.EMPTY,this.right=null!=i?i:tM.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new tM(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 tM.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 tM.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,tM.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,tM.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw S(43730,{key:this.key,value:this.value});if(this.right.isRed())throw S(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw S(27949);return e+ +!this.isRed()}}
1tM.EMPTY=null,tM.RED=!0,tM.BLACK=!1,tM.EMPTY=new class{constructor(){this.size=0}get key(){throw S(57766)}get value(){throw S(16141)}get color(){throw S(16727)}get left(){throw S(29726)}get right(){throw S(36894)}copy(e,t,n,r,i){return this}insert(e,t,n){return new tM(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 tL{constructor(e){this.comparator=e,this.data=new tF(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 tU(this.data.getIterator())}getIteratorFrom(e){return new tU(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 tL)||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 tL(this.comparator);return t.data=e,t}}class tU{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 tB{constructor(e){this.fields=e,e.sort(H.comparator)}static empty(){return new tB([])}unionWith(e){let t=new tL(H.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new tB(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return K(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class tz extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class t${constructor(e){this.binaryString=e}static fromBase64String(e){return new t$(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new tz("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new t$(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 B(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}t$.EMPTY_BYTE_STRING=new t$("");let tK=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function tj(e){if(D(!!e,39018),"string"==typeof e){let t=0,n=tK.exec(e);if(D(!!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:tG(e.seconds),nanos:tG(e.nanos)}}function tG(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function tQ(e){return"string"==typeof e?t$.fromBase64String(e):t$.fromUint8Array(e)}let tW="server_timestamp",tH="__type__",tX="__previous_value__",tY="__local_write_time__";function tJ(e){var t,n;return(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{})[tH])||void 0===n?void 0:n.stringValue)===tW}function tZ(e){let t=e.mapValue.fields[tX];return tJ(t)?tZ(t):t}function t0(e){let t=tj(e.mapValue.fields[tY].timestampValue);return new es(t.seconds,t.nanos)}class t1{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}}
1let t2="(default)";class t5{constructor(e,t){this.projectId=e,this.database=t||t2}static empty(){return new t5("","")}get isDefaultDatabase(){return this.database===t2}isEqual(e){return e instanceof t5&&e.projectId===this.projectId&&e.database===this.database}}let t4="__type__",t3="__max__",t6={mapValue:{fields:{__type__:{stringValue:t3}}}},t8="__vector__",t9="value",t7={nullValue:"NULL_VALUE"};function ne(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?tJ(e)?4:ng(e)?0x1fffffffffffff:nf(e)?10:11:S(28295,{value:e})}function nt(e,t){if(e===t)return!0;let n=ne(e);if(n!==ne(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return t0(e).isEqual(t0(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=tj(e.timestampValue),i=tj(t.timestampValue);return r.seconds===i.seconds&&r.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return tQ(e.bytesValue).isEqual(tQ(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return tG(e.geoPointValue.latitude)===tG(t.geoPointValue.latitude)&&tG(e.geoPointValue.longitude)===tG(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return tG(e.integerValue)===tG(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=tG(e.doubleValue),r=tG(t.doubleValue);return n===r?eP(n)===eP(r):isNaN(n)&&isNaN(r)}return!1;case 9:return K(e.arrayValue.values||[],t.arrayValue.values||[],nt);case 10:case 11:let s=e.mapValue.fields||{},a=t.mapValue.fields||{};if(tV(s)!==tV(a))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===a[e]||!nt(s[e],a[e])))return!1;return!0;default:return S(52216,{left:e})}}function nn(e,t){return void 0!==(e.values||[]).find(e=>nt(e,t))}function nr(e,t){if(e===t)return 0;let n=ne(e),r=ne(t);if(n!==r)return B(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return B(e.booleanValue,t.booleanValue);case 2:let i=tG(e.integerValue||e.doubleValue),s=tG(t.integerValue||t.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return ni(e.timestampValue,t.timestampValue);case 4:return ni(t0(e),t0(t));case 5:return z(e.stringValue,t.stringValue);case 6:return function(e,t){let n=tQ(e),r=tQ(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=B(n[e],r[e]);if(0!==t)return t}return B(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let n=B(tG(e.latitude),tG(t.latitude));return 0!==n?n:B(tG(e.longitude),tG(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return ns(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[t9])||void 0===n?void 0:n.arrayValue,u=null===(r=o[t9])||void 0===r?void 0:r.arrayValue,h=B((null===(i=null==l?void 0:l.values)||void 0===i?void 0:i.length)||0,(null===(s=null==u?void 0:u.values)||void 0===s?void 0:s.length)||0);return 0!==h?h:ns(l,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===t6.mapValue&&t===t6.mapValue)return 0;if(e===t6.mapValue)return 1;if(t===t6.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=z(r[e],s[e]);if(0!==t)return t;let a=nr(n[r[e]],i[s[e]]);if(0!==a)return a}return B(r.length,s.length)}(e.mapValue,t.mapValue);default:throw S(23264,{le:n})}}function ni(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return B(e,t);let n=tj(e),r=tj(t),i=B(n.seconds,r.seconds);return 0!==i?i:B(n.nanos,r.nanos)}function ns(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=nr(n[e],r[e]);if(t)return t}return B(n.length,r.length)}function na(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=tj(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?tQ(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,X.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+=na(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}:${na(e.fields[i])}`;return n+"}"}(e.mapValue):S(61005,{value:e})}function no(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function nl(e){return!!e&&"integerValue"in e}function nu(e){return!!e&&"arrayValue"in e}function nh(e){return!!e&&"nullValue"in e}function nc(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}
1function nd(e){return!!e&&"mapValue"in e}function nf(e){var t,n;return(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{})[t4])||void 0===n?void 0:n.stringValue)===t8}function nm(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 tR(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=nm(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=nm(e.arrayValue.values[n]);return t}return Object.assign({},e)}function ng(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===t3}let np={mapValue:{fields:{[t4]:{stringValue:t8},[t9]:{arrayValue:{}}}}};function ny(e,t){let n=nr(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function nw(e,t){let n=nr(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class nv{constructor(e){this.value=e}static empty(){return new nv({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!nd(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()]=nm(t)}setAll(e){let t=H.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()]=nm(e):r.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){let t=this.field(e.popLast());nd(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return nt(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)];nd(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(tR(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new nv(nm(this.value))}}class nI{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 nI(e,0,ea.min(),ea.min(),ea.min(),nv.empty(),0)}static newFoundDocument(e,t,n,r){return new nI(e,1,t,ea.min(),n,r,0)}static newNoDocument(e,t){return new nI(e,2,t,ea.min(),ea.min(),nv.empty(),0)}static newUnknownDocument(e,t){return new nI(e,3,t,ea.min(),ea.min(),nv.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(ea.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=nv.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=nv.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ea.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 nI&&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 nI(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 nb{constructor(e,t){this.position=e,this.inclusive=t}}function nT(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()?X.comparator(X.fromName(a.referenceValue),n.key):nr(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function nE(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(!nt(e.position[n],t.position[n]))return!1;return!0}class n_{constructor(e,t="asc"){this.field=e,this.dir=t}}class nS{}class nx extends nS{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 nR(e,t,n):"array-contains"===t?new nM(e,n):"in"===t?new nL(e,n):"not-in"===t?new nU(e,n):"array-contains-any"===t?new nq(e,n):new nx(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new nO(e,n):new nF(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(nr(t,this.value)):null!==t&&ne(this.value)===ne(t)&&this.matchesComparison(nr(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return S(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class nD extends nS{constructor(e,t){super(),this.filters=e,this.op=t,this.he=null}static create(e,t){return new nD(e,t)}matches(e){return nN(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 nN(e){return"and"===e.op}function nC(e){return"or"===e.op}function nk(e){return nA(e)&&nN(e)}function nA(e){for(let t of e.filters)if(t instanceof nD)return!1;return!0}function nV(e,t){let n=e.filters.concat(t);return nD.create(n,e.op)}class nR extends nx{constructor(e,t,n){super(e,t,n),this.key=X.fromName(n.referenceValue)}matches(e){let t=X.comparator(e.key,this.key);return this.matchesComparison(t)}}class nO extends nx{constructor(e,t){super(e,"in",t),this.keys=nP("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class nF extends nx{constructor(e,t){super(e,"not-in",t),this.keys=nP("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function nP(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>X.fromName(e.referenceValue))}class nM extends nx{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return nu(t)&&nn(t.arrayValue,this.value)}}class nL extends nx{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&nn(this.value.arrayValue,t)}}class nU extends nx{constructor(e,t){super(e,"not-in",t)}matches(e){if(nn(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!nn(this.value.arrayValue,t)}}class nq extends nx{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!nu(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>nn(this.value.arrayValue,e))}}class nB{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 nz(e,t=null,n=[],r=[],i=null,s=null,a=null){return new nB(e,t,n,r,i,s,a)}function n$(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 nx)return t.field.canonicalString()+t.op.toString()+na(t.value);if(nk(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(","),eF(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>na(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>na(e)).join(",")),e.Pe=t}return e.Pe}function nK(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 nx?n instanceof nx&&t.op===n.op&&t.field.isEqual(n.field)&&nt(t.value,n.value):t instanceof nD?n instanceof nD&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,i)=>t&&e(r,n.filters[i]),!0):void S(19439)}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!nE(e.startAt,t.startAt)&&nE(e.endAt,t.endAt)}function nj(e){return X.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function nG(e,t){return e.filters.filter(e=>e instanceof nx&&e.field.isEqual(t))}
1function nQ(e,t,n){let r=t7,i=!0;for(let n of nG(e,t)){let e=t7,t=!0;switch(n.op){case"<":case"<=":var s;e="nullValue"in(s=n.value)?t7:"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?no(t5.empty(),X.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?nf(s)?np:{mapValue:{}}:S(35942,{value:s});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=t7}0>ny({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>ny({value:r,inclusive:i},{value:e,inclusive:n.inclusive})&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}function nW(e,t,n){let r=t6,i=!0;for(let n of nG(e,t)){let e=t6,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?no(t5.empty(),X.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?np:"mapValue"in s?nf(s)?{mapValue:{}}:t6:S(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=t6}nw({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];nw({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}class nH{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 nX(e){return new nH(e)}function nY(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 nJ(e){return null!==e.collectionGroup}function nZ(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 tL(H.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 n_(t,r))}),n.has(H.keyField().canonicalString())||e.Te.push(new n_(H.keyField(),r))}return e.Te}function n0(e){return e.Ie||(e.Ie=n1(e,nZ(e))),e.Ie}function n1(e,t){if("F"===e.limitType)return nz(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 n_(e.field,t)});let n=e.endAt?new nb(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new nb(e.startAt.position,e.startAt.inclusive):null;return nz(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function n2(e,t){let n=e.filters.concat([t]);return new nH(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function n5(e,t,n){return new nH(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function n4(e,t){return nK(n0(e),n0(t))&&e.limitType===t.limitType}function n3(e){return`${n$(n0(e))}|lt:${e.limitType}`}function n6(e){var t;let n;return`Query(target=${n=(t=n0(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 nx?`${t.field.canonicalString()} ${t.op} ${na(t.value)}`:t instanceof nD?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),eF(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=>na(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>na(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function n8(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):X.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(let n of nZ(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=nT(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,nZ(e),t))&&(!e.endAt||!!function(e,t,n){let r=nT(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,nZ(e),t))}function n9(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function n7(e){return(t,n)=>{let r=!1;for(let i of nZ(e)){let e=function(e,t,n){let r=e.field.isKeyField()?X.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?nr(r,i):S(42886)}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return S(19790,{direction:e.dir})}}(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}class re{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){tR(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){return tO(this.inner)}size(){return this.innerSize}}let rt=new tF(X.comparator),rn=new tF(X.comparator);function rr(...e){let t=rn;for(let n of e)t=t.insert(n.key,n);return t}function ri(e){let t=rn;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function rs(){return new re(e=>e.toString(),(e,t)=>e.isEqual(t))}let ra=new tF(X.comparator),ro=new tL(X.comparator);function rl(...e){let t=ro;for(let n of e)t=t.add(n);return t}let ru=new tL(B);function rh(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:eP(t)?"-0":t}}function rc(e){return{integerValue:""+e}}function rd(e,t){return eM(t)?rc(t):rh(e,t)}class rf{constructor(){this._=void 0}}function rm(e,t){return e instanceof rI?nl(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}class rg extends rf{}class rp extends rf{constructor(e){super(),this.elements=e}}function ry(e,t){let n=rT(t);for(let t of e.elements)n.some(e=>nt(e,t))||n.push(t);return{arrayValue:{values:n}}}class rw extends rf{constructor(e){super(),this.elements=e}}function rv(e,t){let n=rT(t);for(let t of e.elements)n=n.filter(e=>!nt(e,t));return{arrayValue:{values:n}}}class rI extends rf{constructor(e,t){super(),this.serializer=e,this.Ee=t}}function rb(e){return tG(e.integerValue||e.doubleValue)}function rT(e){return nu(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class rE{constructor(e,t){this.field=e,this.transform=t}}class r_{constructor(e,t){this.version=e,this.transformResults=t}}class rS{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new rS}static exists(e){return new rS(void 0,e)}static updateTime(e){return new rS(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 rx(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class rD{}function rN(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new rP(e.key,rS.none()):new rA(e.key,e.data,rS.none());{let n=e.data,r=nv.empty(),i=new tL(H.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 rV(e.key,r,new tB(i.toArray()),rS.none())}}function rC(e,t,n,r){return e instanceof rA?function(e,t,n,r){if(!rx(e.precondition,t))return n;let i=e.value.clone(),s=rF(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof rV?function(e,t,n,r){if(!rx(e.precondition,t))return n;let i=rF(e.fieldTransforms,r,t),s=t.data;return(s.setAll(rR(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):rx(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function rk(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)&&K(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof rp&&r instanceof rp||n instanceof rw&&r instanceof rw?K(n.elements,r.elements,nt):n instanceof rI&&r instanceof rI?nt(n.Ee,r.Ee):n instanceof rg&&r instanceof rg)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class rA extends rD{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 rV extends rD{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 rR(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 rO(e,t,n){let r=new Map;D(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 rp?ry(o,l):o instanceof rw?rv(o,l):i))}return r}function rF(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 rg?function(e,t){let n={fields:{[tH]:{stringValue:tW},[tY]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&tJ(t)&&(t=tZ(t)),t&&(n.fields[tX]=t),{mapValue:n}}(t,s):e instanceof rp?ry(e,s):e instanceof rw?rv(e,s):function(e,t){let n=rm(e,t),r=rb(n)+rb(e.Ee);return nl(n)&&nl(e.Ee)?rc(r):rh(e.serializer,r)}(e,s))}return r}class rP extends rD{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rM extends rD{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class rL{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let i=this.mutations[t];if(i.key.isEqual(e.key)){var r;r=n[t],i instanceof rA?function(e,t,n){let r=e.value.clone(),i=rO(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(i,e,r):i instanceof rV?function(e,t,n){if(!rx(e.precondition,t))return t.convertToUnknownDocument(n.version);let r=rO(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(rR(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(i,e,r):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,e,r)}}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=rC(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=rC(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=rs();return this.mutations.forEach(r=>{let i=e.get(r.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=rN(s,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(ea.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),rl())}isEqual(e){return this.batchId===e.batchId&&K(this.mutations,e.mutations,(e,t)=>rk(e,t))&&K(this.baseMutations,e.baseMutations,(e,t)=>rk(e,t))}}class rU{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){D(e.mutations.length===n.length,58842,{Ve:e.mutations.length,me:n.length});let r=ra,i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new rU(e,t,n,r)}}class rq{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 rB{constructor(e,t){this.count=e,this.unchangedNames=t}}function rz(e){switch(e){case N.OK:return S(64938);case N.CANCELLED:case N.UNKNOWN:case N.DEADLINE_EXCEEDED:case N.RESOURCE_EXHAUSTED:case N.INTERNAL:case N.UNAVAILABLE:case N.UNAUTHENTICATED:return!1;case N.INVALID_ARGUMENT:case N.NOT_FOUND:case N.ALREADY_EXISTS:case N.PERMISSION_DENIED:case N.FAILED_PRECONDITION:case N.ABORTED:case N.OUT_OF_RANGE:case N.UNIMPLEMENTED:case N.DATA_LOSS:return!0;default:return S(15467,{code:e})}}function r$(e){if(void 0===e)return T("GRPC error has no .code"),N.UNKNOWN;switch(e){case r.OK:return N.OK;case r.CANCELLED:return N.CANCELLED;case r.UNKNOWN:return N.UNKNOWN;case r.DEADLINE_EXCEEDED:return N.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return N.RESOURCE_EXHAUSTED;case r.INTERNAL:return N.INTERNAL;case r.UNAVAILABLE:return N.UNAVAILABLE;case r.UNAUTHENTICATED:return N.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return N.INVALID_ARGUMENT;case r.NOT_FOUND:return N.NOT_FOUND;case r.ALREADY_EXISTS:return N.ALREADY_EXISTS;case r.PERMISSION_DENIED:return N.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return N.FAILED_PRECONDITION;case r.ABORTED:return N.ABORTED;case r.OUT_OF_RANGE:return N.OUT_OF_RANGE;
4case r.UNIMPLEMENTED:return N.UNIMPLEMENTED;case r.DATA_LOSS:return N.DATA_LOSS;default:return S(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 rK=new c.jz([0xffffffff,0xffffffff],0);function rj(e){let t=U().encode(e),n=new c.VV;return n.update(t),new Uint8Array(n.digest())}function rG(e){let t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new c.jz([n,r],0),new c.jz([i,s],0)]}class rQ{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new rW(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new rW(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new rW(`Invalid padding when bitmap length is 0: ${t}`);this.fe=8*e.length-t,this.ge=c.jz.fromNumber(this.fe)}pe(e,t,n){let r=e.add(t.multiply(c.jz.fromNumber(n)));return 1===r.compare(rK)&&(r=new c.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.ge).toNumber()}ye(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.fe)return!1;let[t,n]=rG(rj(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 rQ(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]=rG(rj(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 rW extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rH{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,rX.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new rH(ea.min(),r,new tF(B),rt,rl())}}class rX{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 rX(n,t,rl(),rl(),rl())}}class rY{constructor(e,t,n,r){this.Se=e,this.removedTargetIds=t,this.key=n,this.be=r}}class rJ{constructor(e,t){this.targetId=e,this.De=t}}class rZ{constructor(e,t,n=t$.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class r0{constructor(){this.ve=0,this.Ce=r5(),this.Fe=t$.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=rl(),t=rl(),n=rl();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:S(38017,{changeType:i})}}),new rX(this.Fe,this.Me,e,t,n)}ke(){this.xe=!1,this.Ce=r5()}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,D(this.ve>=0,3241,{ve:this.ve})}Ke(){this.xe=!0,this.Me=!0}}class r1{constructor(e){this.We=e,this.Ge=new Map,this.ze=rt,this.je=r2(),this.Je=r2(),this.He=new tF(B)}Ye(e){for(let t of e.Se)e.be&&e.be.isFoundDocument()?this.Ze(t,e.be):this.Xe(t,e.key,e.be);for(let t of e.removedTargetIds)this.Xe(t,e.key,e.be)}et(e){this.forEachTarget(e,t=>{let n=this.tt(t);switch(e.state){case 0:this.nt(t)&&n.Be(e.resumeToken);break;case 1:n.Ue(),n.Oe||n.ke(),n.Be(e.resumeToken);break;case 2:n.Ue(),n.Oe||this.removeTarget(t);break;case 3:this.nt(t)&&(n.Ke(),n.Be(e.resumeToken));break;case 4:this.nt(t)&&(this.rt(t),n.Be(e.resumeToken));break;default:S(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Ge.forEach((e,n)=>{this.nt(n)&&t(n)})}it(e){let t=e.targetId,n=e.De.count,r=this.st(t);if(r){let i=r.target;if(nj(i))if(0===n){let e=new X(i.path);this.Xe(t,e,nI.newNoDocument(e,ea.min()))}else D(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"))}}}}_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=tQ(i).toUint8Array()}catch(e){if(e instanceof tz)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 rQ(t,s,a)}catch(e){return E(e instanceof rW?"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&&nj(i.target)){let t=new X(i.target.path);this.Tt(t).has(r)||this.It(r,t)||this.Xe(r,t,nI.newNoDocument(t,e))}n.Ne&&(t.set(r,n.Le()),n.ke())}});let n=rl();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 rH(e,t,this.He,this.ze,n);return this.ze=rt,this.je=r2(),this.Je=r2(),this.He=new tF(B),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 r0,this.Ge.set(e,t)),t}dt(e){let t=this.Je.get(e);return t||(t=new tL(B),this.Je=this.Je.insert(e,t)),t}Tt(e){let t=this.je.get(e);return t||(t=new tL(B),this.je=this.je.insert(e,t)),t}nt(e){let t=null!==this.st(e);return t||b("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 r0),this.We.getRemoteKeysForTarget(e).forEach(t=>{this.Xe(e,t,null)})}It(e,t){return this.We.getRemoteKeysForTarget(e).has(t)}}function r2(){return new tF(X.comparator)}function r5(){return new tF(X.comparator)}let r4={asc:"ASCENDING",desc:"DESCENDING"},r3={"<":"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"},r6={and:"AND",or:"OR"};class r8{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function r9(e,t){return e.useProto3Json||eF(t)?t:{value:t}}function r7(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 ie(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function it(e){return D(!!e,49232),ea.fromTimestamp(function(e){let t=tj(e);return new es(t.seconds,t.nanos)}(e))}function ir(e,t){return ii(e,t).canonicalString()}function ii(e,t){let n=new Q(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function is(e){let t=Q.fromString(e);return D(iT(t),10190,{key:t.toString()}),t}function ia(e,t){return ir(e.databaseId,t.path)}function io(e,t){let n=is(t);if(n.get(1)!==e.databaseId.projectId)throw new C(N.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 C(N.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new X(ic(n))}function il(e,t){return ir(e.databaseId,t)}function iu(e){let t=is(e);return 4===t.length?Q.emptyPath():ic(t)}function ih(e){return new Q(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function ic(e){return D(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function id(e,t,n){return{name:ia(e,t),fields:n.value.mapValue.fields}}function im(e,t,n){let r=io(e,t.name),i=it(t.updateTime),s=t.createTime?it(t.createTime):ea.min(),a=new nv({mapValue:{fields:t.fields}}),o=nI.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function ig(e,t){var n;let r;if(t instanceof rA)r={update:id(e,t.key,t.value)};else if(t instanceof rP)r={delete:ia(e,t.key)};else if(t instanceof rV)r={update:id(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 rM))return S(16599,{Rt:t.type});r={verify:ia(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof rg)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof rp)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof rw)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof rI)return{fieldPath:t.field.canonicalString(),increment:n.Ee};throw S(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:r7(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:S(27497)),r}function ip(e,t){var n;let r=t.currentDocument?void 0!==(n=t.currentDocument).updateTime?rS.updateTime(it(n.updateTime)):void 0!==n.exists?rS.exists(n.exists):rS.none():rS.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let n;return n=null,"setToServerValue"in t?(D("REQUEST_TIME"===t.setToServerValue,16630,{proto:t}),n=new rg):"appendMissingElements"in t?n=new rp(t.appendMissingElements.values||[]):"removeAllFromArray"in t?n=new rw(t.removeAllFromArray.values||[]):"increment"in t?n=new rI(e,t.increment):S(16584,{proto:t}),new rE(H.fromServerFormat(t.fieldPath),n)}):[];if(t.update){t.update.name;let n=io(e,t.update.name),s=new nv({mapValue:{fields:t.update.fields}});return t.updateMask?new rV(n,s,new tB((t.updateMask.fieldPaths||[]).map(e=>H.fromServerFormat(e))),r,i):new rA(n,s,r,i)}return t.delete?new rP(io(e,t.delete),r):t.verify?new rM(io(e,t.verify),r):S(1463,{proto:t})}function iy(e,t){return{documents:[il(e,t.path)]}}function iw(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=il(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof nx?function(e){if("=="===e.op){if(nc(e.value))return{unaryFilter:{field:iI(e.field),op:"IS_NAN"}};if(nh(e.value))return{unaryFilter:{field:iI(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(nc(e.value))return{unaryFilter:{field:iI(e.field),op:"IS_NOT_NAN"}};if(nh(e.value))return{unaryFilter:{field:iI(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:iI(e.field),op:r3[e.op],value:e.value}}}(t):t instanceof nD?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:r6[t.op],filters:n}}}(t):S(54877,{filter:t})}(nD.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:iI(e.field),direction:r4[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=r9(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 iv(e){var t;let n,r=iu(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){D(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=ib(e.unaryFilter.field);return nx.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=ib(e.unaryFilter.field);return nx.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=ib(e.unaryFilter.field);return nx.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=ib(e.unaryFilter.field);return nx.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return S(61313);default:return S(60726)}}(t):void 0!==t.fieldFilter?nx.create(ib(t.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return S(58110);default:return S(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?nD.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return S(1026)}}(t.compositeFilter.op)):S(30097,{filter:t})}(e);return t instanceof nD&&nk(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new n_(ib(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=eF(n="object"==typeof(t=i.limit)?t.value:t)?null:n);let h=null;i.startAt&&(h=function(e){let t=!!e.before;return new nb(e.values||[],t)}(i.startAt));let c=null;return i.endAt&&(c=function(e){let t=!e.before;return new nb(e.values||[],t)}(i.endAt)),new nH(r,a,l,o,u,"F",h,c)}function iI(e){return{fieldPath:e.canonicalString()}}function ib(e){return H.fromServerFormat(e.fieldPath)}function iT(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class iE{constructor(e,t,n,r,i=ea.min(),s=ea.min(),a=t$.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 iE(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new iE(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new iE(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new iE(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class i_{constructor(e){this.gt=e}}function iS(e,t){let n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:ix(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;r.document={name:ia(i=e.gt,t.key),fields:t.data.value.mapValue.fields,updateTime:r7(i,t.version.toTimestamp()),createTime:r7(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:iD(t.version)};else{if(!t.isUnknownDocument())return S(57904,{document:t});r.unknownDocument={path:n.path.toArray(),version:iD(t.version)}}return r}function ix(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function iD(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function iN(e){let t=new es(e.seconds,e.nanoseconds);return ea.fromTimestamp(t)}function iC(e,t){let n=(t.baseMutations||[]).map(t=>ip(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=>ip(e.gt,t)),i=es.fromMillis(t.localWriteTimeMs);return new rL(t.batchId,i,n,r)}function ik(e){let t=iN(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?iN(e.lastLimboFreeSnapshotVersion):ea.min();return new iE(void 0!==e.query.documents?function(e){let t=e.documents.length;return D(1===t,1966,{count:t}),n0(nX(iu(e.documents[0])))}(e.query):n0(iv(e.query)),e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,t$.fromBase64String(e.resumeToken))}function iA(e,t){let n,r=iD(t.snapshotVersion),i=iD(t.lastLimboFreeSnapshotVersion);n=nj(t.target)?iy(e.gt,t.target):iw(e.gt,t.target).Vt;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:n$(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function iV(e){let t=iv({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?n5(t,t.limit,"L"):t}function iR(e,t){return new rq(t.largestBatchId,ip(e.gt,t.overlayMutation))}function iO(e,t){let n=t.path.lastSegment();return[e,eL(t.path.popLast()),n]}function iF(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:iD(r.readTime),documentKey:eL(r.documentKey.path),largestBatchId:r.largestBatchId}}class iP{getBundleMetadata(e,t){return tA(e,ta).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:iN(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return tA(e,ta).put({bundleId:t.id,createTime:iD(it(t.createTime)),version:t.version})}getNamedQuery(e,t){return tA(e,to).get(t).next(e=>{if(e)return{name:e.name,query:iV(e.bundledQuery),readTime:iN(e.readTime)}})}saveNamedQuery(e,t){return tA(e,to).put({name:t.name,readTime:iD(it(t.readTime)),bundledQuery:t.bundledQuery})}}
4class iM{constructor(e,t){this.serializer=e,this.userId=t}static yt(e,t){return new iM(e,t.uid||"")}getOverlay(e,t){return tA(e,tw).get(iO(this.userId,t)).next(e=>e?iR(this.serializer,e):null)}getOverlays(e,t){let n=rs();return ev.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 rq(t,i);r.push(this.wt(e,s))}),ev.waitFor(r)}removeOverlaysForBatchId(e,t,n){let r=new Set;t.forEach(e=>r.add(eL(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(tA(e,tw).Y(tI,r))}),ev.waitFor(i)}getOverlaysForCollection(e,t,n){let r=rs(),i=eL(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return tA(e,tw).j(tI,s).next(e=>{for(let t of e){let e=iR(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){let i,s=rs(),a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return tA(e,tw).X({index:tT,range:a},(e,t,n)=>{let a=iR(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 tA(e,tw).put(function(e,t,n){let[r,i,s]=iO(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:ig(e.gt,n.mutation)}}(this.serializer,this.userId,t))}}class iL{St(e){return tA(e,t_)}getSessionToken(e){return this.St(e).get("sessionToken").next(e=>{let t=null==e?void 0:e.value;return t?t$.fromUint8Array(t):t$.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.St(e).put({name:"sessionToken",value:t.toUint8Array()})}}class iU{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(tG(e.integerValue));else if("doubleValue"in e){let n=tG(e.doubleValue);isNaN(n)?this.Ct(t,13):(this.Ct(t,15),eP(n)?t.Ft(0):t.Ft(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Ct(t,20),"string"==typeof n&&(n=tj(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(tQ(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?ng(e)?this.Ct(t,Number.MAX_SAFE_INTEGER):nf(e)?this.Lt(e.mapValue,t):(this.kt(e.mapValue,t),this.Ot(t)):"arrayValue"in e?(this.qt(e.arrayValue,t),this.Ot(t)):S(19022,{Qt:e})}xt(e,t){this.Ct(t,25),this.$t(e,t)}$t(e,t){t.Mt(e)}kt(e,t){let n=e.fields||{};for(let e of(this.Ct(t,55),Object.keys(n)))this.xt(e,t),this.Dt(n[e],t)}Lt(e,t){var n,r;let i=e.fields||{};this.Ct(t,53);let s=(null===(r=null===(n=i[t9].arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.length)||0;this.Ct(t,15),t.Ft(tG(s)),this.xt(t9,t),this.Dt(i[t9],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),X.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 iq(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)}iU.Ut=new iU;class iB{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=iq(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=iq(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 iz{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 i${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 iK{constructor(){this.un=new iB,this.cn=new iz(this.un),this.ln=new i$(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 ij{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 ij(this.Pn,this.Tn,this.In,n)}An(e,t,n){return{indexId:this.Pn,uid:e,arrayValue:iW(this.In),directionalValue:iW(this.dn),orderedDocumentKey:iW(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 iG(e,t){let n=e.Pn-t.Pn;return 0!==n?n:0!==(n=iQ(e.In,t.In))?n:0!==(n=iQ(e.dn,t.dn))?n:X.comparator(e.Tn,t.Tn)}function iQ(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 iW(e){return(0,h.Ov)()?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}(e):e}function iH(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 iX{constructor(e){for(let t of(this.Vn=new tL((e,t)=>H.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(D(e.collectionGroup===this.collectionId,49279),this.gn)return!1;let t=el(e);if(void 0!==t&&!this.yn(t))return!1;let n=eu(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 tL(H.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 eh(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new eh(n.field,0))}for(let n of this.mn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new eh(n.field,+("asc"!==n.dir))));return new eo(eo.UNKNOWN_ID,this.collectionId,t,ec.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 iY(e){return e instanceof nx}function iJ(e){return e instanceof nD&&nk(e)}function iZ(e){return iY(e)||iJ(e)||function(e){if(e instanceof nD&&nC(e)){for(let t of e.getFilters())if(!iY(t)&&!iJ(t))return!1;return!0}return!1}(e)}function i0(e,t){return D(e instanceof nx||e instanceof nD,38388),D(t instanceof nx||t instanceof nD,25473),i2(e instanceof nx?t instanceof nx?nD.create([e,t],"and"):i1(e,t):t instanceof nx?i1(t,e):function(e,t){if(D(e.filters.length>0&&t.filters.length>0,48005),nN(e)&&nN(t))return nV(e,t.getFilters());let n=nC(e)?e:t,r=nC(e)?t:e,i=n.filters.map(e=>i0(e,r));return nD.create(i,"or")}(e,t))}function i1(e,t){if(nN(t))return nV(t,e.getFilters());{let n=t.filters.map(t=>i0(e,t));return nD.create(n,"or")}}function i2(e){if(D(e instanceof nx||e instanceof nD,11850),e instanceof nx)return e;let t=e.getFilters();if(1===t.length)return i2(t[0]);if(nA(e))return e;let n=t.map(e=>i2(e)),r=[];
4return n.forEach(t=>{t instanceof nx?r.push(t):t instanceof nD&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:nD.create(r,e.op)}class i5{constructor(){this.Dn=new i4}addToCollectionParentIndex(e,t){return this.Dn.add(t),ev.resolve()}getCollectionParents(e,t){return ev.resolve(this.Dn.getEntries(t))}addFieldIndex(e,t){return ev.resolve()}deleteFieldIndex(e,t){return ev.resolve()}deleteAllFieldIndexes(e){return ev.resolve()}createTargetIndexes(e,t){return ev.resolve()}getDocumentsMatchingTarget(e,t){return ev.resolve(null)}getIndexType(e,t){return ev.resolve(0)}getFieldIndexes(e,t){return ev.resolve([])}getNextCollectionGroupToUpdate(e){return ev.resolve(null)}getMinOffset(e,t){return ev.resolve(em.min())}getMinOffsetFromCollectionGroup(e,t){return ev.resolve(em.min())}updateCollectionGroup(e,t,n){return ev.resolve()}updateIndexEntries(e,t){return ev.resolve()}}class i4{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new tL(Q.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 tL(Q.comparator)).toArray()}}let i3="IndexedDbIndexManager",i6=new Uint8Array(0);class i8{constructor(e,t){this.databaseId=t,this.vn=new i4,this.Cn=new re(e=>n$(e),(e,t)=>nK(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:eL(r)};return tA(e,tr).put(i)}return ev.resolve()}getCollectionParents(e,t){let n=[],r=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return tA(e,tr).j(r).next(e=>{for(let r of e){if(r.collectionId!==t)break;n.push(eU(r.parent))}return n})}addFieldIndex(e,t){let n=tA(e,tl),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=tA(e,th);return i.next(e=>{n.put(iF(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let n=tA(e,tl),r=tA(e,th),i=tA(e,tm);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=tA(e,tl),n=tA(e,tm),r=tA(e,th);return t.Y().next(()=>n.Y()).next(()=>r.Y())}createTargetIndexes(e,t){return ev.forEach(this.Fn(t),t=>this.getIndexType(e,t).next(n=>{if(0===n||1===n){let n=new iX(t).bn();if(null!=n)return this.addFieldIndex(e,n)}}))}getDocumentsMatchingTarget(e,t){let n=tA(e,tm),r=!0,i=new Map;return ev.forEach(this.Fn(t),t=>this.Mn(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>{if(r){let e=rl(),r=[];return ev.forEach(i,(i,s)=>{b(i3,`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${n$(t)}`);let a=function(e,t){let n=el(t);if(void 0===n)return null;for(let t of nG(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 eu(t))for(let t of nG(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 eu(t)){let t=0===i.kind?nQ(e,i.fieldPath,e.startAt):nW(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new nb(n,r)}(s,i),u=function(e,t){let n=[],r=!0;for(let i of eu(t)){let t=0===i.kind?nW(e,i.fieldPath,e.endAt):nQ(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new nb(n,r)}(s,i),h=this.xn(i,s,l),c=this.xn(i,s,u),d=this.On(i,s,o),f=this.Nn(i.indexId,a,h,l.inclusive,c,u.inclusive,d);return ev.forEach(f,i=>n.H(i,t.limit).next(t=>{t.forEach(t=>{let n=X.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return ev.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(D(t instanceof nx||t instanceof nD,34018),t instanceof nx)return t;if(1===t.filters.length)return e(t.filters[0]);let n=t.filters.map(t=>e(t)),r=nD.create(n,t.op);return iZ(r=i2(r))?r:(D(r instanceof nD,64498),D(nN(r),40251),D(r.filters.length>1,57927),r.filters.reduce((e,t)=>
4i0(e,t)))}(function e(t){var n,r;if(D(t instanceof nx||t instanceof nD,20012),t instanceof nx){if(t instanceof nL){let e=(null===(r=null===(n=t.value.arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.map(e=>nx.create(t.field,"==",e)))||[];return nD.create(e,"or")}return t}let i=t.filters.map(t=>e(t));return nD.create(i,t.op)}(e));return D(iZ(t),7391),iY(t)||iJ(t)?[t]:t.getFilters()})(nD.create(e.filters,"and")).map(t=>nz(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 h=0;h<o;++h){let o=t?this.Bn(t[h/l]):i6,c=this.Ln(e,o,n[h%l],r),d=this.kn(e,o,i[h%l],s),f=a.map(t=>this.Ln(e,o,t,!0));u.push(...this.createRange(c,d,f))}return u}Ln(e,t,n,r){let i=new ij(e,X.empty(),t,n);return r?i:i.En()}kn(e,t,n,r){let i=new ij(e,X.empty(),t,n);return r?i.En():i}Mn(e,t){let n=new iX(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);return ev.forEach(r,t=>this.Mn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new tL(H.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 iK;for(let r of eu(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;let i=n.hn(r.kind);iU.Ut.bt(e,i)}return n.an()}Bn(e){let t=new iK;return iU.Ut.bt(e,t.hn(0)),t.an()}Qn(e,t){let n=new iK;return iU.Ut.bt(no(this.databaseId,t),n.hn(function(e){let t=eu(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 iK);let i=0;for(let s of eu(e)){let e=n[i++];for(let n of r)if(this.$n(t,s.fieldPath)&&nu(e))r=this.Un(r,s,e);else{let t=n.hn(s.kind);iU.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 iK;r.seed(n.an()),iU.Ut.bt(e,r.hn(t.kind)),i.push(r)}return i}$n(e,t){return!!e.filters.find(e=>e instanceof nx&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let n=tA(e,tl),r=tA(e,th);return(t?n.j(tu,IDBKeyRange.bound(t,t)):n.j()).next(e=>{let t=[];return ev.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){let n=t?new ec(t.sequenceNumber,new em(iN(t.readTime),new X(eU(t.documentKey)),t.largestBatchId)):ec.empty(),r=e.fields.map(([e,t])=>new eh(H.fromServerFormat(e),t));return new eo(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:B(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){let r=tA(e,tl),i=tA(e,th);return this.Wn(e).next(e=>r.j(tu,IDBKeyRange.bound(t,t)).next(t=>ev.forEach(t,t=>i.put(iF(t.indexId,this.uid,e,n)))))}updateIndexEntries(e,t){let n=new Map;return ev.forEach(t,(t,r)=>{let i=n.get(t.collectionGroup);return(i?ev.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),ev.forEach(i,n=>this.Gn(e,t,n).next(t=>{let i=this.zn(r,n);return t.isEqual(i)?ev.resolve():this.jn(e,r,n,t,i)}))))})}Jn(e,t,n,r){return tA(e,tm).put(r.An(this.uid,this.Qn(n,t.key),t.key))}Hn(e,t,n,r){return tA(e,tm).delete(r.Rn(this.uid,this.Qn(n,t.key),t.key))}Gn(e,t,n){let r=tA(e,tm),i=new tL(iG);return r.X({index:tp,range:IDBKeyRange.only([n.indexId,this.uid,iW(this.Qn(n,t))])},(e,r)=>{i=i.add(new ij(n.indexId,t,iH(r.arrayValue),iH(r.directionalValue)))}).next(()=>i)}zn(e,t){let n=new tL(iG),r=this.qn(t,e);if(null==r)return n;let i=el(t);if(null!=i){let s=e.data.field(i.fieldPath);if(nu(s))for(let i of s.arrayValue.values||[])n=n.add(new ij(t.indexId,e.key,this.Bn(i),r))}else n=n.add(new ij(t.indexId,e.key,i6,r));return n}jn(e,t,n,r,i){b(i3,"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;
4e?(r(l),l=tq(a)):t?(i(o),o=tq(s)):(o=tq(s),l=tq(a))}}(r,i,iG,r=>{s.push(this.Jn(e,t,n,r))},r=>{s.push(this.Hn(e,t,n,r))}),ev.waitFor(s)}Wn(e){let t=1;return tA(e,th).X({index:td,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)=>iG(e,t)).filter((e,t,n)=>!t||0!==iG(e,n[t-1]));let r=[];for(let i of(r.push(e),n)){let n=iG(i,e),s=iG(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,i6,X.empty()),n=r[e+1].Rn(this.uid,i6,X.empty());i.push(IDBKeyRange.bound(t,n))}return i}Yn(e,t){return iG(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(i9)}getMinOffset(e,t){return ev.mapArray(this.Fn(t),t=>this.Mn(e,t).next(e=>e||S(44426))).next(i9)}}function i9(e){D(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>eg(i,t)&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new em(t.readTime,t.documentKey,n)}let i7={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class se{static withCacheSize(e){return new se(e,se.DEFAULT_COLLECTION_PERCENTILE,se.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function st(e,t,n){let r=e.store(eK),i=e.store(eH),s=[],a=IDBKeyRange.only(n.batchId),o=0,l=r.X({range:a},(e,t,n)=>(o++,n.delete()));s.push(l.next(()=>{D(1===o,47070,{batchId:n.batchId})}));let u=[];for(let e of n.mutations){var h,c;let r=(h=e.key.path,c=n.batchId,[t,eL(h),c]);s.push(i.delete(r)),u.push(e.key)}return ev.waitFor(s).next(()=>u)}function sn(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 S(14731);t=e.noDocument}return JSON.stringify(t).length}se.DEFAULT_COLLECTION_PERCENTILE=10,se.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,se.DEFAULT=new se(0x2800000,se.DEFAULT_COLLECTION_PERCENTILE,se.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),se.DISABLED=new se(-1,0,0);class sr{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 D(""!==e.uid,64387),new sr(e.isAuthenticated()?e.uid:"",t,n,r)}checkEmpty(e){let t=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return ss(e).X({index:eG,range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){let i=tA(e,eH),s=ss(e);return s.add({}).next(a=>{D("number"==typeof a,49019);let o=new rL(a,t,n,r),l=function(e,t,n){let r=n.baseMutations.map(t=>ig(e.gt,t)),i=n.mutations.map(t=>ig(e.gt,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,o),u=[],h=new tL((e,t)=>B(e.canonicalString(),t.canonicalString()));for(let e of r){var c;let t=(c=this.userId,[c,eL(e.key.path),a]);h=h.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,eW))}return h.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.Zn[a]=o.keys()}),ev.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return ss(e).get(t).next(e=>e?(D(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),iC(this.serializer,e)):null)}Xn(e,t){return this.Zn[t]?ev.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 ss(e).X({index:eG,range:r},(e,t,r)=>{t.userId===this.userId&&(D(t.batchId>=n,47524,{er:n}),i=iC(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=-1;return ss(e).X({index:eG,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return ss(e).j(eG,t).next(e=>e.map(e=>iC(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let n=[this.userId,eL(t.path)],r=IDBKeyRange.lowerBound(n),i=[];return tA(e,eH).X({range:r},(n,r,s)=>{let[a,o,l]=n,u=eU(o);if(a===this.userId&&t.path.isEqual(u))return ss(e).get(l).next(e=>{if(!e)throw S(61480,{tr:n,batchId:l});D(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:l}),i.push(iC(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tL(B),r=[];return t.forEach(t=>{let i=[this.userId,eL(t.path)],s=IDBKeyRange.lowerBound(i),a=tA(e,eH).X({range:s},(e,r,i)=>{let[s,a,o]=e,l=eU(a);s===this.userId&&t.path.isEqual(l)?n=n.add(o):i.done()});r.push(a)}
4),ev.waitFor(r).next(()=>this.nr(e,n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=[this.userId,eL(n)],s=IDBKeyRange.lowerBound(i),a=new tL(B);return tA(e,eH).X({range:s},(e,t,i)=>{let[s,o,l]=e,u=eU(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(ss(e).get(t).next(e=>{if(null===e)throw S(35274,{batchId:t});D(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),n.push(iC(this.serializer,e))}))}),ev.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return st(e.ce,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.rr(t.batchId)}),ev.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 ev.resolve();let n=IDBKeyRange.lowerBound([this.userId]),r=[];return tA(e,eH).X({range:n},(e,t,n)=>{if(e[0]===this.userId){let t=eU(e[1]);r.push(t)}else n.done()}).next(()=>{D(0===r.length,56720,{ir:r.map(e=>e.canonicalString())})})})}containsKey(e,t){return si(e,this.userId,t)}sr(e){return tA(e,e$).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function si(e,t,n){let r=[t,eL(n.path)],i=r[1],s=IDBKeyRange.lowerBound(r),a=!1;return tA(e,eH).X({range:s,Z:!0},(e,n,r)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),r.done()}).next(()=>a)}function ss(e){return tA(e,eK)}class sa{constructor(e){this._r=e}next(){return this._r+=2,this._r}static ar(){return new sa(0)}static ur(){return new sa(-1)}}class so{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.cr(e).next(t=>{let n=new sa(t.highestTargetId);return t.highestTargetId=n.next(),this.lr(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.cr(e).next(e=>ea.fromTimestamp(new es(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(()=>tA(e,e4).delete(t.targetId)).next(()=>this.cr(e)).next(t=>(D(t.targetCount>0,8065),t.targetCount-=1,this.lr(e,t)))}removeTargets(e,t,n){let r=0,i=[];return tA(e,e4).X((s,a)=>{let o=ik(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,i.push(this.removeTargetData(e,o)))}).next(()=>ev.waitFor(i)).next(()=>r)}forEachTarget(e,t){return tA(e,e4).X((e,n)=>{t(ik(n))})}cr(e){return tA(e,tn).get(tt).next(e=>(D(null!==e,2888),e))}lr(e,t){return tA(e,tn).put(tt,t)}hr(e,t){return tA(e,e4).put(iA(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=n$(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]),i=null;return tA(e,e4).X({range:r,index:e3},(e,n,r)=>{let s=ik(n);nK(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){let r=[],i=sl(e);return t.forEach(t=>{let s=eL(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),ev.waitFor(r)}removeMatchingKeys(e,t,n){let r=sl(e);return ev.forEach(t,t=>{let i=eL(t.path);return ev.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){let n=sl(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=sl(e),i=rl(
4);return r.X({range:n,Z:!0},(e,t,n)=>{let r=new X(eU(e[1]));i=i.add(r)}).next(()=>i)}containsKey(e,t){let n=eL(t.path),r=IDBKeyRange.bound([n],[n+"\0"],!1,!0),i=0;return sl(e).X({index:e7,Z:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}Et(e,t){return tA(e,e4).get(t).next(e=>e?ik(e):null)}}function sl(e){return tA(e,e8)}let su="LruGarbageCollector";function sh([e,t],[n,r]){let i=B(e,n);return 0===i?B(t,r):i}class sc{constructor(e){this.Tr=e,this.buffer=new tL(sh),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>sh(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class sd{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){b(su,`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){ex(e)?b(su,"Ignoring IndexedDB error during garbage collection: ",e):await ew(e)}await this.Rr(3e5)})}}class sf{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 ev.resolve(eO.ue);let n=new sc(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?(b("LruGarbageCollector","Garbage collection skipped; disabled"),ev.resolve(i7)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(b("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),i7):this.pr(e,t))}getCacheSize(e){return this.Vr.getCacheSize(e)}pr(e,t){let n,r,i,s,a,o,l,h=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(b("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(),I()<=u.$b.DEBUG&&b("LruGarbageCollector",`LRU Garbage Collection
5	Counted targets in ${s-h}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-h}ms`),ev.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class sm{constructor(e,t){this.db=e,this.garbageCollector=new sf(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 sg(e,n)}removeReference(e,t,n){return sg(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return sg(e,t)}Sr(e,t){let n;return n=!1,tA(e,e$).ee(r=>si(e,r,t).next(e=>(e&&(n=!0),ev.resolve(!e)))).next(()=>n)}removeOrphanedDocuments(e,t){let n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[],i=0;return this.wr(e,(s,a)=>{if(a<=t){let t=this.Sr(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,ea.min()),sl(e).delete([0,eL(s.path)])))});r.push(t)}}).next(()=>ev.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 sg(e,t)}wr(e,t){let n=sl(e),r,i=eO.ue;return n.X({index:e7},([e,n],{path:s,sequenceNumber:a})=>
6{0===e?(i!==eO.ue&&t(new X(eU(r)),i),i=a,r=s):i=eO.ue}).next(()=>{i!==eO.ue&&t(new X(eU(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function sg(e,t){var n;return sl(e).put((n=e.currentSequenceNumber,{targetId:0,path:eL(t.path),sequenceNumber:n}))}class sp{constructor(){this.changes=new re(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,nI.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?ev.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 sy{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return tA(e,eX).put(n)}removeEntry(e,t,n){return tA(e,eX).delete(function(e,t){let n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],ix(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=nI.newInvalidDocument(t);return tA(e,eX).X({index:eJ,range:IDBKeyRange.only(sv(t))},(e,r)=>{n=this.Dr(t,r)}).next(()=>n)}vr(e,t){let n={size:0,document:nI.newInvalidDocument(t)};return tA(e,eX).X({index:eJ,range:IDBKeyRange.only(sv(t))},(e,r)=>{n={document:this.Dr(t,r),size:sn(r)}}).next(()=>n)}getEntries(e,t){let n=rt;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=rt,r=new tF(X.comparator);return this.Cr(e,t,(e,t)=>{let i=this.Dr(e,t);n=n.insert(e,i),r=r.insert(e,sn(t))}).next(()=>({documents:n,Mr:r}))}Cr(e,t,n){if(t.isEmpty())return ev.resolve();let r=new tL(sb);t.forEach(e=>r=r.add(e));let i=IDBKeyRange.bound(sv(r.first()),sv(r.last())),s=r.getIterator(),a=s.getNext();return tA(e,eX).X({index:eJ,range:i},(e,t,r)=>{let i=X.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>sb(a,i);)n(a,null),a=s.getNext();a&&a.isEqual(i)&&(n(a,t),a=s.hasNext()?s.getNext():null),a?r.G(sv(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(),ix(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 tA(e,eX).j(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let n=rt;for(let i of e){let e=this.Dr(X.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(n8(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=rt,s=sI(t,n),a=sI(t,em.max());return tA(e,eX).X({index:e0,range:IDBKeyRange.bound(s,a,!0)},(e,t,n)=>{let s=this.Dr(X.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 sw(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return tA(e,e2).get(e5).next(e=>(D(!!e,20021),e))}br(e,t){return tA(e,e2).put(e5,t)}Dr(e,t){if(t){let e=function(e,t){let n;if(t.document)n=im(e.gt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=X.fromSegments(t.noDocument.path),r=iN(t.noDocument.readTime);n=nI.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return S(56709);{let e=X.fromSegments(t.unknownDocument.path),r=iN(t.unknownDocument.version);n=nI.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){let t=new es(e[0],e[1]);return ea.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual(ea.min())))return e}return nI.newInvalidDocument(e)}}class sw extends sp{constructor(e,t){super(),this.Or=e,this.trackRemovals=t,this.Nr=new re(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],n=0,r=new tL((e,t)=>B(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=iS(this.Or.serializer,s);r=r.add(i.path.popLast());let l=sn(o);n+=l-a.size,t.push(this.Or.addEntry(e,i,o))}else if(n-=a.size,this.trackRemovals){let n=iS(this.Or.serializer,s.convertToNoDocument(ea.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)),ev.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 sv(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function sI(e,t){let n=t.documentKey.path.toArray();return[e,ix(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function sb(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=B(n[e],r[e]))return i;return(i=B(n.length,r.length))||(i=B(n[n.length-2],r[r.length-2]))||B(n[n.length-1],r[r.length-1])}class sT{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class sE{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&&rC(n.mutation,e,tB.empty(),es.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,rl()).next(()=>t))}getLocalViewOfDocuments(e,t,n=rl()){let r=rs();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=rr();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=rs();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,rl()))}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=rt,s=rs(),a=rs();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof rV)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),rC(a.mutation,t,a.mutation.getFieldMask(),es.now())):s.set(t.key,tB.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 sT(t,null!==(n=s.get(e))&&void 0!==n?n:null))}),a))}recalculateAndSaveOverlays(e,t){let n=rs(),r=new tF((e,t)=>e-t),i=rl();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)||tB.empty();a=i.applyToLocalView(s,a),n.set(e,a);let o=(r.get(i.batchId)||rl()).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=rs();l.forEach(e=>{if(!i.has(e)){let r=rN(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 ev.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 X.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):nJ(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):ev.resolve(rs()),a=-1,o=i;return s.next(t=>ev.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?ev.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,rl())).next(e=>({batchId:a,changes:ri(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new X(t)).next(e=>{let t=rr();
vendor: 4,135 bytes, line 6
6return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let i=t.collectionGroup,s=rr();return this.indexManager.getCollectionParents(e,i).next(a=>ev.forEach(a,a=>{let o=new nH(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,nI.newInvalidDocument(r)))});let n=rr();return e.forEach((e,r)=>{let s=i.get(e);void 0!==s&&rC(s.mutation,r,tB.empty(),es.now()),n8(t,r)&&(n=n.insert(e,r))}),n})}}class s_{constructor(e){this.serializer=e,this.Br=new Map,this.Lr=new Map}getBundleMetadata(e,t){return ev.resolve(this.Br.get(t))}saveBundleMetadata(e,t){return this.Br.set(t.id,{id:t.id,version:t.version,createTime:it(t.createTime)}),ev.resolve()}getNamedQuery(e,t){return ev.resolve(this.Lr.get(t))}saveNamedQuery(e,t){return this.Lr.set(t.name,{name:t.name,query:iV(t.bundledQuery),readTime:it(t.readTime)}),ev.resolve()}}class sS{constructor(){this.overlays=new tF(X.comparator),this.kr=new Map}getOverlay(e,t){return ev.resolve(this.overlays.get(t))}getOverlays(e,t){let n=rs();return ev.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)}),ev.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)),ev.resolve()}getOverlaysForCollection(e,t,n){let r=rs(),i=t.length+1,s=new X(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 ev.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new tF((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=rs(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=rs(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return ev.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 rq(t,n));let i=this.kr.get(t);void 0===i&&(i=rl(),this.kr.set(t,i)),this.kr.set(t,i.add(n.key))}}class sx{constructor(){this.sessionToken=t$.EMPTY_BYTE_STRING}getSessionToken(e){return ev.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,ev.resolve()}}class sD{constructor(){this.qr=new tL(sN.Qr),this.$r=new tL(sN.Ur)}isEmpty(){return this.qr.isEmpty()}addReference(e,t){let n=new sN(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 sN(e,t))}Gr(e,t){e.forEach(e=>this.removeReference(e,t))}zr(e){let t=new X(new Q([])),n=new sN(t,e),r=new sN(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 X(new Q([])),n=new sN(t,e),r=new sN(t,e+1),i=rl();return this.$r.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new sN(e,0),n=this.qr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class sN{constructor(e,t){this.key=e,this.Hr=t}static Qr(e,t){return X.comparator(e.key,t.key)||B(e.Hr,t.Hr)}static Ur(e,t){return B(e.Hr,t.Hr)||X.comparator(e.key,t.key)}}class sC{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.er=1,this.Yr=new tL(sN.Qr)}checkEmpty(e){return ev.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let i=this.er;
6this.er++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new rL(i,t,n,r);for(let t of(this.mutationQueue.push(s),r))this.Yr=this.Yr.add(new sN(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ev.resolve(s)}lookupMutationBatch(e,t){return ev.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.Xr(t+1),r=n<0?0:n;return ev.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return ev.resolve(0===this.mutationQueue.length?-1:this.er-1)}getAllMutationBatches(e){return ev.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new sN(t,0),r=new sN(t,Number.POSITIVE_INFINITY),i=[];return this.Yr.forEachInRange([n,r],e=>{let t=this.Zr(e.Hr);i.push(t)}),ev.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tL(B);return t.forEach(e=>{let t=new sN(e,0),r=new sN(e,Number.POSITIVE_INFINITY);this.Yr.forEachInRange([t,r],e=>{n=n.add(e.Hr)})}),ev.resolve(this.ei(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=n;X.isDocumentKey(i)||(i=i.child(""));let s=new sN(new X(i),0),a=new tL(B);return this.Yr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Hr)),!0)},s),ev.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){D(0===this.ti(t.batchId,"removed"),55003),this.mutationQueue.shift();let n=this.Yr;return ev.forEach(t.mutations,r=>{let i=new sN(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 sN(t,0),r=this.Yr.firstAfterOrEqual(n);return ev.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,ev.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 sk{constructor(e){this.ni=e,this.docs=new tF(X.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 ev.resolve(n?n.document.mutableCopy():nI.newInvalidDocument(t))}getEntries(e,t){let n=rt;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():nI.newInvalidDocument(e))}),ev.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=rt,s=t.path,a=new X(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>=eg(ef(a),n)||(r.has(a.key)||n8(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return ev.resolve(i)}getAllFromCollectionGroup(e,t,n,r){S(9500)}ri(e,t){return ev.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new sA(this)}getSize(e){return ev.resolve(this.size)}}class sA extends sp{constructor(e){super(),this.Or=e}applyChanges(e){let t=[];
vendor: 4,734 bytes, line 6
6return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.Or.addEntry(e,r)):this.Or.removeEntry(n)}),ev.waitFor(t)}getFromCache(e,t){return this.Or.getEntry(e,t)}getAllFromCache(e,t){return this.Or.getEntries(e,t)}}class sV{constructor(e){this.persistence=e,this.ii=new re(e=>n$(e),nK),this.lastRemoteSnapshotVersion=ea.min(),this.highestTargetId=0,this.si=0,this.oi=new sD,this.targetCount=0,this._i=sa.ar()}forEachTarget(e,t){return this.ii.forEach((e,n)=>t(n)),ev.resolve()}getLastRemoteSnapshotVersion(e){return ev.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ev.resolve(this.si)}allocateTargetId(e){return this.highestTargetId=this._i.next(),ev.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.si&&(this.si=t),ev.resolve()}hr(e){this.ii.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this._i=new sa(t),this.highestTargetId=t),e.sequenceNumber>this.si&&(this.si=e.sequenceNumber)}addTargetData(e,t){return this.hr(t),this.targetCount+=1,ev.resolve()}updateTargetData(e,t){return this.hr(t),ev.resolve()}removeTargetData(e,t){return this.ii.delete(t.target),this.oi.zr(t.targetId),this.targetCount-=1,ev.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++)}),ev.waitFor(i).next(()=>r)}getTargetCount(e){return ev.resolve(this.targetCount)}getTargetData(e,t){let n=this.ii.get(t)||null;return ev.resolve(n)}addMatchingKeys(e,t,n){return this.oi.Kr(t,n),ev.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))}),ev.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.oi.zr(t),ev.resolve()}getMatchingKeysForTargetId(e,t){let n=this.oi.Jr(t);return ev.resolve(n)}containsKey(e,t){return ev.resolve(this.oi.containsKey(t))}}class sR{constructor(e,t){this.ai={},this.overlays={},this.ui=new eO(0),this.ci=!1,this.ci=!0,this.li=new sx,this.referenceDelegate=e(this),this.hi=new sV(this),this.indexManager=new i5,this.remoteDocumentCache=new sk(e=>this.referenceDelegate.Pi(e)),this.serializer=new i_(t),this.Ti=new s_(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 sS,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ai[e.toKey()];return n||(n=new sC(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){b("MemoryPersistence","Starting transaction:",e);let r=new sO(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 ev.or(Object.values(this.ai).map(n=>()=>n.containsKey(e,t)))}}class sO extends ey{constructor(e){super(),this.currentSequenceNumber=e}}class sF{constructor(e){this.persistence=e,this.Ai=new sD,this.Ri=null}static Vi(e){return new sF(e)}get mi(){if(this.Ri)return this.Ri;throw S(60996)}addReference(e,t,n){return this.Ai.addReference(n,t),this.mi.delete(n.toString()),ev.resolve()}removeReference(e,t,n){return this.Ai.removeReference(n,t),this.mi.add(n.toString()),ev.resolve()}markPotentiallyOrphaned(e,t){return this.mi.add(t.toString()),ev.resolve()}removeTarget(e,t){this.Ai.zr(t.targetId).forEach(e=>this.mi.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.mi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ii(){this.Ri=new Set}di(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ev.forEach(this.mi,n=>{let r=X.fromPath(n);return this.fi(e,r).next(e=>{e||t.removeEntry(r,ea.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 ev.or([()=>ev.resolve(this.Ai.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}}class sP{constructor(e,t){this.persistence=e,this.gi=new re(e=>eL(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new sf(this,t)}static Vi(e,t){return new sP(e,t)}Ii(){}di(e){return ev.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEac
6hTarget(e,t)}mr(e){let t=this.yr(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}yr(e){let t=0;return this.gr(e,e=>{t++}).next(()=>t)}gr(e,t){return ev.forEach(this.gi,(n,r)=>this.Sr(e,n,r).next(e=>e?ev.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,ea.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.gi.set(t,e.currentSequenceNumber),ev.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),ev.resolve()}removeReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),ev.resolve()}updateLimboDocument(e,t){return this.gi.set(t,e.currentSequenceNumber),ev.resolve()}Pi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(ne(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let n=tZ(t);return n?16+e(n):16;case 5:return 2*t.stringValue.length;case 6:return tQ(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,tR(r.fields,(t,n)=>{i+=t.length+e(n)}),i;default:throw S(13486,{value:t})}}(e.data.value)),t}Sr(e,t,n){return ev.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.gi.get(t);return ev.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class sM{constructor(e){this.serializer=e}q(e,t,n,r){let i=new eb("createOrUpgrade",t);n<1&&r>=1&&(!function(e){e.createObjectStore(eB)}(e),e.createObjectStore(e$,{keyPath:"userId"}),e.createObjectStore(eK,{keyPath:ej,autoIncrement:!0}).createIndex(eG,eQ,{unique:!0}),e.createObjectStore(eH),sL(e),function(e){e.createObjectStore(eq)}(e));let s=ev.resolve();return n<3&&r>=3&&(0!==n&&(e.deleteObjectStore(e8),e.deleteObjectStore(e4),e.deleteObjectStore(tn),sL(e)),s=s.next(()=>(function(e){let t=e.store(tn),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ea.min().toTimestamp(),targetCount:0};return t.put(tt,n)})(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>i.store(eK).j().next(t=>{e.deleteObjectStore(eK),e.createObjectStore(eK,{keyPath:ej,autoIncrement:!0}).createIndex(eG,eQ,{unique:!0});let n=i.store(eK),r=t.map(e=>n.put(e));return ev.waitFor(r)}))),s=s.next(()=>{!function(e){e.createObjectStore(ts,{keyPath:"clientId"})}(e)})),n<5&&r>=5&&(s=s.next(()=>this.pi(i))),n<6&&r>=6&&(s=s.next(()=>((function(e){e.createObjectStore(e2)})(e),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(()=>{(function(e){e.createObjectStore(ta,{keyPath:"bundleId"})})(e),function(e){e.createObjectStore(to,{keyPath:"name"})}(e)})),n<12&&r>=12&&(s=s.next(()=>{let t=e.createObjectStore(tw,{keyPath:tv});t.createIndex(tI,tb,{unique:!1}),t.createIndex(tT,tE,{unique:!1})})),n<13&&r>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore(eX,{keyPath:eY});t.createIndex(eJ,eZ),t.createIndex(e0,e1)})(e)).next(()=>this.Di(e,i)).next(()=>e.deleteObjectStore(eq))),n<14&&r>=14&&(s=s.next(()=>this.Ci(e,i))),n<15&&r>=15&&(s=s.next(()=>{e.createObjectStore(tl,{keyPath:"indexId",autoIncrement:!0}).createIndex(tu,"collectionGroup",{unique:!1}),e.createObjectStore(th,{keyPath:tc}).createIndex(td,tf,{unique:!1}),e.createObjectStore(tm,{keyPath:tg}).createIndex(tp,ty,{unique:!1})})),n<16&&r>=16&&(s=s.next(()=>{t.objectStore(th).clear()}).next(()=>{t.objectStore(tm).clear()})),n<17&&r>=17&&(s=s.next(()=>{!function(e){e.createObjectStore(t_,{keyPath:"name"})}(e)})),n<18&&r>=18&&(0,h.Ov)()&&(s=s.next(()=>{t.objectStore(th).clear()}).next(()=>{t.objectStore(tm).clear()}
6)),s}yi(e){let t=0;return e.store(eq).X((e,n)=>{t+=sn(n)}).next(()=>{let n={byteSize:t};return e.store(e2).put(e5,n)})}pi(e){let t=e.store(e$),n=e.store(eK);return t.j().next(t=>ev.forEach(t,t=>{let r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.j(eG,r).next(n=>ev.forEach(n,n=>{D(n.userId===t.userId,18650,"Cannot process batch from unexpected user",{batchId:n.batchId});let r=iC(this.serializer,n);return st(e,t.userId,r).next(()=>{})}))}))}wi(e){let t=e.store(e8),n=e.store(eq);return e.store(tn).get(tt).next(e=>{let r=[];return n.X((n,i)=>{let s=new Q(n),a=[0,eL(s)];r.push(t.get(a).next(n=>n?ev.resolve():t.put({targetId:0,path:eL(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>ev.waitFor(r))})}Si(e,t){e.createObjectStore(tr,{keyPath:ti});let n=t.store(tr),r=new i4,i=e=>{if(r.add(e)){let t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:eL(r)})}};return t.store(eq).X({Z:!0},(e,t)=>i(new Q(e).popLast())).next(()=>t.store(eH).X({Z:!0},([e,t,n],r)=>i(eU(t).popLast())))}bi(e){let t=e.store(e4);return t.X((e,n)=>{let r=ik(n),i=iA(this.serializer,r);return t.put(i)})}Di(e,t){let n=t.store(eq),r=[];return n.X((e,n)=>{let i=t.store(eX),s=(n.document?new X(Q.fromString(n.document.name).popFirst(5)):n.noDocument?X.fromSegments(n.noDocument.path):n.unknownDocument?X.fromSegments(n.unknownDocument.path):S(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(()=>ev.waitFor(r))}Ci(e,t){let n=t.store(eK),r=new sy(this.serializer),i=new sR(sF.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))&&void 0!==t?t:rl();iC(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),ev.forEach(n,(e,n)=>{let s=new y(n),a=iM.yt(this.serializer,s),o=i.getIndexManager(s);return new sE(r,sr.yt(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new tk(t,eO.ue),e).next()})})}}function sL(e){e.createObjectStore(e8,{keyPath:e9}).createIndex(e7,te,{unique:!0}),e.createObjectStore(e4,{keyPath:"targetId"}).createIndex(e3,e6,{unique:!0}),e.createObjectStore(tn)}let sU="IndexedDbPersistence",sq="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class sB{constructor(e,t,n,r,i,s,a,o,l,u,h=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=h,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=Number.NEGATIVE_INFINITY,this.qi=e=>Promise.resolve(),!sB.C())throw new C(N.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new sm(this,r),this.Qi=t+"main",this.serializer=new i_(o),this.$i=new eT(this.Qi,this.Oi,new sM(this.serializer)),this.li=new iL,this.hi=new so(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new sy(this.serializer),this.Ti=new iP,this.window&&this.window.localStorage?this.Ui=this.window.localStorage:(this.Ui=null,!1===u&&T(sU,"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 C(N.FAILED_PRECONDITION,sq);return this.Wi(),this.Gi(),this.zi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.hi.getHighestSequenceNumber(e))}).then(e=>{this.ui=new eO(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=>tA(e,ts).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(ex(e))return b(sU,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return b(sU,"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 tA(e,eB).get(ez).next(e=>ev.resolve(this.Xi(e)))}es(e){return tA(e,ts).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=tA(e,ts);return t.j().next(e=>{let n=this.rs(e,18e5),r=e.filter(e=>-1===n.indexOf(e));return ev.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?ev.resolve(!0):tA(e,eB).get(ez).next(t=>
6{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 C(N.FAILED_PRECONDITION,sq);return!1}}return!(!this.networkEnabled||!this.inForeground)||tA(e,ts).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&&b(sU,`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",[eB,ts],e=>{let t=new tk(e,eO.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=>tA(e,ts).j().next(e=>this.rs(e,18e5).map(e=>e.clientId)))}get started(){return this.ci}getGlobalsCache(){return this.li}getMutationQueue(e,t){return sr.yt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.hi}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new i8(e,this.serializer.gt.databaseId)}getDocumentOverlayCache(e){return iM.yt(this.serializer,e)}getBundleCache(){return this.Ti}runTransaction(e,t,n){var r;let i;b(sU,"Starting transaction:",e);let s=18===(r=this.Oi)?tC:17===r?tC:16===r?tN:15===r?tN:14===r?tD:13===r?tD:12===r?tx:11===r?tS:void S(60245);return this.$i.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,r=>(i=new tk(r,this.ui?this.ui.next():eO.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 C(N.FAILED_PRECONDITION,ep);return n(i)}).next(e=>this.Zi(i).next(()=>e)):this.Ts(i).next(()=>n(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Ts(e){return tA(e,eB).get(ez).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 C(N.FAILED_PRECONDITION,sq)})}Zi(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return tA(e,eB).put(ez,t)}static C(){return eT.C()}Yi(e){let t=tA(e,eB);return t.get(ez).next(e=>
6this.Xi(e)?(b(sU,"Releasing primary lease."),t.delete(ez)):ev.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?void 0:e.addEventListener)&&(this.Ni=()=>{this.us();let e=/(?:Version|Mobile)\/1[456]/;(0,h.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?void 0:t.getItem(this.ss(e)));return b(sU,`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return T(sU,"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 sz(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class s${constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Is=n,this.ds=r}static Es(e,t){let n=rl(),r=rl();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 s$(e,t.fromCache,n,r)}}class sK{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class sj{constructor(){this.As=!1,this.Rs=!1,this.Vs=100,this.fs=(0,h.nr)()?8:eE((0,h.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 sK;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?(I()<=u.$b.DEBUG&&b("QueryEngine","SDK will not create cache indexes for query:",n6(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),ev.resolve()):(I()<=u.$b.DEBUG&&b("QueryEngine","Query:",n6(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.fs*r?(I()<=u.$b.DEBUG&&b("QueryEngine","The SDK decides to create cache indexes for query:",n6(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,n0(t))):ev.resolve())}ps(e,t){if(nY(t))return ev.resolve(null);let n=n0(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=n0(t=n5(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let i=rl(...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,n5(t,null,"F")):this.vs(e,s,t,n)}))})))}ys(e,t,n,r){return nY(t)||r.isEqual(ea.min())?ev.resolve(null):this.gs.getDocuments(e,n).next(i=>{let s=this.bs(t,i);return this.Ds(t,s,n,r)?ev.resolve(null):(I()<=u.$b.DEBUG&&b("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),n6(t)),this.vs(e,s,t,ed(r,-1)).next(e=>e))})}bs(e,t){let n=new tL(n7(e));return t.forEach((t,r)=>{n8(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 I()<=u.$b.DEBUG&&b("QueryEngine","Using full collection scan to execute query:",n6(t)),this.gs.getDocumentsMatchingQuery(e,t,em.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 sG="LocalStore";class sQ{constructor(e,t,n,r){this.persistence=e,this.Cs=t,this.serializer
6=r,this.Fs=new tF(B),this.Ms=new re(e=>n$(e),nK),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 sE(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 sW(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=rl();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 sH(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.hi.getLastRemoteSnapshotVersion(t))}function sX(e,t,n){let r=rl(),i=rl();return n.forEach(e=>r=r.add(e)),t.getEntries(e,r).next(e=>{let r=rt;return n.forEach((n,s)=>{let a=e.get(n);s.isFoundDocument()!==a.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(ea.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)):b(sG,"Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",s.version)}),{Ls:r,ks:i}})}function sY(e,t){return e.persistence.runTransaction("Allocate target","readwrite",n=>{let r;return e.hi.getTargetData(n,t).next(i=>i?(r=i,ev.resolve(r)):e.hi.allocateTargetId(n).next(i=>(r=new iE(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 sJ(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(!ex(e))throw e;b(sG,`Failed to update sequence numbers for target ${t}: ${e}`)}e.Fs=e.Fs.remove(t),e.Ms.delete(r.target)}function sZ(e,t,n){let r=ea.min(),i=rl();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,n){let r=e.Ms.get(n);return void 0!==r?ev.resolve(e.Fs.get(r)):e.hi.getTargetData(t,n)})(e,s,n0(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:ea.min(),n?i:rl())).next(n=>(s2(e,n9(t),n),{documents:n,qs:i})))}function s0(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 s1(e,t){let n=e.xs.get(t)||ea.min();return e.persistence.runTransaction("Get new document changes","readonly",r=>e.Os.getAllFromCollectionGroup(r,t,ed(n,-1),Number.MAX_SAFE_INTEGER)).then(n=>(s2(e,t,n),n))}function s2(e,t,n){let r=e.xs.get(t)||ea.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.xs.set(t,r)}async function s5(e,t,n,r){let i=rl(),s=rt;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 sY(e,n0(nX(Q.fromString(`__bundle__/docs/${r}`))));return e.persistence.runTransaction("Apply bundle documents","readwrite",t=>sX(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 s4(e,t,n=rl()){let r=await sY(e,n0(iV(t.bundledQuery)));return e.persistence.runTransaction("Save named query","readwrite",i=>{let s=it(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return e.Ti.saveNamedQuery(i,t);let a=r.withResumeToken(t$.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 s3="firestore_clients";function s6(e,t){return`${s3}_${e}_${t}`}let s8="firestore_mutations";function s9(e,t,n){let r=`${s8}_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}let s7="firestore_targets";function ae(e,t){return`${s7}_${e}_${t}`}
6let at="SharedClientState";class an{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 C(r.error.code,r.error.message)),s?new an(e,t,r.state,i):(T(at,`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 ar{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 C(n.error.code,n.error.message)),i?new ar(e,n.state,r):(T(at,`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 ai{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=ru;for(let e=0;r&&e<n.activeTargetIds.length;++e)r=eM(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new ai(e,i):(T(at,`Failed to parse client data for instance '${e}': ${t}`),null)}}class as{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 as(t.clientId,t.onlineState):(T(at,`Failed to parse online state: ${e}`),null)}}class aa{constructor(){this.activeTargetIds=ru}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 ao{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 tF(B),this.started=!1,this.Zs=[];let l=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Xs=s6(this.persistenceKey,this.js),this.eo=(s=this.persistenceKey,`firestore_sequence_number_${s}`),this.Ys=this.Ys.insert(this.js,new aa),this.no=RegExp(`^${s3}_${l}_([^_]*)$`),this.ro=RegExp(`^${s8}_${l}_(\\d+)(?:_(.*))?$`),this.io=RegExp(`^${s7}_${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(s6(this.persistenceKey,e));if(t){let n=ai.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;return 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(ae(this.persistenceKey,e));if(t){let r=ar.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(ae(this.persistenceKey,e))}updateQueryState(e,t,n){this.To(e,t,n)}
6handleUserChange(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 b(at,"READ",e,t),t}setItem(e,t){b(at,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){b(at,"REMOVE",e),this.storage.removeItem(e)}Hs(e){if(e.storageArea===this.storage){if(b(at,"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=eO.ue;if(null!=e)try{let n=JSON.parse(e);D("number"==typeof n,30636,{wo:e}),t=n}catch(e){T(at,"Failed to read sequence number from WebStorage",e)}return t}(e.newValue);t!==eO.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 an(this.currentUser,e,t,n),i=s9(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Ws())}ho(e){let t=s9(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=ae(this.persistenceKey,e),i=new ar(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 ai.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 an.Ks(new y(i),r,t)}po(e,t){let n=Number(this.io.exec(e)[1]);return ar.Ks(n,t)}ao(e){return as.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);b(at,`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=ru;return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class al{constructor(){this.Fo=new aa,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 aa,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class au{xo(e){}shutdown(){}}let ah="ConnectivityMonitor";class ac{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(b(ah,"Network connectivity changed: AVAILABLE"),this.ko))e(0)}Lo(){for(let e of(b(ah,"Network connectivity changed: UNAVAILABLE"),this.ko))e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let ad=null;function af(){return null===ad?ad=0x10000000+Math.round(0x80000000*Math.random()):ad++,"0x"+ad.toString(16)}let am="RestConnection",ag={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
6Query:"runAggregationQuery"};class ap{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===t2?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Wo(e,t,n,r,i){let s=af(),a=this.Go(e,t.toUriEncodedString());b(am,`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,h.zJ)(l);return this.jo(e,a,o,n,u).then(t=>(b(am,`Received RPC '${e}' ${s}: `,t),t),t=>{throw E(am,`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=ag[e];return`${this.$o}/v1/${t}:${n}`}terminate(){}}class ay{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 aw="WebChannelConnection";class av extends ap{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=af();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();b(aw,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case d.O4.TIMEOUT:b(aw,`RPC '${e}' ${s} timed out`),a(new C(N.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(b(aw,`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(N).indexOf(t)>=0?t:N.UNKNOWN}(t.status);a(new C(e,t.message))}else a(new C(N.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new C(N.UNAVAILABLE,"Connection failed."));break;default:S(9055,{c_:e,streamId:s,l_:o.getLastErrorCode(),h_:o.getLastError()})}}finally{b(aw,`RPC '${e}' ${s} completed.`)}});let l=JSON.stringify(r);b(aw,`RPC '${e}' ${s} sending request:`,r),o.send(t,"POST",l,n,15)})}P_(e,t,n){let i=af(),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 h=s.join("");b(aw,`Creating RPC '${e}' stream ${i}: ${h}`,l);let c=a.createWebChannel(h,l);this.T_(c);let f=!1,m=!1,g=new ay({Ho:t=>{m?b(aw,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(f||(b(aw,`Opening RPC '${e}' stream ${i} transport.`),c.open(),f=!0),b(aw,`RPC '${e}' stream ${i} sending:`,t),c.send(t))},Yo:()=>c.close()}),p=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return p(c,d.iO.EventType.OPEN,()=>{m||(b(aw,`RPC '${e}' stream ${i} transport opened.`),g.s_())}),p(c,d.iO.EventType.CLOSE,()=>{m||(m=!0,b(aw,`RPC '${e}' stream ${i} transport closed`),g.__(),this.I_(c))}),p(c,d.iO.EventType.ERROR,t=>{m||(m=!0,E(aw,`RPC '${e}' stream ${i} transport errored. Name:`,t.name,"Message:",t.message),g.__(new C(N.UNAVAILABLE,"The operation could not be completed")))}),p(c,d.iO.EventType.MESSAGE,t=>{var n;if(!m){let s=t.data[0];D(!!s,16349);let a=(null==s?void 0:s.error)||(null===(n=s[0])||void 0===n?void 0:n.error);if(a){b(aw,`RPC '${e}' stream ${i} received error:`,a);let t=a.status,n=function(e){let t=r[e];if(void 0!==t)return r$(t)}(t),s=a.message;void 0===n&&(n=N.INTERNAL,s="Unknown error status: "+t+" with message "+a.message),m=!0,g.__(new C(n,s)),c.close()}else b(aw,`RPC '${e}' stream ${i}
6 received:`,s),g.a_(s)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?b(aw,`RPC '${e}' stream ${i} detected buffering proxy`):t.stat===d.ro.NOPROXY&&b(aw,`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 aI(){return"undefined"!=typeof window?window:null}function ab(){return"undefined"!=typeof document?document:null}function aT(e){return new r8(e,!0)}class aE{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&&b("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 a_="PersistentStream";class aS{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 aE(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===N.RESOURCE_EXHAUSTED?(T(t.toString()),T("Using maximum backoff delay to prevent overloading the backend."),this.F_.f_()):t&&t.code===N.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 C(N.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 b(a_,`close with error: ${e}`),this.stream=null,this.close(4,e)}K_(e){return t=>{this.Fi.enqueueAndForget(()=>this.b_===e?t():(b(a_,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class ax extends aS{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:S(39313,{state:r}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(D(void 0===i||"string"==typeof i,58123),t$.fromBase64String(i||"")):(D(void 0===i||i instanceof m||i instanceof Uint8Array,16193),t$.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;n=new rZ(s,a,o,l&&new C(void 0===l.code?N.UNKNOWN:r$(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=io(e,r.document.name),s=it(r.document.updateTime),a=r.document.createTime?it(r.document.createTime):ea.min(),o=new nv({mapValue:{fields:r.document.fields}}),l=nI.newFoundDocument(i,s,a,o);n=new rY(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let i=io(e,r.document),s=r.readTime?it(r.readTime):ea.min(),a=nI.newNoDocument(i,s);n=new rY([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let i=io(e,r.document);n=new rY([],r.removedTargetIds||[],i,null)}else{if(!("filter"in t))return S(11601,{At:t});{t.filter;let e=t.filter;e.targetId;
6let{count:r=0,unchangedNames:i}=e,s=new rB(r,i);n=new rJ(e.targetId,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ea.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?ea.min():t.readTime?it(t.readTime):ea.min()}(e);return this.listener.J_(t,n)}H_(e){let t={};t.database=ih(this.serializer),t.addTarget=function(e,t){let n,r=t.target;if((n=nj(r)?{documents:iy(e,r)}:{query:iw(e,r).Vt}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=ie(e,t.resumeToken);let r=r9(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(ea.min())>0){n.readTime=r7(e,t.snapshotVersion.toTimestamp());let r=r9(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);let n=function(e,t){let n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return S(28987,{purpose:e})}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.k_(t)}Y_(e){let t={};t.database=ih(this.serializer),t.removeTarget=e,this.k_(t)}}class aD extends aS{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 D(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,D(!e.writeResults||0===e.writeResults.length,55816),this.listener.ea()}onNext(e){var t,n;D(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.F_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(D(void 0!==n,14353),t.map(e=>{let t;return(t=e.updateTime?it(e.updateTime):it(n)).isEqual(ea.min())&&(t=it(n)),new r_(t,e.transformResults||[])})):[]),i=it(e.commitTime);return this.listener.ta(i,r)}na(){let e={};e.database=ih(this.serializer),this.k_(e)}X_(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>ig(this.serializer,e))};this.k_(t)}}class aN{}class aC extends aN{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 C(N.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,ii(t,n),r,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===N.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new C(N.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,ii(t,n),r,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===N.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new C(N.UNKNOWN,e.toString())})}terminate(){this.ra=!0,this.connection.terminate()}}class ak{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):b("OnlineStateTracker",t)}ha(){null!==this.oa&&(this.oa.cancel(),this.oa=null)}}let aA="RemoteStore";class aV{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{aB(this)&&(b(aA,"Restarting streams for network reachability change."),await async function(e){e.Ia.add(4),await aO(e),e.Aa.set("Unknown"),e.Ia.delete(4),await aR(e)}(this))})}),this.Aa=new ak(n,r)}}async function aR(e){if(aB(e))for(let t of e.da)await t(!0)}async function aO(e){for(let t of e.da)await t(!1)}function aF(e,t){e.Ta.has(t.targetId)||(e.Ta.set(t.targetId,t),aq(e)?aU(e):a5(e).x_()&&aM(e,t))}function aP(e,t){let n=a5(e);e.Ta.delete(t),n.x_()&&aL(e,t),0===e.Ta.size&&(n.x_()?n.B_():aB(e)&&e.Aa.set("Unknown"))}function aM(e,t){if(e.Ra.$e(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(ea.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}a5(e).H_(t)}function aL(e,t){e.Ra.$e(t),a5(e).Y_(t)}function aU(e){e.Ra=new r1({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Et:t=>e.Ta.get(t)||null,lt:()=>e.datastore.serializer.databaseId}),a5(e).start(),e.Aa.aa()}function aq(e){return aB(e)&&!a5(e).M_()&&e.Ta.size>0}function aB(e){return 0===e.Ia.size}async function az(e){e.Aa.set("Online")}async function a$(e){e.Ta.forEach((t,n)=>{aM(e,t)})}async function aK(e,t){e.Ra=void 0,aq(e)?(e.Aa.la(t),aU(e)):e.Aa.set("Unknown")}async function aj(e,t,n){if(e.Aa.set("Online"),t instanceof rZ&&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){b(aA,"Failed to remove targets %s: %s ",t.targetIds.join(","),n),await aG(e,n)}else if(t instanceof rY?e.Ra.Ye(t):t instanceof rJ?e.Ra.it(t):e.Ra.et(t),!n.isEqual(ea.min()))try{let t=await sH(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(t$.EMPTY_BYTE_STRING,r.snapshotVersion)),aL(e,t);let i=new iE(r.target,t,n,r.sequenceNumber);aM(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){b(aA,"Failed to raise snapshot:",t),await aG(e,t)}}async function aG(e,t,n){if(!ex(t))throw t;e.Ia.add(1),await aO(e),e.Aa.set("Offline"),n||(n=()=>sH(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{b(aA,"Retrying IndexedDB access"),await n(),e.Ia.delete(1),await aR(e)})}function aQ(e,t){return t().catch(n=>aG(e,n,t))}async function aW(e){var t;let n=a4(e),r=e.Pa.length>0?e.Pa[e.Pa.length-1].batchId:-1;for(;aB(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=a4(e);n.x_()&&n.Z_&&n.X_(t.mutations)}(e,t)}catch(t){await aG(e,t)}aH(e)&&aX(e)}function aH(e){return aB(e)&&!a4(e).M_()&&e.Pa.length>0}function aX(e){a4(e).start()}async function aY(e){a4(e).na()}async function aJ(e){let t=a4(e);for(let n of e.Pa)t.X_(n.mutations)}async function aZ(e,t,n){let r=e.Pa.shift(),i=rU.from(r,t,n);await aQ(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await aW(e)}async function a0(e,t){t&&a4(e).Z_&&await async function(e,t){var n;if(rz(n=t.code)&&n!==N.ABORTED){let n=e.Pa.shift();a4(e).N_(),await aQ(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await aW(e)}}(e,t),aH(e)&&aX(e)}async function a1(e,t){e.asyncQueue.verifyOperationInProgress(),b(aA,"RemoteStore received new credentials");let n=aB(e);e.Ia.add(3),await aO(e),n&&e.Aa.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.Ia.delete(3),await aR(e)}async function a2(e,t){t?(e.Ia.delete(2),await aR(e)):t||(e.Ia.add(2),await aO(e),e.Aa.set("Unknown"))}function a5(e){var t,n,r;return e.Va||(t=e.datastore,n=e.asyncQueue,r={Zo:az.bind(null,e),e_:a$.bind(null,e),n_:aK.bind(null,e),J_:aj.bind(null,e)},t.ia(),e.Va=new ax(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.Va.N_(),aq(e)?aU(e):e.Aa.set("Unknown")):(await e.Va.stop(),e.Ra=void 0)})),e.Va}function a4(e){var t,n,r;return e.ma||(t=e.datastore,n=e.asyncQueue,r={Zo:()=>Promise.resolve(),e_:aY.bind(null,e),n_:a0.bind(null,e),ea:aJ.bind(null,e),ta:aZ.bind(null,e)},t.ia(),e.ma=new aD(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.ma.N_(),await aW(e)):(await e.ma.stop(),e.Pa.length>0&&(b(aA,`Stopping write stream with ${e.Pa.length} pending writes`),e.Pa=[]))})),e.ma}class a3{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new k,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 a3(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 C(N.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 a6(e,t){if(T("AsyncQueue",`${t}: ${e}`),ex(e))return new C(N.UNAVAILABLE,`${t}: ${e}`);throw e}class a8{static emptySet(e){return new a8(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||X.comparator(t.key,n.key):(e,t)=>X.comparator(e.key,t.key),this.keyedMap=rr(),this.sortedSet=new tF(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 a8)||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 a8;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class a9{constructor(){this.fa=new tF(X.comparator)}track(e){let t=e.doc.key,n=this.fa.get(t);n?0!==e.type&&3===n.type?this.fa=this.fa.insert(t,e):3===e.type&&1!==n.type?this.fa=this.fa.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.fa=this.fa.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.fa=this.fa.remove(t):1===e.type&&2===n.type?this.fa=this.fa.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):S(63341,{At:e,ga:n}):this.fa=this.fa.insert(t,e)}pa(){let e=[];return this.fa.inorderTraversal((t,n)=>{e.push(n)}),e}}class a7{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 a7(e,t,a8.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)&&n4(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 oe{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some(e=>e.ba())}}class ot{constructor(){this.queries=on(),this.onlineState="Unknown",this.Da=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=on(),n.forEach((e,n)=>{for(let e of n.wa)e.onError(t)})}(this,new C(N.ABORTED,"Firestore shutting down"))}}function on(){return new re(e=>n3(e),n4)}async function or(e,t){let n=3,r=t.query,i=e.queries.get(r);i?!i.Sa()&&t.ba()&&(n=2):(i=new oe,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=a6(n,`Initialization of query '${n6(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)&&oo(e)}async function oi(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 os(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&&oo(e)}function oa(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 oo(e){e.Da.forEach(e=>{e.next()})}(a=s||(s={})).Fa="default",a.Cache="cache";class ol{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 a7(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=a7.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 ou{constructor(e,t){this.qa=e,this.byteLength=t}Qa(){return"metadata"in this.qa}}class oh{constructor(e){this.serializer=e}Qs(e){return io(this.serializer,e)}$s(e){return e.metadata.exists?im(this.serializer,e.document,!1):nI.newNoDocument(this.Qs(e.metadata.name),this.Us(e.metadata.readTime))}Us(e){return it(e)}}class oc{constructor(e,t){this.$a=e,this.serializer=t,this.Ua=[],this.Ka=[],this.collectionGroups=new Set,this.progress=od(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=Q.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 oh(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)||rl()).add(e);t.set(n,r)}}return t}async za(e){let t=await s5(e,new oh(this.serializer),this.Ka,this.$a.id),n=this.Ga(this.documents);for(let t of this.Ua)await s4(e,t,n.get(t.name));return this.progress.taskState="Success",{progress:this.progress,ja:this.collectionGroups,Ja:t}}}function od(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class of{constructor(e){this.key=e}}class om{constructor(e){this.key=e}}class og{constructor(e,t){this.query=e,this.Ha=t,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=rl(),this.mutatedKeys=rl(),this.Xa=n7(e),this.eu=new a8(this.Xa)}get tu(){return this.Ha}nu(e,t){let n=t?t.ru:new a9,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),h=n8(this.query,t)?t:null,c=!!u&&this.mutatedKeys.has(u.key),d=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations),f=!1;u&&h?u.data.isEqual(h.data)?c!==d&&(n.track({type:3,doc:h}),f=!0):this.iu(u,h)||(n.track({type:2,doc:h}),f=!0,(o&&this.Xa(h,o)>0||l&&0>this.Xa(h,l))&&(a=!0)):!u&&h?(n.track({type:0,doc:h}),f=!0):u&&!h&&(n.track({type:1,doc:u}),f=!0,(o||l)&&(a=!0)),f&&(h?(s=s.add(h),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;){let e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{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 S(20277,{At:e})}};return n(e)-n(t)})(e.type,t.type)||this.Xa(e.doc,t.doc)),this.su(n),r=null!=r&&r;let a=t&&!r?this.ou():[],o=0===this.Za.size&&this.current&&!r?1:0,l=o!==this.Ya;return(this.Ya=o,0!==s.length||l)?{snapshot:new a7(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 a9,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=rl(),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 om(e))}
7),this.Za.forEach(n=>{e.has(n)||t.push(new of(n))}),t}uu(e){this.Ha=e.qs,this.Za=rl();let t=this.nu(e.documents);return this.applyChanges(t,!0)}cu(){return a7.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,0===this.Ya,this.hasCachedResults)}}let op="SyncEngine";class oy{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class ow{constructor(e){this.key=e,this.lu=!1}}class ov{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 re(e=>n3(e),n4),this.Tu=new Map,this.Iu=new Set,this.du=new tF(X.comparator),this.Eu=new Map,this.Au=new sD,this.Ru={},this.Vu=new Map,this.mu=sa.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return!0===this.fu}}async function oI(e,t,n=!0){let r,i=oX(e),s=i.Pu.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),r=s.view.cu()):r=await oT(i,t,n,!0),r}async function ob(e,t){let n=oX(e);await oT(n,t,!0,!1)}async function oT(e,t,n,r){let i,s=await sY(e.localStore,n0(t)),a=s.targetId,o=e.sharedCl
7ientState.addLocalQueryTarget(a,n);return r&&(i=await oE(e,t,a,"current"===o,s.resumeToken)),e.isPrimaryClient&&n&&aF(e.remoteStore,s),i}async function oE(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 sZ(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 oP(e,t.targetId,o._u),o.snapshot})(e,t,n,r);let s=await sZ(e.localStore,t,!0),a=new og(t,s.qs),o=a.nu(s.documents),l=rX.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);oP(e,n,u._u);let h=new oy(t,n,a);return e.Pu.set(t,h),e.Tu.has(n)?e.Tu.get(n).push(t):e.Tu.set(n,[t]),u.snapshot}async function o_(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=>!n4(e,t))),void e.Pu.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(r.targetId),e.sharedClientState.isActiveQueryTarget(r.targetId)||await sJ(e.localStore,r.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(r.targetId),n&&aP(e.remoteStore,r.targetId),oO(e,r.targetId)}).catch(ew)):(oO(e,r.targetId),await sJ(e.localStore,r.targetId,!0))}async function oS(e,t){let n=e.Pu.get(t),r=e.Tu.get(n.targetId);e.isPrimaryClient&&1===r.length&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),aP(e.remoteStore,n.targetId))}async function ox(e,t,n){let r=oY(e);try{var i;let e,s=await function(e,t){let n,r,i=es.now(),s=t.reduce((e,t)=>e.add(t.key),rl());return e.persistence.runTransaction("Locally write mutations","readwrite",a=>{let o=rt,l=rl();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=rm(r.transform,e||null);null!=i&&(null===n&&(n=nv.empty()),n.set(r.field,i))}return n||null}(e,n.get(e.key).overlayedDocument);null!=t&&s.push(new rV(e.key,t,function e(t){let n=[];return tR(t.fields,(t,r)=>{let i=new H([t]);if(nd(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 tB(n)}(t.value.mapValue),rS.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:ri(n)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(s.batchId),i=s.batchId,(e=r.Ru[r.currentUser.toKey()])||(e=new tF(B)),e=e.insert(i,n),r.Ru[r.currentUser.toKey()]=e,await oL(r,s.changes),await aW(r.remoteStore)}catch(t){let e=a6(t,"Failed to persist write");n.reject(e)}}async function oD(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 h=u.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(o)?h=h.withResumeToken(t$.EMPTY_BYTE_STRING,ea.min()).withLastLimboFreeSnapshotVersion(ea.min()):s.resumeToken.approximateByteSize()>0&&(h=h.withResumeToken(s.resumeToken,n)),r=r.insert(o,h),l=h,(0===u.resumeToken.approximateByteSize()||l.snapshotVersion.toMicroseconds()-u.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&a.push(e.hi.updateTargetData(i,h))});let o=rt,l=rl();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&a.push(e.persistence.referenceDelegate.updateLimboDocument(i,n))}),a.push(sX(i,s,t.documentUpdates).next(e=>{o=e.Ls,l=e.ks})),!n.isEqual(ea.min())){let t=e.hi.getLastRemoteSnapshotVersion(i).next(t=>e.hi.setTargetsMetadata(i,i.currentSequenceNumber,n));a.push(t)}return ev.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&&(D(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?r.lu=!0:t.modifiedDocuments.size>0?D(r.lu,14607):t.removedDocuments.size>0&&(D(r.lu,42227),r.lu=!1))}),await oL(e,n,t)}catch(e){await ew(e)}}function oN(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&&oo(r),i.length&&e.hu.J_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function oC(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Eu.get(t),i=r&&r.key;if(i){let n=new tF(X.comparator);n=n.insert(i,nI.newNoDocument(i,ea.min()));let r=rl().add(i),s=new rH(ea.min(),new Map,new tF(B),n,r);await oD(e,s),e.du=e.du.remove(i),e.Eu.delete(t),oM(e)}else await sJ(e.localStore,t,!1).then(()=>oO(e,t,n)).catch(ew)}async function ok(e,t){var n;let r=t.batch.batchId;try{let i=await (n=e.localStore).persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),i=n.Os.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let i=n.batch,s=i.keys(),a=ev.resolve();return s.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let s=n.docVersions.get(e);D(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=rl();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))});oR(e,r,null),oV(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await oL(e,i)}catch(e){await ew(e)}}async function oA(e,t,n){var r;try{let i=await (r=e.localStore).persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(D(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))});oR(e,t,n),oV(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await oL(e,i)}catch(e){await ew(e)}}function oV(e,t){(e.Vu.get(t)||[]).forEach(e=>{e.resolve()}),e.Vu.delete(t)}function oR(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 oO(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)||oF(e,t)})}function oF(e,t){e.Iu.delete(t.path.canonicalString());let n=e.du.get(t);null!==n&&(aP(e.remoteStore,n),e.du=e.du.remove(t),e.Eu.delete(n),oM(e))}function oP(e,t,n){for(let r of n)r instanceof of?(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)||(b(op,"New document in limbo: "+n),e.Iu.add(r),oM(e))}(e,r)):r instanceof om?(b(op,"Document no longer in limbo: "+r.key),e.Au.removeReference(r.key,t),e.Au.containsKey(r.key)||oF(e,r.key)):S(19791,{yu:r})}function oM(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 X(Q.fromString(t)),r=e.mu.next();e.Eu.set(r,new ow(n)),e.du=e.du.insert(n,r),aF(e.remoteStore,new iE(n0(nX(n.path)),r,"TargetPurposeLimboResolution",eO.ue))}}async function oL(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?void 0:s.current;
7e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=s$.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=>ev.forEach(t,t=>ev.forEach(t.Is,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>ev.forEach(t.ds,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!ex(e))throw e;b(sG,"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 oU(e,t){if(!e.currentUser.isEqual(t)){b(op,"User change. New user:",t.toKey());let n=await sW(e.localStore,t);e.currentUser=t,e.Vu.forEach(e=>{e.forEach(e=>{e.reject(new C(N.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Vu.clear(),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await oL(e,n.Bs)}}function oq(e,t){let n=e.Eu.get(t);if(n&&n.lu)return rl().add(n.key);{let n=rl(),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 oB(e,t){let n=await sZ(e.localStore,t.query,!0),r=t.view.uu(n);return e.isPrimaryClient&&oP(e,t.targetId,r._u),r}async function oz(e,t){return s1(e.localStore,t).then(t=>oL(e,t))}async function o$(e,t,n,r){let i=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):ev.resolve(null)))}(e.localStore,t);null!==i?("pending"===n?await aW(e.remoteStore):"acknowledged"===n||"rejected"===n?(oR(e,t,r||null),oV(e,t),function(e,t){e.mutationQueue.rr(t)}(e.localStore,t)):S(6720,"Unknown batchState",{wu:n}),await oL(e,i)):b(op,"Cannot apply mutation batch with id: "+t)}async function oK(e,t){if(oX(e),oY(e),!0===t&&!0!==e.fu){let t=e.sharedClientState.getAllActiveQueryTargets(),n=await oj(e,t.toArray());for(let t of(e.fu=!0,await a2(e.remoteStore,!0),n))aF(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(()=>(oO(e,i),sJ(e.localStore,i,!0))),aP(e.remoteStore,i)}),await n,await oj(e,t),e.Eu.forEach((t,n)=>{aP(e.remoteStore,n)}),e.Au.jr(),e.Eu=new Map,e.du=new tF(X.comparator),e.fu=!1,await a2(e.remoteStore,!1)}}async function oj(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 sY(e.localStore,n0(s[0])),s)){let t=e.Pu.get(n),r=await oB(e,t);r.snapshot&&i.push(r.snapshot)}else{let r=await s0(e.localStore,n);t=await sY(e.localStore,r),await oE(e,oG(r),n,!1,t.resumeToken)}r.push(t)}return e.hu.J_(i),r}function oG(e){var t,n,r,i,s;return t=e.path,n=e.collectionGroup,r=e.orderBy,i=e.filters,s=e.limit,new nH(t,n,r,i,s,"F",e.startAt,e.endAt)}function oQ(e){return e.localStore.persistence.Ps()}async function oW(e,t,n,r){if(e.fu)return void b(op,"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 s1(e.localStore,n9(i[0])),s=rH.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,t$.EMPTY_BYTE_STRING);await oL(e,r,s);break}case"rejected":await sJ(e.localStore,t,!0),oO(e,t,r);break;default:S(64155,n)}}async function oH(e,t,n){let r=oX(e);if(r.fu){for(let e of t){if(r.Tu.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){b(op,"Adding an already active target "+e);continue}let t=await s0(r.localStore,e),n=await sY(r.localStore,t);await oE(r,oG(t),n.targetId,!1,n.resumeToken),aF(r.remoteStore,n)}for(let e of n)r.Tu.has(e)&&await sJ(r.localStore,e,!1).then(()=>{aP(r.remoteStore,e),oO(r,e)}).catch(ew)}}function oX(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=oD.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=oq.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=oC.bind(null,e),e.hu.J_=os.bind(null,e.eventManager),e.hu.pu=oa.bind(null,e.eventManager),e}function oY(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=ok.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=oA.bind(null,e),e}class oJ{constructor(){this.kind="memory",this.synchronizeTabs=!1}
7async initialize(e){this.serializer=aT(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 sj,new sQ(t,n,e.initialUser,this.serializer)}Du(e){return new sR(sF.Vi,this.serializer)}bu(e){return new al}async terminate(){var e,t;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(t=this.indexBackfillerScheduler)||void 0===t||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}oJ.provider={build:()=>new oJ};class oZ extends oJ{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,t){return D(this.persistence.referenceDelegate instanceof sP,46915),new sd(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Du(e){let t=void 0!==this.cacheSizeBytes?se.withCacheSize(this.cacheSizeBytes):se.DEFAULT;return new sR(e=>sP.Vi(e,t),this.serializer)}}class o0 extends oJ{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 oY(this.Mu.syncEngine),await aW(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 sj,new sQ(t,n,e.initialUser,this.serializer)}Cu(e,t){return new sd(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Fu(e,t){let n=new eR(t,this.persistence);return new eV(e.asyncQueue,n)}Du(e){let t=sz(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?se.withCacheSize(this.cacheSizeBytes):se.DEFAULT;return new sB(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,aI(),ab(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(e){return new al}}class o1 extends o0{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 ao&&(this.sharedClientState.syncEngine={Do:o$.bind(null,t),vo:oW.bind(null,t),Co:oH.bind(null,t),Ps:oQ.bind(null,t),bo:oz.bind(null,t)},await this.sharedClientState.start()),await this.persistence.ji(async e=>{await oK(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=aI();if(!ao.C(t))throw new C(N.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let n=sz(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ao(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class o2{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=>oN(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=oU.bind(null,this.syncEngine),await a2(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ot}createDatastore(e){var t;let n=aT(e.databaseInfo.databaseId),r=new av(e.databaseInfo);return t=e.authCredentials,new aC(t,e.appCheckCredentials,r,n)}createRemoteStore(e){var t,n;return t=this.localStore,n=this.datastore,new aV(t,n,e.asyncQueue,e=>oN(this.syncEngine,e,0),ac.C()?new ac:new au)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){let o=new ov(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){b(aA,"RemoteStore shutting down."),e.Ia.add(5),await aO(e),e.Ea.shutdown(),e.Aa.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(t=this.eventManager)||void 0===t||t.terminate()}}function o5(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()}}o2.provider={build:()=>new o2};class o4{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 o3{constructor(e,t){this.Nu=e,this.serializer=t,this.metadata=new k,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 ou(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 o6{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 ou(JSON.parse(this.Qu(e)),e)}Qu(e){if(this.cursor+e>this.bundleData.length)throw new C(N.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 o8{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 C(N.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=>ia(e.serializer,t))},r=await e.Jo("BatchGetDocuments",e.serializer.databaseId,Q.emptyPath(),n,t.length),i=new Map;r.forEach(t=>{var n;let r=(n=e.serializer,"found"in t?function(e,t){D(!!t.found,43571),t.found.name,t.found.updateTime;let n=io(e,t.found.name),r=it(t.found.updateTime),i=t.found.createTime?it(t.found.createTime):ea.min(),s=new nv({mapValue:{fields:t.found.fields}});return nI.newFoundDocument(n,r,i,s)}(n,t):"missing"in t?function(e,t){D(!!t.missing,3894),D(!!t.readTime,22933);let n=io(e,t.missing),r=it(t.readTime);return nI.newNoDocument(n,r)}(n,t):S(7234,{result:t}));i.set(r.key.toString(),r)});let s=[];
9return t.forEach(e=>{let t=i.get(e.toString());D(!!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 rP(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=X.fromPath(t);this.mutations.push(new rM(n,this.precondition(n)))}),await async function(e,t){let n={writes:t.map(t=>ig(e.serializer,t))};await e.Wo("Commit",e.serializer.databaseId,Q.emptyPath(),n)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw S(50498,{Wu:e.constructor.name});t=ea.min()}let n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new C(N.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(ea.min())?rS.exists(!1):rS.updateTime(t):rS.none()}preconditionForUpdate(e){let t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(ea.min()))throw new C(N.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return rS.updateTime(t)}return rS.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}let o9="FirestoreClient";class o7{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=y.UNAUTHENTICATED,this.clientId=q.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async e=>{b(o9,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(b(o9,"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 k;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=a6(n,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function le(e,t){e.asyncQueue.verifyOperationInProgress(),b(o9,"Initializing OfflineComponentProvider");let n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await sW(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>{E("Terminating Firestore due to IndexedDb database deletion"),e.terminate().then(()=>{b("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 lt(e,t){e.asyncQueue.verifyOperationInProgress();let n=await ln(e);b(o9,"Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>a1(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>a1(t.remoteStore,n)),e._onlineComponents=t}async function ln(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){b(o9,"Using user provided OfflineComponentProvider");try{await le(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===N.FAILED_PRECONDITION||t.code===N.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 le(e,new oJ)}}else b(o9,"Using default OfflineComponentProvider"),await le(e,new oZ(void 0));return e._offlineComponents}async function lr(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(b(o9,"Using user provided OnlineComponentProvider"),await lt(e,e._uninitializedComponentsProvider._online)):(b(o9,"Using default OnlineComponentProvider"),await lt(e,new o2))),e._onlineComponents}function li(e){return lr(e).then(e=>e.syncEngine)}async function ls(e){let t=await lr(e),n=t.eventManager;return n.onListen=oI.bind(null,t.syncEngine),n.onUnlisten=o_.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=ob.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=oS.bind(null,t.syncEngine),n}function la(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let lo=new Map,ll="firestore.googleapis.com";class lu{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new C(N.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=ll,this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||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 C(N.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new C(N.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=la(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new C(N.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new C(N.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new C(N.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 lh{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 lu({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new C(N.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 C(N.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 lu(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new V;switch(e.type){case"firstParty":return new P(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new C(N.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=lo.get(e);t&&(b("ComponentProvider","Removing Datastore"),lo.delete(e),t.terminate())}(this),Promise.resolve()}}class lc{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new lc(this.firestore,e,this._query)}}class ld{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 lf(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new ld(this.firestore,e,this._key)}toJSON(){return{type:ld._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,n){if(ei(t,ld._jsonSchema))return new ld(e,n||null,new X(Q.fromString(t.referencePath)))}}ld._jsonSchemaVersion="firestore/documentReference/1.0",ld._jsonSchema={type:er("string",ld._jsonSchemaVersion),referencePath:er("string")};class lf extends lc{constructor(e,t,n){super(e,t,nX(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 ld(this.firestore,null,new X(e))}withConverter(e){return new lf(this.firestore,e,this._path)}}function lm(e,t,...n){if(e=(0,h.Ku)(e),Y("collection","path",t),e instanceof lh){let r=Q.fromString(t,...n);return Z(r),new lf(e,null,r)}{if(!(e instanceof ld||e instanceof lf))throw new C(N.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(Q.fromString(t,...n));return Z(r),new lf(e.firestore,null,r)}}function lg(e,t,...n){if(e=(0,h.Ku)(e),1==arguments.length&&(t=q.newId()),Y("doc","path",t),e instanceof lh){let r=Q.fromString(t,...n);return J(r),new ld(e,null,new X(r))}{if(!(e instanceof ld||e instanceof lf))throw new C(N.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(Q.fromString(t,...n));return J(r),new ld(e.firestore,e instanceof lf?e.converter:null,new X(r))}}let lp="AsyncQueue";class ly{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 aE(this,"async_queue_retry"),this.oc=()=>{let e=ab();e&&b(lp,"Visibility state changed to "+e.visibilityState),this.F_.y_()},this._c=e;let t=ab();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=ab();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise(()=>{});let t=new k;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(!ex(e))throw e;b(lp,"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: ",lw(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=a3.createAndSchedule(this,e,t,n,e=>this.lc(e));return this.ec.push(r),r}ac(){this.tc&&S(47125,{hc:lw(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 lw(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}function lv(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 lI{constructor(){this._progressObserver={},this._taskCompletionResolver=new k,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)}}class lb extends lh{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ly,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new ly(e),this._firestoreClient=void 0,await e}}}function lT(e,t){let n="object"==typeof e?e:(0,o.Sx)(),r=(0,o.j6)(n,"firestore").getImmediate({identifier:"string"==typeof e?e:t||t2});if(!r._initialized){let e=(0,h.yU)("firestore");e&&function(e,t,n,r={}){var i;e=en(e,lh);let s=(0,h.zJ)(t),a=e._getSettings(),o=Object.assign(Object.assign({},a),{emulatorOptions:e._getEmulatorOptions()}),l=`${t}:${n}`;s&&((0,h.gE)(`https://${l}`),(0,h.P1)("Firestore",!0)),a.host!==ll&&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,h.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,h.Fy)(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);let s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new C(N.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new y(s)}e._authCredentials=new R(new A(t,n))}}(r,...e)}return r}function lE(e){if(e._terminated)throw new C(N.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||l_(e),e._firestoreClient}function l_(e){var t,n,r,i,s;let a=e._freezeSettings(),o=(i=e._databaseId,s=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",new t1(i,s,e._persistenceKey,a.host,a.ssl,a.experimentalForceLongPolling,a.experimentalAutoDetectLongPolling,la(a.experimentalLongPollingOptions),a.useFetchStreams,a.isUsingEmulator));e._componentsProvider||(null===(n=a.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=a.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider}),e._firestoreClient=new o7(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))}class lS{constructor(e){this._byteString=e}static fromBase64String(e){try{return new lS(t$.fromBase64String(e))}catch(e){throw new C(N.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new lS(t$.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:lS._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(ei(e,lS._jsonSchema))return lS.fromBase64String(e.bytes)}}
9lS._jsonSchemaVersion="firestore/bytes/1.0",lS._jsonSchema={type:er("string",lS._jsonSchemaVersion),bytes:er("string")};class lx{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new C(N.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new H(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class lD{constructor(e){this._methodName=e}}class lN{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new C(N.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new C(N.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 B(this._lat,e._lat)||B(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:lN._jsonSchemaVersion}}static fromJSON(e){if(ei(e,lN._jsonSchema))return new lN(e.latitude,e.longitude)}}lN._jsonSchemaVersion="firestore/geoPoint/1.0",lN._jsonSchema={type:er("string",lN._jsonSchemaVersion),latitude:er("number"),longitude:er("number")};class lC{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:lC._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(ei(e,lC._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new lC(e.vectorValues);throw new C(N.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}lC._jsonSchemaVersion="firestore/vectorValue/1.0",lC._jsonSchema={type:er("string",lC._jsonSchemaVersion),vectorValues:er("object")};let lk=/^__.*__$/;class lA{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new rV(e,this.data,this.fieldMask,t,this.fieldTransforms):new rA(e,this.data,t,this.fieldTransforms)}}class lV{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new rV(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function lR(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw S(40011,{Ec:e})}}class lO{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 lO(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?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?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 l0(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(lR(this.Ec)&&lk.test(e))throw this.wc('Document fields cannot begin and end with "__"')}}class lF{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||aT(e)}Dc(e,t,n,r=!1){return new lO({Ec:e,methodName:t,bc:n,path:H.emptyPath(),mc:!1,Sc:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function lP(e){let t=e._freezeSettings(),n=aT(e._databaseId);return new lF(e._databaseId,!!t.ignoreUndefinedProperties,n)}function lM(e,t,n,r,i,s={}){let a,o,l=e.Dc(s.merge||s.mergeFields?2:0,t,n,i);lX("Data must be an object, but it was:",l,r);let u=lW(r,l);if(s.merge)a=new tB(l.fieldMask),o=l.fieldTransforms;else if(s.mergeFields){let e=[];for(let r of s.mergeFields){let i=lY(t,r,n);if(!l.contains(i))throw new C(N.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);l1(e,i)||e.push(i)}a=new tB(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new lA(new nv(u),a,o)}class lL extends lD{_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 lL}}
9function lU(e,t,n){return new lO({Ec:3,bc:t.settings.bc,methodName:e._methodName,mc:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class lq extends null{_toFieldTransform(e){return new rE(e.path,new rg)}isEqual(e){return e instanceof lq}}class lB extends lD{constructor(e,t){super(e),this.vc=t}_toFieldTransform(e){let t=lU(this,e,!0),n=new rp(this.vc.map(e=>lQ(e,t)));return new rE(e.path,n)}isEqual(e){return e instanceof lB&&(0,h.bD)(this.vc,e.vc)}}class lz extends lD{constructor(e,t){super(e),this.vc=t}_toFieldTransform(e){let t=lU(this,e,!0),n=new rw(this.vc.map(e=>lQ(e,t)));return new rE(e.path,n)}isEqual(e){return e instanceof lz&&(0,h.bD)(this.vc,e.vc)}}class l$ extends lD{constructor(e,t){super(e),this.Cc=t}_toFieldTransform(e){let t=new rI(e.serializer,rd(e.serializer,this.Cc));return new rE(e.path,t)}isEqual(e){return e instanceof l$&&this.Cc===e.Cc}}function lK(e,t,n,r){let i=e.Dc(1,t,n);lX("Data must be an object, but it was:",i,r);let s=[],a=nv.empty();return tR(r,(e,r)=>{let o=lZ(t,e,n);r=(0,h.Ku)(r);let l=i.gc(o);if(r instanceof lL)s.push(o);else{let e=lQ(r,l);null!=e&&(s.push(o),a.set(o,e))}}),new lV(a,new tB(s),i.fieldTransforms)}function lj(e,t,n,r,i,s){let a=e.Dc(1,t,n),o=[lY(t,r,n)],l=[i];if(s.length%2!=0)throw new C(N.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(lY(t,s[e])),l.push(s[e+1]);let u=[],c=nv.empty();for(let e=o.length-1;e>=0;--e)if(!l1(u,o[e])){let t=o[e],n=l[e];n=(0,h.Ku)(n);let r=a.gc(t);if(n instanceof lL)u.push(t);else{let e=lQ(n,r);null!=e&&(u.push(t),c.set(t,e))}}return new lV(c,new tB(u),a.fieldTransforms)}function lG(e,t,n,r=!1){return lQ(n,e.Dc(r?4:3,t))}function lQ(e,t){if(lH(e=(0,h.Ku)(e)))return lX("Unsupported field value:",t,e),lW(e,t);if(e instanceof lD)return function(e,t){if(!lR(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=lQ(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,h.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return rd(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let n=es.fromDate(e);return{timestampValue:r7(t.serializer,n)}}if(e instanceof es){let n=new es(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:r7(t.serializer,n)}}if(e instanceof lN)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof lS)return{bytesValue:ie(t.serializer,e._byteString)};if(e instanceof ld){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:ir(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof lC)return{mapValue:{fields:{[t4]:{stringValue:t8},[t9]:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw t.wc("VectorValues must only contain numeric values.");return rh(t.serializer,e)})}}}}};throw t.wc(`Unsupported field value: ${et(e)}`)}(e,t)}function lW(e,t){let n={};return tO(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):tR(e,(e,r)=>{let i=lQ(r,t.Vc(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function lH(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof es||e instanceof lN||e instanceof lS||e instanceof ld||e instanceof lD||e instanceof lC)}function lX(e,t,n){if(!lH(n)||!ee(n)){let r=et(n);throw"an object"===r?t.wc(e+" a custom object"):t.wc(e+" "+r)}}function lY(e,t,n){if((t=(0,h.Ku)(t))instanceof lx)return t._internalPath;if("string"==typeof t)return lZ(e,t);throw l0("Field path arguments must be of type string or ",e,!1,void 0,n)}let lJ=RegExp("[~\\*/\\[\\]]");function lZ(e,t,n){if(t.search(lJ)>=0)throw l0(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new lx(...t.split("."))._internalPath}catch(r){throw l0(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function l0(e,t,n,r,i){let s=r&&!r.isEmpty(),a=void 0!==i,o=`Function ${t}
9() 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 C(N.INVALID_ARGUMENT,o+e+l)}function l1(e,t){return e.some(e=>e.isEqual(t))}class l2{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 ld(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new l5(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(l4("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class l5 extends l2{data(){return super.data()}}function l4(e,t){return"string"==typeof t?lZ(e,t):t instanceof lx?t._internalPath:t._delegate._internalPath}function l3(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new C(N.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class l6{}class l8 extends l6{}function l9(e,t,...n){let r=[];for(let i of(t instanceof l6&&r.push(t),function(e){let t=e.filter(e=>e instanceof ut).length,n=e.filter(e=>e instanceof l7).length;if(t>1||t>0&&n>0)throw new C(N.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 l7 extends l8{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new l7(e,t,n)}_apply(e){let t=this._parse(e);return uc(e._query,t),new lc(e.firestore,e.converter,n2(e._query,t))}_parse(e){let t=lP(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 C(N.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){uh(a,s);let t=[];for(let n of a)t.push(uu(r,e,n));o={arrayValue:{values:t}}}else o=uu(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||uh(a,s),o=lG(n,t,a,"in"===s||"not-in"===s);return nx.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function ue(e,t,n){let r=l4("where",e);return l7._create(r,t,n)}class ut extends l6{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new ut(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]:nD.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())uc(n,e),n=n2(n,e)}(e._query,t),new lc(e.firestore,e.converter,n2(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class un extends l8{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new un(e,t)}_apply(e){let t=function(e,t,n){if(null!==e.startAt)throw new C(N.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new C(N.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new n_(t,n)}(e._query,this._field,this._direction);return new lc(e.firestore,e.converter,function(e,t){let n=e.explicitOrderBy.concat([t]);return new nH(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}function ur(e,t="asc"){let n=l4("orderBy",e);return un._create(n,t)}class ui extends l8{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}
9static _create(e,t,n){return new ui(e,t,n)}_apply(e){return new lc(e.firestore,e.converter,n5(e._query,this._limit,this._limitType))}}function us(e){return function(e,t){if(t<=0)throw new C(N.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}("limit",e),ui._create("limit",e,"F")}class ua extends l8{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new ua(e,t,n)}_apply(e){var t;let n=ul(e,this.type,this._docOrFields,this._inclusive);return new lc(e.firestore,e.converter,new nH((t=e._query).path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,n,t.endAt))}}class uo extends l8{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uo(e,t,n)}_apply(e){var t;let n=ul(e,this.type,this._docOrFields,this._inclusive);return new lc(e.firestore,e.converter,new nH((t=e._query).path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,n))}}function ul(e,t,n,r){if(n[0]=(0,h.Ku)(n[0]),n[0]instanceof l2)return function(e,t,n,r,i){if(!r)throw new C(N.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);let s=[];for(let n of nZ(e))if(n.field.isKeyField())s.push(no(t,r.key));else{let e=r.data.field(n.field);if(tJ(e))throw new C(N.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 C(N.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 nb(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{let i=lP(e.firestore);return function(e,t,n,r,i,s){let a=e.explicitOrderBy;if(i.length>a.length)throw new C(N.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let o=[];for(let s=0;s<i.length;s++){let l=i[s];if(a[s].field.isKeyField()){if("string"!=typeof l)throw new C(N.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!nJ(e)&&-1!==l.indexOf("/"))throw new C(N.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(Q.fromString(l));if(!X.isDocumentKey(n))throw new C(N.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 X(n);o.push(no(t,i))}else{let e=lG(n,r,l);o.push(e)}}return new nb(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function uu(e,t,n){if("string"==typeof(n=(0,h.Ku)(n))){if(""===n)throw new C(N.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!nJ(t)&&-1!==n.indexOf("/"))throw new C(N.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(Q.fromString(n));if(!X.isDocumentKey(r))throw new C(N.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 no(e,new X(r))}if(n instanceof ld)return no(e,n._key);throw new C(N.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${et(n)}.`)}function uh(e,t){if(!Array.isArray(e)||0===e.length)throw new C(N.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function uc(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 C(N.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new C(N.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class ud{convertValue(e,t="none"){switch(ne(e)){case 0:return null;case 1:return e.booleanValue;case 2:return tG(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(tQ(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw S(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return tR(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertVectorValue(e){var t,n,r;return new lC(null===(r=null===(n=null===(t=e.fields)||void 0===t?void 0:t[t9].arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.map(e=>tG(e.doubleValue)))}convertGeoPoint(e){return new lN(tG(e.latitude),tG(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=tZ(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(t0(e));default:return null}}convertTimestamp(e){let t=tj(e);return new es(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=Q.fromString(e);D(iT(n),9688,{name:e});let r=new t5(n.get(1),n.get(3)),i=new X(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 uf(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class um extends ud{constructor(e){super(),this.firestore=e}convertBytes(e){return new lS(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);
9return new ld(this.firestore,null,t)}}class ug{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class up extends l2{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 uy(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(l4("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new C(N.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=up._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}}up._jsonSchemaVersion="firestore/documentSnapshot/1.0",up._jsonSchema={type:er("string",up._jsonSchemaVersion),bundleSource:er("string","DocumentSnapshot"),bundleName:er("string"),bundle:er("string")};class uy extends up{data(e={}){return super.data(e)}}class uw{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new ug(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 uy(this._firestore,this._userDataWriter,n.key,n,new ug(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 C(N.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 uy(e._firestore,e._userDataWriter,n.doc.key,n.doc,new ug(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 uy(e._firestore,e._userDataWriter,t.doc.key,t.doc,new ug(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 S(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 C(N.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=uw._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=q.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}}uw._jsonSchemaVersion="firestore/querySnapshot/1.0",uw._jsonSchema={type:er("string",uw._jsonSchemaVersion),bundleSource:er("string","QuerySnapsh
9ot"),bundleName:er("string"),bundle:er("string")};class uv extends ud{constructor(e){super(),this.firestore=e}convertBytes(e){return new lS(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new ld(this.firestore,null,t)}}function uI(e){e=en(e,lc);let t=en(e.firestore,lb),n=lE(t),r=new uv(t);return l3(e._query),(function(e,t,n={}){let r=new k;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new o4({next:n=>{s.Ou(),t.enqueueAndForget(()=>oi(e,a)),n.fromCache&&"server"===r.source?i.reject(new C(N.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 ol(n,s,{includeMetadataChanges:!0,ka:!0});return or(e,a)})(await ls(e),e.asyncQueue,t,n,r)),r.promise})(n,e._query).then(n=>new uw(t,r,e,n))}function ub(e,t,n,...r){e=en(e,ld);let i=en(e.firestore,lb),s=lP(i);return u_(i,[("string"==typeof(t=(0,h.Ku)(t))||t instanceof lx?lj(s,"updateDoc",e._key,t,n,r):lK(s,"updateDoc",e._key,t)).toMutation(e._key,rS.exists(!0))])}function uT(e){return u_(en(e.firestore,lb),[new rP(e._key,rS.none())])}function uE(e,t){let n=en(e.firestore,lb),r=lg(e),i=uf(e.converter,t);return u_(n,[lM(lP(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,rS.exists(!1))]).then(()=>r)}function u_(e,t){var n=lE(e);let r=new k;return n.asyncQueue.enqueueAndForget(async()=>ox(await li(n),t,r)),r.promise}class uS{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=o2.provider,this._offlineComponentProvider={build:t=>new o0(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}function ux(e,t){if((e=(0,h.Ku)(e)).firestore!==t)throw new C(N.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class uD{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=lP(e)}get(e){let t=ux(e,this._firestore),n=new um(this._firestore);return this._transaction.lookup([t._key]).then(e=>{if(!e||1!==e.length)return S(24041);let r=e[0];if(r.isFoundDocument())return new l2(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new l2(this._firestore,n,t._key,null,t.converter);throw S(18433,{doc:r})})}set(e,t,n){let r=ux(e,this._firestore),i=uf(r.converter,t,n),s=lM(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=ux(e,this._firestore);return i="string"==typeof(t=(0,h.Ku)(t))||t instanceof lx?lj(this._dataReader,"Transaction.update",s._key,t,n,r):lK(this._dataReader,"Transaction.update",s._key,t),this._transaction.update(s._key,i),this}delete(e){let t=ux(e,this._firestore);return this._transaction.delete(t._key),this}}new WeakMap,!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 lb(new O(e.getProvider("auth-internal")),new L(i,e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new C(N.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new t5(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.