1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[135],{1622:(e,t,n)=>{n.d(t,{GG:()=>o7,K7:()=>li,_A:()=>oQ,rJ:()=>oz,vK:()=>lt});var r,i,s,a,o=n(8277),l=n(6366),u=n(395),h=n(2846),c=n(916),d=n(4052),f=n(5704),m=n(5376).Buffer;let g="@firebase/firestore",p="4.9.2";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="12.3.0",v=new u.Vy("@firebase/firestore");function I(){return v.logLevel}function E(e,...t){if(v.logLevel<=u.$b.DEBUG){let n=t.map(b);v.debug(`Firestore (${w}): ${e}`,...n)}}function T(e,...t){if(v.logLevel<=u.$b.ERROR){let n=t.map(b);v.error(`Firestore (${w}): ${e}`,...n)}}function S(e,...t){if(v.logLevel<=u.$b.WARN){let n=t.map(b);v.warn(`Firestore (${w}): ${e}`,...n)}}function b(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function x(e,t,n){let r="Unexpected state";"string"==typeof t?r=t:n=t,_(e,r,n)}function _(e,t,n){let r=`FIRESTORE (${w}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==n)try{r+=" CONTEXT: "+JSON.stringify(n)}catch(e){r+=" CONTEXT: "+n}throw T(r),Error(r)}function C(e,t,n,r){let i="Unexpected state";"string"==typeof n?i=n:r=n,e||_(t,i,r)}let D={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class N extends h.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class 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 R{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(y.UNAUTHENTICATED))}shutdown(){}}class V{constructor(e){this.t=e,this.currentUser=y.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){C(void 0===this.o,42304);let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),i=new 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=>{E("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(E("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?(E("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(C("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 C(null===e||"string"==typeof e,2055,{h:e}),new y(e)}}class O{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 M{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new O(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(y.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class P{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 F{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,o.xZ)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){C(void 0===this.o,3512);let n=e=>{null!=e.error&&E("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,E("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>
1{E("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?r(e):E("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new P(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(C("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new P(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class L{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 U(e,t){return e<t?-1:+(e>t)}function B(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=e.charAt(r),i=t.charAt(r);if(n!==i)return q(n)===q(i)?U(n,i):q(n)?1:-1}return U(e.length,t.length)}function q(e){let t=e.charCodeAt(0);return t>=55296&&t<=57343}function z(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}let K="__name__";class ${constructor(e,t,n){void 0===t?t=0:t>e.length&&x(637,{offset:t,range:e.length}),void 0===n?n=e.length-t:n>e.length-t&&x(1746,{length:n,range:e.length-t}),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===$.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof $?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=$.compareSegments(e.get(r),t.get(r));if(0!==n)return n}return U(e.length,t.length)}static compareSegments(e,t){let n=$.isNumericId(e),r=$.isNumericId(t);return n&&!r?-1:!n&&r?1:n&&r?$.extractNumericId(e).compare($.extractNumericId(t)):B(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 G extends ${construct(e,t,n){return new G(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new N(D.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new G(t)}static emptyPath(){return new G([])}}let j=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Q extends ${construct(e,t,n){return new Q(e,t,n)}static isValidIdentifier(e){return j.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),Q.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===K}static keyField(){return new Q([K])}static fromServerFormat(e){let t=[],n="",r=0,i=()=>
1{if(0===n.length)throw new N(D.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 N(D.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new N(D.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new N(D.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Q(t)}static emptyPath(){return new Q([])}}class W{constructor(e){this.path=e}static fromPath(e){return new W(G.fromString(e))}static fromName(e){return new W(G.fromString(e).popFirst(5))}static empty(){return new W(G.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===G.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return G.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new W(new G(e.slice()))}}function H(e){if(W.isDocumentKey(e))throw new N(D.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function J(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new N(D.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=function(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var t;let n=(t=e).constructor?t.constructor.name:null;return n?`a custom ${n} object`:"an object"}}return"function"==typeof e?"a function":x(12329,{type:typeof e})}(e);throw new N(D.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function X(e,t){let n={typeString:e};return t&&(n.value=t),n}function Y(e,t){let n;if("object"!=typeof e||null===e||Object.getPrototypeOf(e)!==Object.prototype&&null!==Object.getPrototypeOf(e))throw new N(D.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 N(D.INVALID_ARGUMENT,n);return!0}class Z{static now(){return Z.fromMillis(Date.now())}static fromDate(e){return Z.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*1e6);return new Z(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new N(D.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new N(D.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?U(this.nanoseconds,e.nanoseconds):U(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:Z._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(Y(e,Z._jsonSchema))return new Z(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}Z._jsonSchemaVersion="firestore/timestamp/1.0",Z._jsonSchema={type:X("string",Z._jsonSchemaVersion),seconds:X("number"),nanoseconds:X("number")};class ee{static fromTimestamp(e){return new ee(e)}static min(){return new ee(new Z(0,0))}static max(){return new ee(new Z(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 et{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function en(e){return e.fields.find(e=>2===e.kind)}function er(e){return e.fields.filter(e=>2!==e.kind)}et.UNKNOWN_ID=-1;class ei{constructor(e,t){this.fieldPath=e,this.kind=t}}class es{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new es(0,el.min())}}function ea(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;return new el(ee.fromTimestamp(1e9===r?new Z(n+1,0):new Z(n,r)),W.empty(),t)}function eo(e){return new el(e.readTime,e.key,-1)}
1class el{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new el(ee.min(),W.empty(),-1)}static max(){return new el(ee.max(),W.empty(),-1)}}function eu(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n||0!==(n=W.comparator(e.documentKey,t.documentKey))?n:U(e.largestBatchId,t.largestBatchId)}let eh="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ec{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function ed(e){if(e.code!==D.FAILED_PRECONDITION||e.message!==eh)throw e;E("LocalStore","Unexpectedly lost primary lease")}class ef{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&x(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new ef((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 ef?t:ef.resolve(t)}catch(e){return ef.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):ef.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):ef.reject(t)}static resolve(e){return new ef((t,n)=>{t(e)})}static reject(e){return new ef((t,n)=>{n(e)})}static waitFor(e){return new ef((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=ef.resolve(!1);for(let n of e)t=t.next(e=>e?ef.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 ef((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 ef((n,r)=>{let i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}let em="SimpleDb";class eg{static open(e,t,n,r){try{return new eg(t,e.transaction(r,n))}catch(e){throw new ev(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 ev(e,t.error)):this.S.resolve()},this.transaction.onerror=t=>{let n=eb(t.target.error);this.S.reject(new ev(e,n))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(E(em,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}C(){let e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){return new eE(this.transaction.objectStore(e))}}class ep{static delete(e){return E(em,"Removing database:",e),eT((0,h.mS)().indexedDB.deleteDatabase(e)).toPromise()}static v(){if(!(0,h.zW)())return!1;if(ep.F())return!0;let e=(0,h.ZQ)(),t=ep.M(e),n=ey(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(){return void 0!==f&&"YES"===f.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE}static O(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.N=n,this.B=null,12.2===ep.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 L(e){return this.db||(E(em,"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 ev(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 N(D.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 N(D.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 ev(e,r))},r.onupgradeneeded=e=>{E(em,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);let t=e.target.result;this.N.k(t,r.transaction,e.oldVersion,this.version).next(()=>{E(em,"Database upgrade to version "+this.version+" complete")}
1)}})),this.q&&(this.db.onversionchange=e=>this.q(e)),this.db}$(e){this.q=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){let i="readonly"===t,s=0;for(;;){++s;try{this.db=await this.L(e);let t=eg.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.C(),e)).catch(e=>(t.abort(e),ef.reject(e))).toPromise();return s.catch(()=>{}),await t.D,s}catch(t){let e="FirebaseError"!==t.name&&s<3;if(E(em,"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 ey(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class ew{constructor(e){this.U=e,this.K=!1,this.W=null}get isDone(){return this.K}get G(){return this.W}set cursor(e){this.U=e}done(){this.K=!0}j(e){this.W=e}delete(){return eT(this.U.delete())}}class ev extends N{constructor(e,t){super(D.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function eI(e){return"IndexedDbTransactionError"===e.name}class eE{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(E(em,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(E(em,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),eT(n)}add(e){return E(em,"ADD",this.store.name,e,e),eT(this.store.add(e))}get(e){return eT(this.store.get(e)).next(t=>(void 0===t&&(t=null),E(em,"GET",this.store.name,e,t),t))}delete(e){return E(em,"DELETE",this.store.name,e),eT(this.store.delete(e))}count(){return E(em,"COUNT",this.store.name),eT(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 ef((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),t=[];return this.H(e,(e,n)=>{t.push(n)}).next(()=>t)}}Y(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new ef((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}Z(e,t){E(em,"DELETE ALL",this.store.name);let n=this.options(e,t);n.X=!1;let r=this.cursor(n);return this.H(r,(e,t,n)=>n.delete())}ee(e,t){let n;t?n=e:(n={},t=e);let r=this.cursor(n);return this.H(r,t)}te(e){let t=this.cursor({});return new ef((n,r)=>{t.onerror=e=>{r(eb(e.target.error))},t.onsuccess=t=>{let r=t.target.result;r?e(r.primaryKey,r.value).next(e=>{e?r.continue():n()}):n()}})}H(e,t){let n=[];return new ef((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 ew(i),a=t(i.primaryKey,i.value,s);if(a instanceof ef){let e=a.catch(e=>(s.done(),ef.reject(e)));n.push(e)}s.isDone?r():null===s.G?i.continue():i.continue(s.G)}}).next(()=>ef.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.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function eT(e){return new ef((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{n(eb(e.target.error))}})}let eS=!1;function eb(e){let t=ep.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 N("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 eS||(eS=!0,setTimeout(()=>{throw e},0)),e}}return e}let ex="IndexBackfiller";class e_{constructor(e,t){this.asyncQueue=e,this.ne=t,this.task=null}start(){this.re(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}re(e){E(ex,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let e=await this.ne.ie();E(ex,`Documents written: ${e}`)}catch(e){eI(e)?E(ex,"Ignoring IndexedDB error during index backfill: ",e):await ed(e)}await this.re(6e4)})}}class eC{constructor(e,t){this.localStore=e,this.persistence=t}async ie(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.se(t,e))}se(e,t){let n=new Set,r=t,i=!0;return ef.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>
1{if(null!==t&&!n.has(t))return E(ex,`Processing collection: ${t}`),this.oe(e,t,r).next(e=>{r-=e,n.add(t)});i=!1})).next(()=>t-r)}oe(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._e(r,n)).next(n=>(E(ex,`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n))).next(()=>i.size)}))}_e(e,t){let n=e;return t.changes.forEach((e,t)=>{let r=eo(t);eu(r,n)>0&&(n=r)}),new el(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class eD{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ae(e),this.ue=e=>t.writeSequenceNumber(e))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ue&&this.ue(e),e}}eD.ce=-1;function eN(e){return 0===e&&1/e==-1/0}function ek(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let n=t,r=e.length;for(let t=0;t<r;t++){let r=e.charAt(t);switch(r){case"\0":n+="\x01\x10";break;case"\x01":n+="\x01\x11";break;default:n+=r}}return n}(e.get(n),t);return t+"\x01\x01"}function eA(e){let t=e.length;if(C(t>=2,64408,{path:e}),2===t)return C("\x01"===e.charAt(0)&&"\x01"===e.charAt(1),56145,{path:e}),G.emptyPath();let n=t-2,r=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>n)&&x(50515,{path:e}),e.charAt(t+1)){case"\x01":let a,o=e.substring(s,t);0===i.length?a=o:(i+=o,a=i,i=""),r.push(a);break;case"\x10":i+=e.substring(s,t),i+="\0";break;case"\x11":i+=e.substring(s,t+1);break;default:x(61167,{path:e})}s=t+2}return new G(r)}
1let eR="remoteDocuments",eV="owner",eO="owner",eM="mutationQueues",eP="mutations",eF="batchId",eL="userMutationsIndex",eU=["userId","batchId"],eB={},eq="documentMutations",ez="remoteDocumentsV14",eK=["prefixPath","collectionGroup","readTime","documentId"],e$="documentKeyIndex",eG=["prefixPath","collectionGroup","documentId"],ej="collectionGroupIndex",eQ=["collectionGroup","readTime","prefixPath","documentId"],eW="remoteDocumentGlobal",eH="remoteDocumentGlobalKey",eJ="targets",eX="queryTargetsIndex",eY=["canonicalId","targetId"],eZ="targetDocuments",e0=["targetId","path"],e1="documentTargetsIndex",e2=["path","targetId"],e5="targetGlobalKey",e6="targetGlobal",e4="collectionParents",e3=["collectionId","parent"],e8="clientMetadata",e9="bundles",e7="namedQueries",te="indexConfiguration",tt="collectionGroupIndex",tn="indexState",tr=["indexId","uid"],ti="sequenceNumberIndex",ts=["uid","sequenceNumber"],ta="indexEntries",to=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],tl="documentKeyIndex",tu=["indexId","uid","orderedDocumentKey"],th="documentOverlays",tc=["userId","collectionPath","documentId"],td="collectionPathOverlayIndex",tf=["userId","collectionPath","largestBatchId"],tm="collectionGroupOverlayIndex",tg=["userId","collectionGroup","largestBatchId"],tp="globals",ty=[eM,eP,eq,eR,eJ,eV,e6,eZ,e8,eW,e4,e9,e7],tw=[...ty,th],tv=[eM,eP,eq,ez,eJ,eV,e6,eZ,e8,eW,e4,e9,e7,th],tI=[...tv,te,tn,ta],tE=[...tI,tp];class tT extends ec{constructor(e,t){super(),this.le=e,this.currentSequenceNumber=t}}function tS(e,t){return ep.O(e.le,t)}function tb(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tx(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}class t_{constructor(e,t){this.comparator=e,this.root=t||tD.EMPTY}insert(e,t){return new t_(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,tD.BLACK,null,null))}remove(e){return new t_(this.comparator,this.root.remove(e,this.comparator).copy(null,null,tD.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){let r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return -1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new tC(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new tC(this.root,e,this.comparator,!1)}getReverseIterator(){return new tC(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new tC(this.root,e,this.comparator,!0)}}class tC{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 tD{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:tD.RED,this.left=null!=r?r:tD.EMPTY,this.right=null!=i?i:tD.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new tD(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 tD.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 tD.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,tD.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,tD.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw x(43730,{key:this.key,value:this.value});if(this.right.isRed())throw x(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw x(27949);return e+ +!this.isRed()}}
1tD.EMPTY=null,tD.RED=!0,tD.BLACK=!1,tD.EMPTY=new class{constructor(){this.size=0}get key(){throw x(57766)}get value(){throw x(16141)}get color(){throw x(16727)}get left(){throw x(29726)}get right(){throw x(36894)}copy(e,t,n,r,i){return this}insert(e,t,n){return new tD(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 tN{constructor(e){this.comparator=e,this.data=new t_(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 tk(this.data.getIterator())}getIteratorFrom(e){return new tk(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 tN)||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 tN(this.comparator);return t.data=e,t}}class tk{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function tA(e){return e.hasNext()?e.getNext():void 0}class tR{constructor(e){this.fields=e,e.sort(Q.comparator)}static empty(){return new tR([])}unionWith(e){let t=new tN(Q.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new tR(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return z(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class tV extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class tO{constructor(e){this.binaryString=e}static fromBase64String(e){return new tO(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new tV("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new tO(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 U(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}tO.EMPTY_BYTE_STRING=new tO("");let tM=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function tP(e){if(C(!!e,39018),"string"==typeof e){let t=0,n=tM.exec(e);if(C(!!n,46558,{timestamp:e}),n[1]){let e=n[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:tF(e.seconds),nanos:tF(e.nanos)}}function tF(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function tL(e){return"string"==typeof e?tO.fromBase64String(e):tO.fromUint8Array(e)}let tU="server_timestamp",tB="__type__",tq="__previous_value__",tz="__local_write_time__";function tK(e){return(e?.mapValue?.fields||{})[tB]?.stringValue===tU}function t$(e){let t=e.mapValue.fields[tq];return tK(t)?t$(t):t}function tG(e){let t=tP(e.mapValue.fields[tz].timestampValue);return new Z(t.seconds,t.nanos)}class tj{constructor(e,t,n,r,i,s,a,o,l,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u}}let tQ="(default)";class tW{constructor(e,t){this.projectId=e,this.database=t||tQ}static empty(){return new tW("","")}get isDefaultDatabase(){return this.database===tQ}isEqual(e){return e instanceof tW&&e.projectId===this.projectId&&e.database===this.database}}let tH="__type__",tJ="__max__",tX={mapValue:{fields:{__type__:{stringValue:tJ}}}},tY="__vector__",tZ="value",t0={nullValue:"NULL_VALUE"};function t1(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?tK(e)?4:na(e)?0x1fffffffffffff:ni(e)?10:11:x(28295,{value:e})}function t2(e,t){if(e===t)return!0;let n=t1(e);if(n!==t1(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return tG(e).isEqual(tG(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=tP(e.timestampValue),i=tP(t.timestampValue);return r.seconds===i.seconds&&r.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return tL(e.bytesValue).isEqual(tL(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return tF(e.geoPointValue.latitude)===tF(t.geoPointValue.latitude)&&tF(e.geoPointValue.longitude)===tF(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return tF(e.integerValue)===tF(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=tF(e.doubleValue),r=tF(t.doubleValue);return n===r?eN(n)===eN(r):isNaN(n)&&isNaN(r)}return!1;case 9:return z(e.arrayValue.values||[],t.arrayValue.values||[],t2);case 10:case 11:let s=e.mapValue.fields||{},a=t.mapValue.fields||{};if(tb(s)!==tb(a))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===a[e]||!t2(s[e],a[e])))return!1;return!0;default:return x(52216,{left:e})}}function t5(e,t){return void 0!==(e.values||[]).find(e=>t2(e,t))}function t6(e,t){if(e===t)return 0;let n=t1(e),r=t1(t);if(n!==r)return U(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return U(e.booleanValue,t.booleanValue);case 2:let i=tF(e.integerValue||e.doubleValue),s=tF(t.integerValue||t.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return t4(e.timestampValue,t.timestampValue);case 4:return t4(tG(e),tG(t));case 5:return B(e.stringValue,t.stringValue);case 6:return function(e,t){let n=tL(e),r=tL(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=U(n[e],r[e]);if(0!==t)return t}return U(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let n=U(tF(e.latitude),tF(t.latitude));return 0!==n?n:U(tF(e.longitude),tF(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return t3(e.arrayValue,t.arrayValue);case 10:return function(e,t){let n=e.fields||{},r=t.fields||{},i=n[tZ]?.arrayValue,s=r[tZ]?.arrayValue,a=U(i?.values?.length||0,s?.values?.length||0);return 0!==a?a:t3(i,s)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===tX.mapValue&&t===tX.mapValue)return 0;if(e===tX.mapValue)return 1;if(t===tX.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=B(r[e],s[e]);if(0!==t)return t;let a=t6(n[r[e]],i[s[e]]);if(0!==a)return a}return U(r.length,s.length)}(e.mapValue,t.mapValue);default:throw x(23264,{he:n})}}function t4(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return U(e,t);let n=tP(e),r=tP(t),i=U(n.seconds,r.seconds);return 0!==i?i:U(n.nanos,r.nanos)}function t3(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=t6(n[e],r[e]);if(t)return t}return U(n.length,r.length)}function t8(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=tP(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?tL(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,W.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+=t8(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}:${t8(e.fields[i])}`;return n+"}"}(e.mapValue):x(61005,{value:e})}function t9(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function t7(e){return!!e&&"integerValue"in e}function ne(e){return!!e&&"arrayValue"in e}function nt(e){return!!e&&"nullValue"in e}function nn(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function nr(e){return!!e&&"mapValue"in e}function ni(e){return(e?.mapValue?.fields||{})[tH]?.stringValue===tY}function ns(e){if(e.geoPointValue)return{geoPointValue:{...e.geoPointValue}};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:{...e.timestampValue}};if(e.mapValue){let t={mapValue:{fields:{}}};return tx(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=ns(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=ns(e.arrayValue.values[n]);return t}return{...e}}function na(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===tJ}let no={mapValue:{fields:{[tH]:{stringValue:tY},[tZ]:{arrayValue:{}}}}};function nl(e,t){let n=t6(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function nu(e,t){let n=t6(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class nh{constructor(e){this.value=e}static empty(){return new nh({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!nr(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()]=ns(t)}setAll(e){let t=Q.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()]=ns(e):r.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){let t=this.field(e.popLast());nr(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return t2(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)];nr(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}
1applyChanges(e,t,n){for(let r of(tx(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new nh(ns(this.value))}}class nc{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new nc(e,0,ee.min(),ee.min(),ee.min(),nh.empty(),0)}static newFoundDocument(e,t,n,r){return new nc(e,1,t,ee.min(),n,r,0)}static newNoDocument(e,t){return new nc(e,2,t,ee.min(),ee.min(),nh.empty(),0)}static newUnknownDocument(e,t){return new nc(e,3,t,ee.min(),ee.min(),nh.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(ee.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=nh.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=nh.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ee.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof nc&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new nc(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class nd{constructor(e,t){this.position=e,this.inclusive=t}}function nf(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()?W.comparator(W.fromName(a.referenceValue),n.key):t6(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function nm(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(!t2(e.position[n],t.position[n]))return!1;return!0}class ng{constructor(e,t="asc"){this.field=e,this.dir=t}}class np{}class ny extends np{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new nb(e,t,n):"array-contains"===t?new nD(e,n):"in"===t?new nN(e,n):"not-in"===t?new nk(e,n):"array-contains-any"===t?new nA(e,n):new ny(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new nx(e,n):new n_(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(t6(t,this.value)):null!==t&&t1(this.value)===t1(t)&&this.matchesComparison(t6(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return x(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class nw extends np{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new nw(e,t)}matches(e){return nv(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.Pe||(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function nv(e){return"and"===e.op}function nI(e){return"or"===e.op}function nE(e){return nT(e)&&nv(e)}function nT(e){for(let t of e.filters)if(t instanceof nw)return!1;return!0}function nS(e,t){let n=e.filters.concat(t);return nw.create(n,e.op)}class nb extends ny{constructor(e,t,n){super(e,t,n),this.key=W.fromName(n.referenceValue)}matches(e){let t=W.comparator(e.key,this.key);return this.matchesComparison(t)}}class nx extends ny{constructor(e,t){super(e,"in",t),this.keys=nC("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class n_ extends ny{constructor(e,t){super(e,"not-in",t),this.keys=nC("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function nC(e,t){return(t.arrayValue?.values||[]).map(e=>W.fromName(e.referenceValue))}class nD extends ny{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return ne(t)&&t5(t.arrayValue,this.value)}}class nN extends ny{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&t5(this.value.arrayValue,t)}}class nk extends ny{constructor(e,t){super(e,"not-in",t)}matches(e){if(t5(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!t5(this.value.arrayValue,t)}}class nA extends ny{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!ne(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>t5(this.value.arrayValue,e))}}class nR{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.Te=null}}function nV(e,t=null,n=[],r=[],i=null,s=null,a=null){return new nR(e,t,n,r,i,s,a)}function nO(e){if(null===e.Te){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 ny)return t.field.canonicalString()+t.op.toString()+t8(t.value);if(nE(t))return t.filters.map(t=>e(t)).join(",");{let n=t.filters.map(t=>e(t)).join(",");return`${t.op}(${n})`}})(e)).join(","),t+="|ob:",t+=e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),null==e.limit||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>t8(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>t8(e)).join(",")),e.Te=t}return e.Te}function nM(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 ny?n instanceof ny&&t.op===n.op&&t.field.isEqual(n.field)&&t2(t.value,n.value):t instanceof nw?n instanceof nw&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,i)=>t&&e(r,n.filters[i]),!0):void x(19439)}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!nm(e.startAt,t.startAt)&&nm(e.endAt,t.endAt)}function nP(e){return W.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function nF(e,t){return e.filters.filter(e=>e instanceof ny&&e.field.isEqual(t))}function nL(e,t,n){let r=t0,i=!0;for(let n of nF(e,t)){let e=t0,t=!0;switch(n.op){case"<":case"<=":var s;
1e="nullValue"in(s=n.value)?t0:"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?t9(tW.empty(),W.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?ni(s)?no:{mapValue:{}}:x(35942,{value:s});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=t0}0>nl({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>nl({value:r,inclusive:i},{value:e,inclusive:n.inclusive})&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}function nU(e,t,n){let r=tX,i=!0;for(let n of nF(e,t)){let e=tX,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?t9(tW.empty(),W.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?no:"mapValue"in s?ni(s)?{mapValue:{}}:tX:x(61959,{value:s}),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=tX}nu({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];nu({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}class nB{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.Ie=null,this.Ee=null,this.de=null,this.startAt,this.endAt}}function nq(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 nz(e){if(null===e.Ie){let t;e.Ie=[];let n=new Set;for(let t of e.explicitOrderBy)e.Ie.push(t),n.add(t.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(t=new tN(Q.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.Ie.push(new ng(t,r))}),n.has(Q.keyField().canonicalString())||e.Ie.push(new ng(Q.keyField(),r))}return e.Ie}function nK(e){return e.Ee||(e.Ee=function(e,t){if("F"===e.limitType)return nV(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 ng(e.field,t)});let n=e.endAt?new nd(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new nd(e.startAt.position,e.startAt.inclusive):null;return nV(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(e,nz(e))),e.Ee}function n$(e,t,n){return new nB(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function nG(e,t){return nM(nK(e),nK(t))&&e.limitType===t.limitType}function nj(e){return`${nO(nK(e))}|lt:${e.limitType}`}function nQ(e){var t;let n;return`Query(target=${n=(t=nK(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 ny?`${t.field.canonicalString()} ${t.op} ${t8(t.value)}`:t instanceof nw?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),null==t.limit||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(e=>t8(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>t8(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function nW(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):W.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=nf(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,nz(e),t))&&(!e.endAt||!!function(e,t,n){let r=nf(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,nz(e),t))}function nH(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function nJ(e){return(t,n)=>{let r=!1;for(let i of nz(e)){let e=function(e,t,n){let r=e.field.isKeyField()?W.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?t6(r,i):x(42886)}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return x(19790,{direction:e.dir})}}(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}class nX{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){tx(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){var e=this.inner;for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}size(){return this.innerSize}}let nY=new t_(W.comparator),nZ=new t_(W.comparator);function n0(...e){let t=nZ;for(let n of e)t=t.insert(n.key,n);return t}function n1(){return new nX(e=>e.toString(),(e,t)=>e.isEqual(t))}let n2=new t_(W.comparator),n5=new tN(W.comparator);function n6(...e){let t=n5;for(let n of e)t=t.add(n);return t}let n4=new tN(U);class n3{constructor(){this._=void 0}}class n8 extends n3{}class n9 extends n3{constructor(e){super(),this.elements=e}}function n7(e,t){let n=ri(t);for(let t of e.elements)n.some(e=>t2(e,t))||n.push(t);return{arrayValue:{values:n}}}class re extends n3{constructor(e){super(),this.elements=e}}function rt(e,t){let n=ri(t);for(let t of e.elements)n=n.filter(e=>!t2(e,t));return{arrayValue:{values:n}}}class rn extends n3{constructor(e,t){super(),this.serializer=e,this.Ae=t}}function rr(e){return tF(e.integerValue||e.doubleValue)}function ri(e){return ne(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class rs{constructor(e,t){this.field=e,this.transform=t}}class ra{constructor(e,t){this.version=e,this.transformResults=t}}class ro{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new ro}static exists(e){return new ro(void 0,e)}static updateTime(e){return new ro(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function rl(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class ru{}function rh(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new rw(e.key,ro.none()):new rf(e.key,e.data,ro.none());{let n=e.data,r=nh.empty(),i=new tN(Q.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 rm(e.key,r,new tR(i.toArray()),ro.none())}}function rc(e,t,n,r){return e instanceof rf?function(e,t,n,r){if(!rl(e.precondition,t))return n;let i=e.value.clone(),s=ry(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof rm?function(e,t,n,r){if(!rl(e.precondition,t))return n;let i=ry(e.fieldTransforms,r,t),s=t.data;return(s.setAll(rg(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):rl(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function rd(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)&&z(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof n9&&r instanceof n9||n instanceof re&&r instanceof re?z(n.elements,r.elements,t2):n instanceof rn&&r instanceof rn?t2(n.Ae,r.Ae):n instanceof n8&&r instanceof n8)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class rf extends ru{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 rm extends ru{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function rg(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 rp(e,t,n){let r=new Map;C(e.length===n.length,32656,{Re:n.length,Ve: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 n9?n7(o,l):o instanceof re?rt(o,l):i))}return r}function ry(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 n8?function(e,t){let n={fields:{[tB]:{stringValue:tU},[tz]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&tK(t)&&(t=t$(t)),t&&(n.fields[tq]=t),{mapValue:n}}(t,s):e instanceof n9?n7(e,s):e instanceof re?rt(e,s):function(e,t){let n=function(e,t){return e instanceof rn?t7(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}(e,t),r=rr(n)+rr(e.Ae);return t7(n)&&t7(e.Ae)?{integerValue:""+r}:function(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:eN(t)?"-0":t}}(e.serializer,r)}(e,s))}return r}class rw extends ru{constructor(e,t){super(),this.key=e,this.prec
1ondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rv extends ru{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class rI{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let r=this.mutations[t];r.key.isEqual(e.key)&&function(e,t,n){e instanceof rf?function(e,t,n){let r=e.value.clone(),i=rp(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof rm?function(e,t,n){if(!rl(e.precondition,t))return t.convertToUnknownDocument(n.version);let r=rp(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(rg(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}(r,e,n[t])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=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=n1();return this.mutations.forEach(r=>{let i=e.get(r.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=rh(s,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(ee.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),n6())}isEqual(e){return this.batchId===e.batchId&&z(this.mutations,e.mutations,(e,t)=>rd(e,t))&&z(this.baseMutations,e.baseMutations,(e,t)=>rd(e,t))}}class rE{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){C(e.mutations.length===n.length,58842,{me:e.mutations.length,fe:n.length});let r=n2,i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new rE(e,t,n,r)}}class rT{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 rS{constructor(e,t){this.count=e,this.unchangedNames=t}}function rb(e){if(void 0===e)return T("GRPC error has no .code"),D.UNKNOWN;switch(e){case r.OK:return D.OK;case r.CANCELLED:return D.CANCELLED;case r.UNKNOWN:return D.UNKNOWN;case r.DEADLINE_EXCEEDED:return D.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return D.RESOURCE_EXHAUSTED;case r.INTERNAL:return D.INTERNAL;case r.UNAVAILABLE:return D.UNAVAILABLE;case r.UNAUTHENTICATED:return D.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return D.INVALID_ARGUMENT;case r.NOT_FOUND:return D.NOT_FOUND;case r.ALREADY_EXISTS:return D.ALREADY_EXISTS;case r.PERMISSION_DENIED:return D.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return D.FAILED_PRECONDITION;case r.ABORTED:return D.ABORTED;case r.OUT_OF_RANGE:return D.OUT_OF_RANGE;case r.UNIMPLEMENTED:return D.UNIMPLEMENTED;case r.DATA_LOSS:return D.DATA_LOSS;default:return x(39323,{code:e})}}(i=r||(r={}))[i.OK=0]="OK",i[i.CANCELLED=1]="CANCELLED",i[i.UNKNOWN=2]="UNKNOWN",i[i.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",i[i.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",i[i.NOT_FOUND=5]="NOT_FOUND",i[i.ALREADY_EXISTS=6]="ALREADY_EXISTS",i[i.PERMISSION_DENIED=7]="PERMISSION_DENIED",i[i.UNAUTHENTICATED=16]="UNAUTHENTICATED",i[i.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",i[i.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",i[i.ABORTED=10]="ABORTED",i[i.OUT_OF_RANGE=11]="OUT_OF_RANGE",i[i.UNIMPLEMENTED=12]="UNIMPLEMENTED",i[i.INTERNAL=13]="INTERNAL",i[i.UNAVAILABLE=14]="UNAVAILABLE",i[i.DATA_LOSS=15]="DATA_LOSS";let rx=new c.jz([0xffffffff,0xffffffff],0);function r_(e){let t=(new TextEncoder).encode(e),n=new c.VV;return n.update(t),new Uint8Array(n.digest())}function rC(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 rD{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new rN(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new rN(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new rN(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.pe=c.jz.fromNumber(this.ge)}ye(e,t,n){let r=e.add(t.multiply(c.jz.fromNumber(n)));return 1===r.compare(rx)&&(r=new c.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.ge)return!1;let[t,n]=rC(r_(e));for(let e=0;e<this.hashCount;e++){let r=this.ye(t,n,e);if(!this.we(r))return!1}return!0}static create(e,t,n){let r=new rD(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);
4return n.forEach(e=>r.insert(e)),r}insert(e){if(0===this.ge)return;let[t,n]=rC(r_(e));for(let e=0;e<this.hashCount;e++){let r=this.ye(t,n,e);this.Se(r)}}Se(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class rN extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rk{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,rA.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new rk(ee.min(),r,new t_(U),nY,n6())}}class rA{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 rA(n,t,n6(),n6(),n6())}}class rR{constructor(e,t,n,r){this.be=e,this.removedTargetIds=t,this.key=n,this.De=r}}class rV{constructor(e,t){this.targetId=e,this.Ce=t}}class rO{constructor(e,t,n=tO.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class rM{constructor(){this.ve=0,this.Fe=rL(),this.Me=tO.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return 0!==this.ve}get Be(){return this.Oe}Le(e){e.approximateByteSize()>0&&(this.Oe=!0,this.Me=e)}ke(){let e=n6(),t=n6(),n=n6();return this.Fe.forEach((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:x(38017,{changeType:i})}}),new rA(this.Me,this.xe,e,t,n)}qe(){this.Oe=!1,this.Fe=rL()}Qe(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}$e(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}Ue(){this.ve+=1}Ke(){this.ve-=1,C(this.ve>=0,3241,{ve:this.ve})}We(){this.Oe=!0,this.xe=!0}}class rP{constructor(e){this.Ge=e,this.ze=new Map,this.je=nY,this.Je=rF(),this.He=rF(),this.Ye=new t_(U)}Ze(e){for(let t of e.be)e.De&&e.De.isFoundDocument()?this.Xe(t,e.De):this.et(t,e.key,e.De);for(let t of e.removedTargetIds)this.et(t,e.key,e.De)}tt(e){this.forEachTarget(e,t=>{let n=this.nt(t);switch(e.state){case 0:this.rt(t)&&n.Le(e.resumeToken);break;case 1:n.Ke(),n.Ne||n.qe(),n.Le(e.resumeToken);break;case 2:n.Ke(),n.Ne||this.removeTarget(t);break;case 3:this.rt(t)&&(n.We(),n.Le(e.resumeToken));break;case 4:this.rt(t)&&(this.it(t),n.Le(e.resumeToken));break;default:x(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ze.forEach((e,n)=>{this.rt(n)&&t(n)})}st(e){let t=e.targetId,n=e.Ce.count,r=this.ot(t);if(r){let i=r.target;if(nP(i))if(0===n){let e=new W(i.path);this.et(t,e,nc.newNoDocument(e,ee.min()))}else C(1===n,20013,{expectedCount:n});else{let r=this._t(t);if(r!==n){let n=this.ut(e),i=n?this.ct(n,e,r):1;0!==i&&(this.it(t),this.Ye=this.Ye.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}ut(e){let t,n,r=e.Ce.unchangedNames;if(!r||!r.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=r;try{t=tL(i).toUint8Array()}catch(e){if(e instanceof tV)return S("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 rD(t,s,a)}catch(e){return S(e instanceof rN?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===n.ge?null:n}ct(e,t,n){return 2*(t.Ce.count!==n-this.Pt(e,t.targetId))}Pt(e,t){let n=this.Ge.getRemoteKeysForTarget(t),r=0;return n.forEach(n=>{let i=this.Ge.ht(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.et(t,n,null),r++)}),r}Tt(e){let t=new Map;this.ze.forEach((n,r)=>{let i=this.ot(r);if(i){if(n.current&&nP(i.target)){let t=new W(i.target.path);this.It(t).has(r)||this.Et(r,t)||this.et(r,t,nc.newNoDocument(t,e))}n.Be&&(t.set(r,n.ke()),n.qe())}});let n=n6();this.He.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{let t=this.ot(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.je.forEach((t,n)=>n.setReadTime(e));let r=new rk(e,t,this.Ye,this.je,n);return this.je=nY,this.Je=rF(),this.He=rF(),this.Ye=new t_(U),r}Xe(e,t){if(!this.rt(e))return;
4let n=2*!!this.Et(e,t.key);this.nt(e).Qe(t.key,n),this.je=this.je.insert(t.key,t),this.Je=this.Je.insert(t.key,this.It(t.key).add(e)),this.He=this.He.insert(t.key,this.dt(t.key).add(e))}et(e,t,n){if(!this.rt(e))return;let r=this.nt(e);this.Et(e,t)?r.Qe(t,1):r.$e(t),this.He=this.He.insert(t,this.dt(t).delete(e)),this.He=this.He.insert(t,this.dt(t).add(e)),n&&(this.je=this.je.insert(t,n))}removeTarget(e){this.ze.delete(e)}_t(e){let t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ue(e){this.nt(e).Ue()}nt(e){let t=this.ze.get(e);return t||(t=new rM,this.ze.set(e,t)),t}dt(e){let t=this.He.get(e);return t||(t=new tN(U),this.He=this.He.insert(e,t)),t}It(e){let t=this.Je.get(e);return t||(t=new tN(U),this.Je=this.Je.insert(e,t)),t}rt(e){let t=null!==this.ot(e);return t||E("WatchChangeAggregator","Detected inactive target",e),t}ot(e){let t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(e){this.ze.set(e,new rM),this.Ge.getRemoteKeysForTarget(e).forEach(t=>{this.et(e,t,null)})}Et(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}}function rF(){return new t_(W.comparator)}function rL(){return new t_(W.comparator)}let rU={asc:"ASCENDING",desc:"DESCENDING"},rB={"<":"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"},rq={and:"AND",or:"OR"};class rz{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function rK(e,t){return e.useProto3Json||null==t?t:{value:t}}function r$(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 rG(e){return C(!!e,49232),ee.fromTimestamp(function(e){let t=tP(e);return new Z(t.seconds,t.nanos)}(e))}function rj(e,t){return rQ(e,t).canonicalString()}function rQ(e,t){let n=new G(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function rW(e){let t=G.fromString(e);return C(r7(t),10190,{key:t.toString()}),t}function rH(e,t){return rj(e.databaseId,t.path)}function rJ(e,t){let n=rW(t);if(n.get(1)!==e.databaseId.projectId)throw new N(D.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new N(D.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new W(r0(n))}function rX(e,t){return rj(e.databaseId,t)}function rY(e){let t=rW(e);return 4===t.length?G.emptyPath():r0(t)}function rZ(e){return new G(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function r0(e){return C(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function r1(e,t,n){return{name:rH(e,t),fields:n.value.mapValue.fields}}function r2(e,t){var n;let r;if(t instanceof rf)r={update:r1(e,t.key,t.value)};else if(t instanceof rw)r={delete:rH(e,t.key)};else if(t instanceof rm)r={update:r1(e,t.key,t.data),updateMask:function(e){let t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof rv))return x(16599,{Vt:t.type});r={verify:rH(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof n8)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof n9)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof re)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof rn)return{fieldPath:t.field.canonicalString(),increment:n.Ae};throw x(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:r$(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:x(27497)),r}function r5(e,t){var n;let r=t.currentDocument?void 0!==(n=t.currentDocument).updateTime?ro.updateTime(rG(n.updateTime)):void 0!==n.exists?ro.exists(n.exists):ro.none():ro.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let n;
4return n=null,"setToServerValue"in t?(C("REQUEST_TIME"===t.setToServerValue,16630,{proto:t}),n=new n8):"appendMissingElements"in t?n=new n9(t.appendMissingElements.values||[]):"removeAllFromArray"in t?n=new re(t.removeAllFromArray.values||[]):"increment"in t?n=new rn(e,t.increment):x(16584,{proto:t}),new rs(Q.fromServerFormat(t.fieldPath),n)}):[];if(t.update){t.update.name;let n=rJ(e,t.update.name),s=new nh({mapValue:{fields:t.update.fields}});return t.updateMask?new rm(n,s,new tR((t.updateMask.fieldPaths||[]).map(e=>Q.fromServerFormat(e))),r,i):new rf(n,s,r,i)}return t.delete?new rw(rJ(e,t.delete),r):t.verify?new rv(rJ(e,t.verify),r):x(1463,{proto:t})}function r6(e,t){return{documents:[rX(e,t.path)]}}function r4(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=rX(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof ny?function(e){if("=="===e.op){if(nn(e.value))return{unaryFilter:{field:r8(e.field),op:"IS_NAN"}};if(nt(e.value))return{unaryFilter:{field:r8(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(nn(e.value))return{unaryFilter:{field:r8(e.field),op:"IS_NOT_NAN"}};if(nt(e.value))return{unaryFilter:{field:r8(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:r8(e.field),op:rB[e.op],value:e.value}}}(t):t instanceof nw?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:rq[t.op],filters:n}}}(t):x(54877,{filter:t})}(nw.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:r8(e.field),direction:rU[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=rK(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}),{ft:s,parent:i}}function r3(e){var t;let n,r=rY(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){C(1===s,65062);let e=i.from[0];e.allDescendants?a=e.collectionId:r=r.child(e.collectionId)}let o=[];i.where&&(o=function(e){let t=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=r9(e.unaryFilter.field);return ny.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=r9(e.unaryFilter.field);return ny.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=r9(e.unaryFilter.field);return ny.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=r9(e.unaryFilter.field);return ny.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return x(61313);default:return x(60726)}}(t):void 0!==t.fieldFilter?ny.create(r9(t.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return x(58110);default:return x(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?nw.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return x(1026)}}(t.compositeFilter.op)):x(30097,{filter:t})}(e);return t instanceof nw&&nE(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new ng(r9(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=null==(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 nd(e.values||[],t)}(i.startAt));let c=null;return i.endAt&&(c=function(e){let t=!e.before;return new nd(e.values||[],t)}(i.endAt)),new nB(r,a,l,o,u,"F",h,c)}function r8(e){return{fieldPath:e.canonicalString()}}function r9(e){return Q.fromServerFormat(e.fieldPath)}function r7(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class ie{constructor(e,t,n,r,i=ee.min(),s=ee.min(),a=tO.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 it{constructor(e){this.yt=e}}function ir(e,t){let n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:ii(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;r.document={name:rH(i=e.yt,t.key),fields:t.data.value.mapValue.fields,updateTime:r$(i,t.version.toTimestamp()),createTime:r$(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:is(t.ver
4sion)};else{if(!t.isUnknownDocument())return x(57904,{document:t});r.unknownDocument={path:n.path.toArray(),version:is(t.version)}}return r}function ii(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function is(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function ia(e){let t=new Z(e.seconds,e.nanoseconds);return ee.fromTimestamp(t)}function io(e,t){let n=(t.baseMutations||[]).map(t=>r5(e.yt,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=>r5(e.yt,t)),i=Z.fromMillis(t.localWriteTimeMs);return new rI(t.batchId,i,n,r)}function il(e){let t=ia(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?ia(e.lastLimboFreeSnapshotVersion):ee.min();return new ie(void 0!==e.query.documents?function(e){let t=e.documents.length;return C(1===t,1966,{count:t}),nK(new nB(rY(e.documents[0])))}(e.query):nK(r3(e.query)),e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,tO.fromBase64String(e.resumeToken))}function iu(e,t){let n,r=is(t.snapshotVersion),i=is(t.lastLimboFreeSnapshotVersion);n=nP(t.target)?r6(e.yt,t.target):r4(e.yt,t.target).ft;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:nO(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function ih(e){let t=r3({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?n$(t,t.limit,"L"):t}function ic(e,t){return new rT(t.largestBatchId,r5(e.yt,t.overlayMutation))}function id(e,t){let n=t.path.lastSegment();return[e,ek(t.path.popLast()),n]}function im(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:is(r.readTime),documentKey:ek(r.documentKey.path),largestBatchId:r.largestBatchId}}class ig{getBundleMetadata(e,t){return tS(e,e9).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:ia(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return tS(e,e9).put({bundleId:t.id,createTime:is(rG(t.createTime)),version:t.version})}getNamedQuery(e,t){return tS(e,e7).get(t).next(e=>{if(e)return{name:e.name,query:ih(e.bundledQuery),readTime:ia(e.readTime)}})}saveNamedQuery(e,t){return tS(e,e7).put({name:t.name,readTime:is(rG(t.readTime)),bundledQuery:t.bundledQuery})}}class ip{constructor(e,t){this.serializer=e,this.userId=t}static wt(e,t){return new ip(e,t.uid||"")}getOverlay(e,t){return tS(e,th).get(id(this.userId,t)).next(e=>e?ic(this.serializer,e):null)}getOverlays(e,t){let n=n1();return ef.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 rT(t,i);r.push(this.St(e,s))}),ef.waitFor(r)}removeOverlaysForBatchId(e,t,n){let r=new Set;t.forEach(e=>r.add(ek(e.getCollectionPath())));let i=[];return r.forEach(t=>{let r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(tS(e,th).Z(td,r))}),ef.waitFor(i)}getOverlaysForCollection(e,t,n){let r=n1(),i=ek(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,1/0],!0);return tS(e,th).J(td,s).next(e=>{for(let t of e){let e=ic(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){let i,s=n1(),a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,1/0],!0);return tS(e,th).ee({index:tm,range:a},(e,t,n)=>{let a=ic(this.serializer,t);s.size()<r||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):n.done()}).next(()=>s)}St(e,t){return tS(e,th).put(function(e,t,n){let[r,i,s]=id(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:r2(e.yt,n.mutation)}}(this.serializer,this.userId,t))}}class iy{bt(e){return tS(e,tp)}getSessionToken(e){return this.bt(e).get("sessionToken").next(e=>{let t=e?.value;return t?tO.fromUint8Array(t):tO.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.bt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class iw{constructor(){}Dt(e,t){this.Ct(e,t),t.vt()}Ct(e,t){if("nullValue"in e)this.Ft(t,5);else if("booleanValue"in e)this.Ft(t,10),t.Mt(+!!e.booleanValue);else if("integerValue"in e)this.Ft(t,15),t.Mt(tF(e.integerValue));else if("doubleValue"in e){let n=tF(e.doubleValue);isNaN(n)?this.Ft(t,13):(this.Ft(t,15),eN(n)?t.Mt(0):t.Mt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Ft(t,20),"string"==typeof n&&(n=tP(n)),t.xt(`${n.seconds||""}`),t.Mt(n.nanos||0)}else if("stringValue"in e)this.Ot(e.stringValue,t),this.Nt(t);else if("bytesValue"in e)this.Ft(t,30),t.Bt(tL(e.bytesValue)),this.Nt(t);else if("referenceValue"in e)this.Lt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Ft(t,45),t.Mt(n.latitude||0),t.Mt(n.longitude||0)}else"mapValue"in e?na(e)?this.Ft(t,Number.MAX_SAFE_INTEGER):ni(e)?this.kt(e.mapValue,t):(this.qt(e.mapValue,t),this.Nt(t)):"arrayValue"in e?(this.Qt(e.arrayValue,t),this.Nt(t)):x(19022,{$t:e})}Ot(e,t){this.Ft(t,25),this.Ut(e,t)}Ut(e,t){t.xt(e)}qt(e,t){let n=e.fields||{};for(let e of(this.Ft(t,55),Object.keys(n)))this.Ot(e,t),this.Ct(n[e],t)}kt(e,t){let n=e.fields||{};this.Ft(t,53);let r=n[tZ].arrayValue?.values?.length||0;this.Ft(t,15),t.Mt(tF(r)),this.Ot(tZ,t),this.Ct(n[tZ],t)}Qt(e,t){let n=e.values||[];for(let e of(this.Ft(t,50),n))this.Ct(e,t)}
4Lt(e,t){this.Ft(t,37),W.fromName(e).path.forEach(e=>{this.Ft(t,60),this.Ut(e,t)})}Ft(e,t){e.Mt(t)}Nt(e){e.Mt(2)}}function iv(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)}iw.Kt=new iw;class iI{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Wt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.Gt(n.value),n=t.next();this.zt()}jt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.Jt(n.value),n=t.next();this.Ht()}Yt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Gt(e);else if(e<2048)this.Gt(960|e>>>6),this.Gt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Gt(480|e>>>12),this.Gt(128|63&e>>>6),this.Gt(128|63&e);else{let e=t.codePointAt(0);this.Gt(240|e>>>18),this.Gt(128|63&e>>>12),this.Gt(128|63&e>>>6),this.Gt(128|63&e)}}this.zt()}Zt(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.Ht()}Xt(e){let t=this.en(e),n=iv(t);this.tn(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(e){let t=this.en(e),n=iv(t);this.tn(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])}rn(){this.sn(255),this.sn(255)}_n(){this.an(255),this.an(255)}reset(){this.position=0}seed(e){this.tn(e.length),this.buffer.set(e,this.position),this.position+=e.length}un(){return this.buffer.slice(0,this.position)}en(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}Gt(e){let t=255&e;0===t?(this.sn(0),this.sn(255)):255===t?(this.sn(255),this.sn(0)):this.sn(t)}Jt(e){let t=255&e;0===t?(this.an(0),this.an(255)):255===t?(this.an(255),this.an(0)):this.an(e)}zt(){this.sn(0),this.sn(1)}Ht(){this.an(0),this.an(1)}sn(e){this.tn(1),this.buffer[this.position++]=e}an(e){this.tn(1),this.buffer[this.position++]=~e}tn(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 iE{constructor(e){this.cn=e}Bt(e){this.cn.Wt(e)}xt(e){this.cn.Yt(e)}Mt(e){this.cn.Xt(e)}vt(){this.cn.rn()}}class iT{constructor(e){this.cn=e}Bt(e){this.cn.jt(e)}xt(e){this.cn.Zt(e)}Mt(e){this.cn.nn(e)}vt(){this.cn._n()}}class iS{constructor(){this.cn=new iI,this.ln=new iE(this.cn),this.hn=new iT(this.cn)}seed(e){this.cn.seed(e)}Pn(e){return 0===e?this.ln:this.hn}un(){return this.cn.un()}reset(){this.cn.reset()}}class ib{constructor(e,t,n,r){this.Tn=e,this.In=t,this.En=n,this.dn=r}An(){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 ib(this.Tn,this.In,this.En,n)}Rn(e,t,n){return{indexId:this.Tn,uid:e,arrayValue:iC(this.En),directionalValue:iC(this.dn),orderedDocumentKey:iC(t),documentKey:n.path.toArray()}}Vn(e,t,n){let r=this.Rn(e,t,n);return[r.indexId,r.uid,r.arrayValue,r.directionalValue,r.orderedDocumentKey,r.documentKey]}}function ix(e,t){let n=e.Tn-t.Tn;return 0!==n||0!==(n=i_(e.En,t.En))||0!==(n=i_(e.dn,t.dn))?n:W.comparator(e.In,t.In)}function i_(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 iC(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 iD(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 iN{constructor(e){for(let t of(this.mn=new tN((e,t)=>Q.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.fn=e.orderBy,this.gn=[],e.filters))t.isInequality()?this.mn=this.mn.add(t):this.gn.push(t)}get pn(){return this.mn.size>1}yn(e){if(C(e.collectionGroup===this.collectionId,49279),this.pn)return!1;let t=en(e);if(void 0!==t&&!this.wn(t))return!1;let n=er(e),r=new Set,i=0,s=0;for(;i<n.length&&this.wn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;
4if(this.mn.size>0){let e=this.mn.getIterator().getNext();if(!r.has(e.field.canonicalString())){let t=n[i];if(!this.Sn(e,t)||!this.bn(this.fn[s++],t))return!1}++i}for(;i<n.length;++i){let e=n[i];if(s>=this.fn.length||!this.bn(this.fn[s++],e))return!1}return!0}Dn(){if(this.pn)return null;let e=new tN(Q.comparator),t=[];for(let n of this.gn)if(!n.field.isKeyField())if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new ei(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new ei(n.field,0))}for(let n of this.fn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new ei(n.field,+("asc"!==n.dir))));return new et(et.UNKNOWN_ID,this.collectionId,t,es.empty())}wn(e){for(let t of this.gn)if(this.Sn(t,e))return!0;return!1}Sn(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}bn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function ik(e){return e instanceof ny}function iA(e){return e instanceof nw&&nE(e)}function iR(e){return ik(e)||iA(e)||function(e){if(e instanceof nw&&nI(e)){for(let t of e.getFilters())if(!ik(t)&&!iA(t))return!1;return!0}return!1}(e)}function iV(e,t){return C(e instanceof ny||e instanceof nw,38388),C(t instanceof ny||t instanceof nw,25473),iM(e instanceof ny?t instanceof ny?nw.create([e,t],"and"):iO(e,t):t instanceof ny?iO(t,e):function(e,t){if(C(e.filters.length>0&&t.filters.length>0,48005),nv(e)&&nv(t))return nS(e,t.getFilters());let n=nI(e)?e:t,r=nI(e)?t:e,i=n.filters.map(e=>iV(e,r));return nw.create(i,"or")}(e,t))}function iO(e,t){if(nv(t))return nS(t,e.getFilters());{let n=t.filters.map(t=>iV(e,t));return nw.create(n,"or")}}function iM(e){if(C(e instanceof ny||e instanceof nw,11850),e instanceof ny)return e;let t=e.getFilters();if(1===t.length)return iM(t[0]);if(nT(e))return e;let n=t.map(e=>iM(e)),r=[];return n.forEach(t=>{t instanceof ny?r.push(t):t instanceof nw&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:nw.create(r,e.op)}class iP{constructor(){this.Cn=new iF}addToCollectionParentIndex(e,t){return this.Cn.add(t),ef.resolve()}getCollectionParents(e,t){return ef.resolve(this.Cn.getEntries(t))}addFieldIndex(e,t){return ef.resolve()}deleteFieldIndex(e,t){return ef.resolve()}deleteAllFieldIndexes(e){return ef.resolve()}createTargetIndexes(e,t){return ef.resolve()}getDocumentsMatchingTarget(e,t){return ef.resolve(null)}getIndexType(e,t){return ef.resolve(0)}getFieldIndexes(e,t){return ef.resolve([])}getNextCollectionGroupToUpdate(e){return ef.resolve(null)}getMinOffset(e,t){return ef.resolve(el.min())}getMinOffsetFromCollectionGroup(e,t){return ef.resolve(el.min())}updateCollectionGroup(e,t,n){return ef.resolve()}updateIndexEntries(e,t){return ef.resolve()}}class iF{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new tN(G.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 tN(G.comparator)).toArray()}}let iL="IndexedDbIndexManager",iU=new Uint8Array(0);class iB{constructor(e,t){this.databaseId=t,this.vn=new iF,this.Fn=new nX(e=>nO(e),(e,t)=>nM(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.vn.has(t)){let n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.vn.add(t)});let i={collectionId:n,parent:ek(r)};return tS(e,e4).put(i)}return ef.resolve()}getCollectionParents(e,t){let n=[],r=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return tS(e,e4).J(r).next(e=>{for(let r of e){if(r.collectionId!==t)break;n.push(eA(r.parent))}return n})}addFieldIndex(e,t){let n=tS(e,te),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=tS(e,tn);return i.next(e=>{n.put(im(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let n=tS(e,te),r=tS(e,tn),i=tS(e,ta);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=tS(e,te),n=tS(e,ta),r=tS(e,tn);return t.Z().next(()=>n.Z()).next(()=>r.Z())}createTargetIndexes(e,t){return ef.forEach(this.Mn(t),t=>this.getIndexType(e,t).next(n=>{if(0===n||1===n){let n=new iN(t).Dn();if(null!=n)return this.addFieldIndex(e,n)}}))}getDocumentsMatchingTarget(e,t){let n=tS(e,ta),r=!0,i=new Map;return ef.forEach(this.Mn(t),t=>this.xn(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>{if(r){let e=n6(),r=[];return ef.forEach(i,(i,s)=>{E(iL,`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${nO(t)}`);let a=function(e,t){let n=en(t);if(void 0===n)return null;for(let t of nF(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 er(t))for(let t of nF(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 er(t)){let t=0===i.kind?nL(e,i.fieldPath,e.startAt):nU(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new nd(n,r)}(s,i),u=function(e,t){let n=[],r=!0;for(let i of er(t)){let t=0===i.kind?nU(e,i.fieldPath,e.endAt):nL(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new nd(n,r)}(s,i),h=this.On(i,s,l),c=this.On(i,s,u),d=this.Nn(i,s,o),f=this.Bn(i.indexId,a,h,l.inclusive,c,u.inclusive,d);return ef.forEach(f,i=>n.Y(i,t.limit).next(t=>{t.forEach(t=>{let n=W.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return ef.resolve(null)})}Mn(e){let t=this.Fn.get(e);return t||(t=0===e.filters.length?[e]:(function(e){if(0===e.getFilters().length)return[];let t=function e(t){if(C(t instanceof ny||t instanceof nw,34018),t instanceof ny)return t;if(1===t.filters.length)return e(t.filters[0]);let n=t.filters.map(t=>e(t)),r=nw.create(n,t.op);return iR(r=iM(r))?r:(C(r instanceof nw,64498),C(nv(r),40251),C(r.filters.length>1,57927),r.filters.reduce((e,t)=>
4iV(e,t)))}(function e(t){if(C(t instanceof ny||t instanceof nw,20012),t instanceof ny){if(t instanceof nN){let e=t.value.arrayValue?.values?.map(e=>ny.create(t.field,"==",e))||[];return nw.create(e,"or")}return t}let n=t.filters.map(t=>e(t));return nw.create(n,t.op)}(e));return C(iR(t),7391),ik(t)||iA(t)?[t]:t.getFilters()})(nw.create(e.filters,"and")).map(t=>nV(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.Fn.set(e,t)),t}Bn(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.Ln(t[h/l]):iU,c=this.kn(e,o,n[h%l],r),d=this.qn(e,o,i[h%l],s),f=a.map(t=>this.kn(e,o,t,!0));u.push(...this.createRange(c,d,f))}return u}kn(e,t,n,r){let i=new ib(e,W.empty(),t,n);return r?i:i.An()}qn(e,t,n,r){let i=new ib(e,W.empty(),t,n);return r?i.An():i}xn(e,t){let n=new iN(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.yn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let n=2,r=this.Mn(t);return ef.forEach(r,t=>this.xn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new tN(Q.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 iS;for(let r of er(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;let i=n.Pn(r.kind);iw.Kt.Dt(e,i)}return n.un()}Ln(e){let t=new iS;return iw.Kt.Dt(e,t.Pn(0)),t.un()}$n(e,t){let n=new iS;return iw.Kt.Dt(t9(this.databaseId,t),n.Pn(function(e){let t=er(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.un()}Nn(e,t,n){if(null===n)return[];let r=[];r.push(new iS);let i=0;for(let s of er(e)){let e=n[i++];for(let n of r)if(this.Un(t,s.fieldPath)&&ne(e))r=this.Kn(r,s,e);else{let t=n.Pn(s.kind);iw.Kt.Dt(e,t)}}return this.Wn(r)}On(e,t,n){return this.Nn(e,t,n.position)}Wn(e){let t=[];for(let n=0;n<e.length;++n)t[n]=e[n].un();return t}Kn(e,t,n){let r=[...e],i=[];for(let e of n.arrayValue.values||[])for(let n of r){let r=new iS;r.seed(n.un()),iw.Kt.Dt(e,r.Pn(t.kind)),i.push(r)}return i}Un(e,t){return!!e.filters.find(e=>e instanceof ny&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let n=tS(e,te),r=tS(e,tn);return(t?n.J(tt,IDBKeyRange.bound(t,t)):n.J()).next(e=>{let t=[];return ef.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){let n=t?new es(t.sequenceNumber,new el(ia(t.readTime),new W(eA(t.documentKey)),t.largestBatchId)):es.empty(),r=e.fields.map(([e,t])=>new ei(Q.fromServerFormat(e),t));return new et(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:U(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){let r=tS(e,te),i=tS(e,tn);return this.Gn(e).next(e=>r.J(tt,IDBKeyRange.bound(t,t)).next(t=>ef.forEach(t,t=>i.put(im(t.indexId,this.uid,e,n)))))}updateIndexEntries(e,t){let n=new Map;return ef.forEach(t,(t,r)=>{let i=n.get(t.collectionGroup);return(i?ef.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),ef.forEach(i,n=>this.zn(e,t,n).next(t=>{let i=this.jn(r,n);return t.isEqual(i)?ef.resolve():this.Jn(e,r,n,t,i)}))))})}Hn(e,t,n,r){return tS(e,ta).put(r.Rn(this.uid,this.$n(n,t.key),t.key))}Yn(e,t,n,r){return tS(e,ta).delete(r.Vn(this.uid,this.$n(n,t.key),t.key))}zn(e,t,n){let r=tS(e,ta),i=new tN(ix);return r.ee({index:tl,range:IDBKeyRange.only([n.indexId,this.uid,iC(this.$n(n,t))])},(e,r)=>{i=i.add(new ib(n.indexId,t,iD(r.arrayValue),iD(r.directionalValue)))}).next(()=>i)}jn(e,t){let n=new tN(ix),r=this.Qn(t,e);if(null==r)return n;let i=en(t);if(null!=i){let s=e.data.field(i.fieldPath);if(ne(s))for(let i of s.arrayValue.values||[])n=n.add(new ib(t.indexId,e.key,this.Ln(i),r))}else n=n.add(new ib(t.indexId,e.key,iU,r));return n}Jn(e,t,n,r,i){E(iL,"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=tA(s),l=tA(a);for(;o||l;){let e=!1,t=!1;if(o&&l){let r=n(o,l);r<0?t=!0:r>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(l),l=tA(a)):t?(i(o),o=tA(s)):(o=tA(s),l=tA(a))}}(r,i,ix,r=>{s.push(this.Hn(e,t,n,r))},r=>{s.push(this.Yn(e,t,n,r))}),ef.waitFor(s)}Gn(e){let t=1;return tS(e,tn).ee({index:ti,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,n,r)=>{r.done(),t=n.sequenceNumber+1}
4).next(()=>t)}createRange(e,t,n){n=n.sort((e,t)=>ix(e,t)).filter((e,t,n)=>!t||0!==ix(e,n[t-1]));let r=[];for(let i of(r.push(e),n)){let n=ix(i,e),s=ix(i,t);if(0===n)r[0]=e.An();else if(n>0&&s<0)r.push(i),r.push(i.An());else if(s>0)break}r.push(t);let i=[];for(let e=0;e<r.length;e+=2){if(this.Zn(r[e],r[e+1]))return[];let t=r[e].Vn(this.uid,iU,W.empty()),n=r[e+1].Vn(this.uid,iU,W.empty());i.push(IDBKeyRange.bound(t,n))}return i}Zn(e,t){return ix(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(iq)}getMinOffset(e,t){return ef.mapArray(this.Mn(t),t=>this.xn(e,t).next(e=>e||x(44426))).next(iq)}}function iq(e){C(0!==e.length,28825);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){let i=e[r].indexState.offset;0>eu(i,t)&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new el(t.readTime,t.documentKey,n)}let iz={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class iK{static withCacheSize(e){return new iK(e,iK.DEFAULT_COLLECTION_PERCENTILE,iK.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function i$(e,t,n){let r=e.store(eP),i=e.store(eq),s=[],a=IDBKeyRange.only(n.batchId),o=0,l=r.ee({range:a},(e,t,n)=>(o++,n.delete()));s.push(l.next(()=>{C(1===o,47070,{batchId:n.batchId})}));let u=[];for(let e of n.mutations){var h,c;let r=(h=e.key.path,c=n.batchId,[t,ek(h),c]);s.push(i.delete(r)),u.push(e.key)}return ef.waitFor(s).next(()=>u)}function iG(e){let t;if(!e)return 0;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw x(14731);t=e.noDocument}return JSON.stringify(t).length}iK.DEFAULT_COLLECTION_PERCENTILE=10,iK.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,iK.DEFAULT=new iK(0x2800000,iK.DEFAULT_COLLECTION_PERCENTILE,iK.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),iK.DISABLED=new iK(-1,0,0);class ij{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Xn={}}static wt(e,t,n,r){return C(""!==e.uid,64387),new ij(e.isAuthenticated()?e.uid:"",t,n,r)}checkEmpty(e){let t=!0,n=IDBKeyRange.bound([this.userId,-1/0],[this.userId,1/0]);return iW(e).ee({index:eL,range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){let i=tS(e,eq),s=iW(e);return s.add({}).next(a=>{C("number"==typeof a,49019);let o=new rI(a,t,n,r),l=function(e,t,n){let r=n.baseMutations.map(t=>r2(e.yt,t)),i=n.mutations.map(t=>r2(e.yt,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,o),u=[],h=new tN((e,t)=>U(e.canonicalString(),t.canonicalString()));for(let e of r){var c,d;let t=(c=this.userId,d=e.key.path,[c,ek(d),a]);h=h.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,eB))}return h.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.Xn[a]=o.keys()}),ef.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return iW(e).get(t).next(e=>e?(C(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),io(this.serializer,e)):null)}er(e,t){return this.Xn[t]?ef.resolve(this.Xn[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){let n=e.keys();return this.Xn[t]=n,n}return null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return iW(e).ee({index:eL,range:r},(e,t,r)=>{t.userId===this.userId&&(C(t.batchId>=n,47524,{tr:n}),i=io(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,1/0]),n=-1;return iW(e).ee({index:eL,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,1/0]);return iW(e).J(eL,t).next(e=>e.map(e=>io(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let n=[this.userId,ek(t.path)],r=IDBKeyRange.lowerBound(n),i=[];return tS(e,eq).ee({range:r},(n,r,s)=>{let[a,o,l]=n,u=eA(o);if(a===this.userId&&t.path.isEqual(u))return iW(e).get(l).next(e=>{if(!e)throw x(61480,{nr:n,batchId:l});C(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:l}),i.push(io(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tN(U),r=[];return t.forEach(t=>{let i=[this.userId,ek(t.path)],s=IDBKeyRange.lowerBound(i),a=tS(e,eq).ee({range:s},(e,r,i)=>{let[s,a,o]=e,l=eA(a);s===this.userId&&t.path.isEqual(l)?n=n.add(o):i.done()});r.push(a)}),ef.waitFor(r).next(()=>this.rr(e,n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=[this.userId,ek(n)],s=IDBKeyRange.lowerBound(i),a=new tN(U);return tS(e,eq).ee({range:s},(e,t,i)=>
4{let[s,o,l]=e,u=eA(o);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(a=a.add(l)):i.done()}).next(()=>this.rr(e,a))}rr(e,t){let n=[],r=[];return t.forEach(t=>{r.push(iW(e).get(t).next(e=>{if(null===e)throw x(35274,{batchId:t});C(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),n.push(io(this.serializer,e))}))}),ef.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return i$(e.le,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.ir(t.batchId)}),ef.forEach(n,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}ir(e){delete this.Xn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>{if(!t)return ef.resolve();let n=IDBKeyRange.lowerBound([this.userId]),r=[];return tS(e,eq).ee({range:n},(e,t,n)=>{if(e[0]===this.userId){let t=eA(e[1]);r.push(t)}else n.done()}).next(()=>{C(0===r.length,56720,{sr:r.map(e=>e.canonicalString())})})})}containsKey(e,t){return iQ(e,this.userId,t)}_r(e){return tS(e,eM).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function iQ(e,t,n){let r=[t,ek(n.path)],i=r[1],s=IDBKeyRange.lowerBound(r),a=!1;return tS(e,eq).ee({range:s,X:!0},(e,n,r)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),r.done()}).next(()=>a)}function iW(e){return tS(e,eP)}class iH{constructor(e){this.ar=e}next(){return this.ar+=2,this.ar}static ur(){return new iH(0)}static cr(){return new iH(-1)}}class iJ{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.lr(e).next(t=>{let n=new iH(t.highestTargetId);return t.highestTargetId=n.next(),this.hr(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.lr(e).next(e=>ee.fromTimestamp(new Z(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.lr(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,n){return this.lr(e).next(r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.hr(e,r)))}addTargetData(e,t){return this.Pr(e,t).next(()=>this.lr(e).next(n=>(n.targetCount+=1,this.Tr(t,n),this.hr(e,n))))}updateTargetData(e,t){return this.Pr(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>tS(e,eJ).delete(t.targetId)).next(()=>this.lr(e)).next(t=>(C(t.targetCount>0,8065),t.targetCount-=1,this.hr(e,t)))}removeTargets(e,t,n){let r=0,i=[];return tS(e,eJ).ee((s,a)=>{let o=il(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,i.push(this.removeTargetData(e,o)))}).next(()=>ef.waitFor(i)).next(()=>r)}forEachTarget(e,t){return tS(e,eJ).ee((e,n)=>{t(il(n))})}lr(e){return tS(e,e6).get(e5).next(e=>(C(null!==e,2888),e))}hr(e,t){return tS(e,e6).put(e5,t)}Pr(e,t){return tS(e,eJ).put(iu(this.serializer,t))}Tr(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.lr(e).next(e=>e.targetCount)}getTargetData(e,t){let n=nO(t),r=IDBKeyRange.bound([n,-1/0],[n,1/0]),i=null;return tS(e,eJ).ee({range:r,index:eX},(e,n,r)=>{let s=il(n);nM(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){let r=[],i=iX(e);return t.forEach(t=>{let s=ek(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),ef.waitFor(r)}removeMatchingKeys(e,t,n){let r=iX(e);return ef.forEach(t,t=>{let i=ek(t.path);return ef.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){let n=iX(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=iX(e),i=n6();return r.ee({range:n,X:!0},(e,t,n)=>{let r=new W(eA(e[1]));i=i.add(r)}).next(()=>i)}containsKey(e,t){let n=ek(t.path),r=IDBKeyRange.bound([n],[n+"\0"],!1,!0),i=0;return iX(e).ee({index:e1,X:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}At(e,t){return tS(e,eJ).get(t).next(e=>e?il(e):null)}}function iX(e){return tS(e,eZ)}let iY="LruGarbageCollector";function iZ([e,t],[n,r]){let i=U(e,n);return 0===i?U(t,r):i}class i0{constructor(e){this.Ir=e,this.buffer=new tN(iZ),this.Er=0}dr(){return++this.Er}Ar(e){let t=[e,this.dr()];if(this.buffer.size<this.Ir)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>iZ(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class i1{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Rr=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Vr(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return null!==this.Rr}Vr(e){E(iY,`Garbage collection scheduled in ${e}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){eI(e)?E(iY,"Ignoring IndexedDB error during garbage collection: ",e):await ed(e)}await this.Vr(3e5)})}}class i2{constructor(e,t){this.mr=e,this.params=t}calculateTargetCount(e,t){return this.mr.gr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return ef.resolve(eD.ce);let n=new i0(t);return this.mr.forEachTarget(e,e=>n.Ar(e.sequenceNumber)).next(()=>this.mr.pr(e,e=>n.Ar(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.mr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.mr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(E("LruGarbageCollector","Garbage collection skipped; disabled"),ef.resolve(iz)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(E("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),iz):this.yr(e,t))}getCacheSize(e){return this.mr.getCacheSize(e)}yr(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?(E("LruGarbageCollector",`C
4apping 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&&E("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`),ef.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class i5{constructor(e,t){this.db=e,this.garbageCollector=new i2(this,t)}gr(e){let t=this.wr(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}wr(e){let t=0;return this.pr(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}pr(e,t){return this.Sr(e,(e,n)=>t(n))}addReference(e,t,n){return i6(e,n)}removeReference(e,t,n){return i6(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return i6(e,t)}br(e,t){let n;return n=!1,tS(e,eM).te(r=>iQ(e,r,t).next(e=>(e&&(n=!0),ef.resolve(!e)))).next(()=>n)}removeOrphanedDocuments(e,t){let n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[],i=0;return this.Sr(e,(s,a)=>{if(a<=t){let t=this.br(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,ee.min()),iX(e).delete([0,ek(s.path)])))});r.push(t)}}).next(()=>ef.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 i6(e,t)}Sr(e,t){let n=iX(e),r,i=eD.ce;return n.ee({index:e1},([e,n],{path:s,sequenceNumber:a})=>{0===e?(i!==eD.ce&&t(new W(eA(r)),i),i=a,r=s):i=eD.ce}).next(()=>{i!==eD.ce&&t(new W(eA(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function i6(e,t){var n;return iX(e).put((n=e.currentSequenceNumber,{targetId:0,path:ek(t.path),sequenceNumber:n}))}class i4{constructor(){this.changes=new nX(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,nc.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?ef.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 i3{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return tS(e,ez).put(n)}removeEntry(e,t,n){return tS(e,ez).delete(function(e,t){let n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],ii(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next(n=>(n.byteSize+=t,this.Dr(e,n)))}getEntry(e,t){let n=nc.newInvalidDocument(t);return tS(e,ez).ee({index:e$,range:IDBKeyRange.only(i9(t))},(e,r)=>{n=this.Cr(t,r)}).next(()=>n)}vr(e,t){let n={size:0,document:nc.newInvalidDocument(t)};return tS(e,ez).ee({index:e$,range:IDBKeyRange.only(i9(t))},(e,r)=>{n={document:this.Cr(t,r),size:iG(r)}}).next(()=>n)}getEntries(e,t){let n=nY;return this.Fr(e,t,(e,t)=>{let r=this.Cr(e,t);n=n.insert(e,r)}).next(()=>n)}Mr(e,t){let n=nY,r=new t_(W.comparator);return this.Fr(e,t,(e,t)=>{let i=this.Cr(e,t);n=n.insert(e,i),r=r.insert(e,iG(t))}).next(()=>({documents:n,Or:r}))}Fr(e,t,n){if(t.isEmpty())return ef.resolve();let r=new tN(se);t.forEach(e=>r=r.add(e));let i=IDBKeyRange.bound(i9(r.first()),i9(r.last())),s=r.getIterator(),a=s.getNext();return tS(e,ez).ee({index:e$,range:i},(e,t,r)=>{let i=W.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>se(a,i);)n(a,null),a=s.getNext();a&&a.isEqual(i)&&(n(a,t),a=s.hasNext()?s.getNext():null),a?r.j(i9(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(),ii(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 tS(e,ez).J(IDBKeyRange.bound(a,o,!0)).next(e=>{i?.incrementDocumentReadCount(e.length);let n=nY;for(let i of e){let e=this.Cr(W.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);
6e.isFoundDocument()&&(nW(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=nY,s=i7(t,n),a=i7(t,el.max());return tS(e,ez).ee({index:ej,range:IDBKeyRange.bound(s,a,!0)},(e,t,n)=>{let s=this.Cr(W.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 i8(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return tS(e,eW).get(eH).next(e=>(C(!!e,20021),e))}Dr(e,t){return tS(e,eW).put(eH,t)}Cr(e,t){if(t){let e=function(e,t){let n;if(t.document)n=function(e,t,n){let r=rJ(e,t.name),i=rG(t.updateTime),s=t.createTime?rG(t.createTime):ee.min(),a=new nh({mapValue:{fields:t.fields}}),o=nc.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}(e.yt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=W.fromSegments(t.noDocument.path),r=ia(t.noDocument.readTime);n=nc.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return x(56709);{let e=W.fromSegments(t.unknownDocument.path),r=ia(t.unknownDocument.version);n=nc.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){let t=new Z(e[0],e[1]);return ee.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual(ee.min())))return e}return nc.newInvalidDocument(e)}}class i8 extends i4{constructor(e,t){super(),this.Nr=e,this.trackRemovals=t,this.Br=new nX(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],n=0,r=new tN((e,t)=>U(e.canonicalString(),t.canonicalString()));
6return this.changes.forEach((i,s)=>{let a=this.Br.get(i);if(t.push(this.Nr.removeEntry(e,i,a.readTime)),s.isValidDocument()){let o=ir(this.Nr.serializer,s);r=r.add(i.path.popLast());let l=iG(o);n+=l-a.size,t.push(this.Nr.addEntry(e,i,o))}else if(n-=a.size,this.trackRemovals){let n=ir(this.Nr.serializer,s.convertToNoDocument(ee.min()));t.push(this.Nr.addEntry(e,i,n))}}),r.forEach(n=>{t.push(this.Nr.indexManager.addToCollectionParentIndex(e,n))}),t.push(this.Nr.updateMetadata(e,n)),ef.waitFor(t)}getFromCache(e,t){return this.Nr.vr(e,t).next(e=>(this.Br.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Nr.Mr(e,t).next(({documents:e,Or:t})=>(t.forEach((t,n)=>{this.Br.set(t,{size:n,readTime:e.get(t).readTime})}),e))}}function i9(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function i7(e,t){let n=t.documentKey.path.toArray();return[e,ii(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function se(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=U(n[e],r[e]))return i;return(i=U(n.length,r.length))||(i=U(n[n.length-2],r[r.length-2]))||U(n[n.length-1],r[r.length-1])}class st{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class sn{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,tR.empty(),Z.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,n6()).next(()=>t))}getLocalViewOfDocuments(e,t,n=n6()){let r=n1();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=n0();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=n1();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,n6()))}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=nY,s=n1(),a=n1();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof rm)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),rc(a.mutation,t,a.mutation.getFieldMask(),Z.now())):s.set(t.key,tR.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>a.set(e,new st(t,s.get(e)??null))),a))}recalculateAndSaveOverlays(e,t){let n=n1(),r=new t_((e,t)=>e-t),i=n6();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)||tR.empty();a=i.applyToLocalView(s,a),n.set(e,a);let o=(r.get(i.batchId)||n6()).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=n1();l.forEach(e=>{if(!i.has(e)){let r=rh(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 ef.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 W.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):null!==t.collectionGroup?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):ef.resolve(n1()),a=-1,o=i;return s.next(t=>ef.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?ef.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,n6())).next(e=>{let t;return{batchId:a,changes:(t=nZ,e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t)}}))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new W(t)).next(e=>{let t=n0();
vendor: 4,134 bytes, line 6
6return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let i=t.collectionGroup,s=n0();return this.indexManager.getCollectionParents(e,i).next(a=>ef.forEach(a,a=>{let o=new nB(a.child(i),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r))).next(e=>{i.forEach((t,n)=>{let r=n.getKey();null===e.get(r)&&(e=e.insert(r,nc.newInvalidDocument(r)))});let n=n0();return e.forEach((e,r)=>{let s=i.get(e);void 0!==s&&rc(s.mutation,r,tR.empty(),Z.now()),nW(t,r)&&(n=n.insert(e,r))}),n})}}class sr{constructor(e){this.serializer=e,this.Lr=new Map,this.kr=new Map}getBundleMetadata(e,t){return ef.resolve(this.Lr.get(t))}saveBundleMetadata(e,t){return this.Lr.set(t.id,{id:t.id,version:t.version,createTime:rG(t.createTime)}),ef.resolve()}getNamedQuery(e,t){return ef.resolve(this.kr.get(t))}saveNamedQuery(e,t){return this.kr.set(t.name,{name:t.name,query:ih(t.bundledQuery),readTime:rG(t.readTime)}),ef.resolve()}}class si{constructor(){this.overlays=new t_(W.comparator),this.qr=new Map}getOverlay(e,t){return ef.resolve(this.overlays.get(t))}getOverlays(e,t){let n=n1();return ef.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.St(e,t,r)}),ef.resolve()}removeOverlaysForBatchId(e,t,n){let r=this.qr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.qr.delete(n)),ef.resolve()}getOverlaysForCollection(e,t,n){let r=n1(),i=t.length+1,s=new W(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 ef.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new t_((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=n1(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=n1(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return ef.resolve(a)}St(e,t,n){let r=this.overlays.get(n.key);if(null!==r){let e=this.qr.get(r.largestBatchId).delete(n.key);this.qr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new rT(t,n));let i=this.qr.get(t);void 0===i&&(i=n6(),this.qr.set(t,i)),this.qr.set(t,i.add(n.key))}}class ss{constructor(){this.sessionToken=tO.EMPTY_BYTE_STRING}getSessionToken(e){return ef.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,ef.resolve()}}class sa{constructor(){this.Qr=new tN(so.$r),this.Ur=new tN(so.Kr)}isEmpty(){return this.Qr.isEmpty()}addReference(e,t){let n=new so(e,t);this.Qr=this.Qr.add(n),this.Ur=this.Ur.add(n)}Wr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Gr(new so(e,t))}zr(e,t){e.forEach(e=>this.removeReference(e,t))}jr(e){let t=new W(new G([])),n=new so(t,e),r=new so(t,e+1),i=[];return this.Ur.forEachInRange([n,r],e=>{this.Gr(e),i.push(e.key)}),i}Jr(){this.Qr.forEach(e=>this.Gr(e))}Gr(e){this.Qr=this.Qr.delete(e),this.Ur=this.Ur.delete(e)}Hr(e){let t=new W(new G([])),n=new so(t,e),r=new so(t,e+1),i=n6();return this.Ur.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new so(e,0),n=this.Qr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class so{constructor(e,t){this.key=e,this.Yr=t}static $r(e,t){return W.comparator(e.key,t.key)||U(e.Yr,t.Yr)}static Kr(e,t){return U(e.Yr,t.Yr)||W.comparator(e.key,t.key)}}class sl{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.tr=1,this.Zr=new tN(so.$r)}checkEmpty(e){return ef.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let i=this.tr;
6this.tr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new rI(i,t,n,r);for(let t of(this.mutationQueue.push(s),r))this.Zr=this.Zr.add(new so(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ef.resolve(s)}lookupMutationBatch(e,t){return ef.resolve(this.Xr(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.ei(t+1),r=n<0?0:n;return ef.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return ef.resolve(0===this.mutationQueue.length?-1:this.tr-1)}getAllMutationBatches(e){return ef.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new so(t,0),r=new so(t,1/0),i=[];return this.Zr.forEachInRange([n,r],e=>{let t=this.Xr(e.Yr);i.push(t)}),ef.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tN(U);return t.forEach(e=>{let t=new so(e,0),r=new so(e,1/0);this.Zr.forEachInRange([t,r],e=>{n=n.add(e.Yr)})}),ef.resolve(this.ti(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=n;W.isDocumentKey(i)||(i=i.child(""));let s=new so(new W(i),0),a=new tN(U);return this.Zr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Yr)),!0)},s),ef.resolve(this.ti(a))}ti(e){let t=[];return e.forEach(e=>{let n=this.Xr(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){C(0===this.ni(t.batchId,"removed"),55003),this.mutationQueue.shift();let n=this.Zr;return ef.forEach(t.mutations,r=>{let i=new so(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.Zr=n})}ir(e){}containsKey(e,t){let n=new so(t,0),r=this.Zr.firstAfterOrEqual(n);return ef.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,ef.resolve()}ni(e,t){return this.ei(e)}ei(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Xr(e){let t=this.ei(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class su{constructor(e){this.ri=e,this.docs=new t_(W.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.ri(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 ef.resolve(n?n.document.mutableCopy():nc.newInvalidDocument(t))}getEntries(e,t){let n=nY;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():nc.newInvalidDocument(e))}),ef.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=nY,s=t.path,a=new W(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>=eu(eo(a),n)||(r.has(a.key)||nW(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return ef.resolve(i)}getAllFromCollectionGroup(e,t,n,r){x(9500)}ii(e,t){return ef.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new sh(this)}getSize(e){return ef.resolve(this.size)}}class sh extends i4{constructor(e){super(),this.Nr=e}applyChanges(e){let t=[];
vendor: 4,734 bytes, line 6
6return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.Nr.addEntry(e,r)):this.Nr.removeEntry(n)}),ef.waitFor(t)}getFromCache(e,t){return this.Nr.getEntry(e,t)}getAllFromCache(e,t){return this.Nr.getEntries(e,t)}}class sc{constructor(e){this.persistence=e,this.si=new nX(e=>nO(e),nM),this.lastRemoteSnapshotVersion=ee.min(),this.highestTargetId=0,this.oi=0,this._i=new sa,this.targetCount=0,this.ai=iH.ur()}forEachTarget(e,t){return this.si.forEach((e,n)=>t(n)),ef.resolve()}getLastRemoteSnapshotVersion(e){return ef.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ef.resolve(this.oi)}allocateTargetId(e){return this.highestTargetId=this.ai.next(),ef.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.oi&&(this.oi=t),ef.resolve()}Pr(e){this.si.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.ai=new iH(t),this.highestTargetId=t),e.sequenceNumber>this.oi&&(this.oi=e.sequenceNumber)}addTargetData(e,t){return this.Pr(t),this.targetCount+=1,ef.resolve()}updateTargetData(e,t){return this.Pr(t),ef.resolve()}removeTargetData(e,t){return this.si.delete(t.target),this._i.jr(t.targetId),this.targetCount-=1,ef.resolve()}removeTargets(e,t,n){let r=0,i=[];return this.si.forEach((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.si.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)}),ef.waitFor(i).next(()=>r)}getTargetCount(e){return ef.resolve(this.targetCount)}getTargetData(e,t){let n=this.si.get(t)||null;return ef.resolve(n)}addMatchingKeys(e,t,n){return this._i.Wr(t,n),ef.resolve()}removeMatchingKeys(e,t,n){this._i.zr(t,n);let r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(t=>{i.push(r.markPotentiallyOrphaned(e,t))}),ef.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this._i.jr(t),ef.resolve()}getMatchingKeysForTargetId(e,t){let n=this._i.Hr(t);return ef.resolve(n)}containsKey(e,t){return ef.resolve(this._i.containsKey(t))}}class sd{constructor(e,t){this.ui={},this.overlays={},this.ci=new eD(0),this.li=!1,this.li=!0,this.hi=new ss,this.referenceDelegate=e(this),this.Pi=new sc(this),this.indexManager=new iP,this.remoteDocumentCache=new su(e=>this.referenceDelegate.Ti(e)),this.serializer=new it(t),this.Ii=new sr(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.li=!1,Promise.resolve()}get started(){return this.li}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new si,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ui[e.toKey()];return n||(n=new sl(t,this.referenceDelegate),this.ui[e.toKey()]=n),n}getGlobalsCache(){return this.hi}getTargetCache(){return this.Pi}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ii}runTransaction(e,t,n){E("MemoryPersistence","Starting transaction:",e);let r=new sf(this.ci.next());return this.referenceDelegate.Ei(),n(r).next(e=>this.referenceDelegate.di(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ai(e,t){return ef.or(Object.values(this.ui).map(n=>()=>n.containsKey(e,t)))}}class sf extends ec{constructor(e){super(),this.currentSequenceNumber=e}}class sm{constructor(e){this.persistence=e,this.Ri=new sa,this.Vi=null}static mi(e){return new sm(e)}get fi(){if(this.Vi)return this.Vi;throw x(60996)}addReference(e,t,n){return this.Ri.addReference(n,t),this.fi.delete(n.toString()),ef.resolve()}removeReference(e,t,n){return this.Ri.removeReference(n,t),this.fi.add(n.toString()),ef.resolve()}markPotentiallyOrphaned(e,t){return this.fi.add(t.toString()),ef.resolve()}removeTarget(e,t){this.Ri.jr(t.targetId).forEach(e=>this.fi.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.fi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ei(){this.Vi=new Set}di(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ef.forEach(this.fi,n=>{let r=W.fromPath(n);return this.gi(e,r).next(e=>{e||t.removeEntry(r,ee.min())})}).next(()=>(this.Vi=null,t.apply(e)))}updateLimboDocument(e,t){return this.gi(e,t).next(e=>{e?this.fi.delete(t.toString()):this.fi.add(t.toString())})}Ti(e){return 0}gi(e,t){return ef.or([()=>ef.resolve(this.Ri.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ai(e,t)])}}class sg{constructor(e,t){this.persistence=e,this.pi=new nX(e=>ek(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new i2(this,t)}static mi(e,t){return new sg(e,t)}Ei(){}di(e){return ef.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEac
6hTarget(e,t)}gr(e){let t=this.wr(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}wr(e){let t=0;return this.pr(e,e=>{t++}).next(()=>t)}pr(e,t){return ef.forEach(this.pi,(n,r)=>this.br(e,n,r).next(e=>e?ef.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.ii(e,r=>this.br(e,r,t).next(e=>{e||(n++,i.removeEntry(r,ee.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.pi.set(t,e.currentSequenceNumber),ef.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.pi.set(n,e.currentSequenceNumber),ef.resolve()}removeReference(e,t,n){return this.pi.set(n,e.currentSequenceNumber),ef.resolve()}updateLimboDocument(e,t){return this.pi.set(t,e.currentSequenceNumber),ef.resolve()}Ti(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(t1(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let n=t$(t);return n?16+e(n):16;case 5:return 2*t.stringValue.length;case 6:return tL(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,tx(r.fields,(t,n)=>{i+=t.length+e(n)}),i;default:throw x(13486,{value:t})}}(e.data.value)),t}br(e,t,n){return ef.or([()=>this.persistence.Ai(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.pi.get(t);return ef.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class sp{constructor(e){this.serializer=e}k(e,t,n,r){let i=new eg("createOrUpgrade",t);n<1&&r>=1&&(e.createObjectStore(eV),e.createObjectStore(eM,{keyPath:"userId"}),e.createObjectStore(eP,{keyPath:eF,autoIncrement:!0}).createIndex(eL,eU,{unique:!0}),e.createObjectStore(eq),sy(e),e.createObjectStore(eR));let s=ef.resolve();return n<3&&r>=3&&(0!==n&&(e.deleteObjectStore(eZ),e.deleteObjectStore(eJ),e.deleteObjectStore(e6),sy(e)),s=s.next(()=>(function(e){let t=e.store(e6),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ee.min().toTimestamp(),targetCount:0};return t.put(e5,n)})(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>i.store(eP).J().next(t=>{e.deleteObjectStore(eP),e.createObjectStore(eP,{keyPath:eF,autoIncrement:!0}).createIndex(eL,eU,{unique:!0});let n=i.store(eP),r=t.map(e=>n.put(e));return ef.waitFor(r)}))),s=s.next(()=>{e.createObjectStore(e8,{keyPath:"clientId"})})),n<5&&r>=5&&(s=s.next(()=>this.yi(i))),n<6&&r>=6&&(s=s.next(()=>(e.createObjectStore(eW),this.wi(i)))),n<7&&r>=7&&(s=s.next(()=>this.Si(i))),n<8&&r>=8&&(s=s.next(()=>this.bi(e,i))),n<9&&r>=9&&(s=s.next(()=>{e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&r>=10&&(s=s.next(()=>this.Di(i))),n<11&&r>=11&&(s=s.next(()=>{e.createObjectStore(e9,{keyPath:"bundleId"}),e.createObjectStore(e7,{keyPath:"name"})})),n<12&&r>=12&&(s=s.next(()=>{let t=e.createObjectStore(th,{keyPath:tc});t.createIndex(td,tf,{unique:!1}),t.createIndex(tm,tg,{unique:!1})})),n<13&&r>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore(ez,{keyPath:eK});t.createIndex(e$,eG),t.createIndex(ej,eQ)})(e)).next(()=>this.Ci(e,i)).next(()=>e.deleteObjectStore(eR))),n<14&&r>=14&&(s=s.next(()=>this.Fi(e,i))),n<15&&r>=15&&(s=s.next(()=>{e.createObjectStore(te,{keyPath:"indexId",autoIncrement:!0}).createIndex(tt,"collectionGroup",{unique:!1}),e.createObjectStore(tn,{keyPath:tr}).createIndex(ti,ts,{unique:!1}),e.createObjectStore(ta,{keyPath:to}).createIndex(tl,tu,{unique:!1})})),n<16&&r>=16&&(s=s.next(()=>{t.objectStore(tn).clear()}).next(()=>{t.objectStore(ta).clear()})),n<17&&r>=17&&(s=s.next(()=>{e.createObjectStore(tp,{keyPath:"name"})})),n<18&&r>=18&&(0,h.Ov)()&&(s=s.next(()=>{t.objectStore(tn).clear()}).next(()=>{t.objectStore(ta).clear()}
6)),s}wi(e){let t=0;return e.store(eR).ee((e,n)=>{t+=iG(n)}).next(()=>{let n={byteSize:t};return e.store(eW).put(eH,n)})}yi(e){let t=e.store(eM),n=e.store(eP);return t.J().next(t=>ef.forEach(t,t=>{let r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.J(eL,r).next(n=>ef.forEach(n,n=>{C(n.userId===t.userId,18650,"Cannot process batch from unexpected user",{batchId:n.batchId});let r=io(this.serializer,n);return i$(e,t.userId,r).next(()=>{})}))}))}Si(e){let t=e.store(eZ),n=e.store(eR);return e.store(e6).get(e5).next(e=>{let r=[];return n.ee((n,i)=>{let s=new G(n),a=[0,ek(s)];r.push(t.get(a).next(n=>n?ef.resolve():t.put({targetId:0,path:ek(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>ef.waitFor(r))})}bi(e,t){e.createObjectStore(e4,{keyPath:e3});let n=t.store(e4),r=new iF,i=e=>{if(r.add(e)){let t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:ek(r)})}};return t.store(eR).ee({X:!0},(e,t)=>i(new G(e).popLast())).next(()=>t.store(eq).ee({X:!0},([e,t,n],r)=>i(eA(t).popLast())))}Di(e){let t=e.store(eJ);return t.ee((e,n)=>{let r=il(n),i=iu(this.serializer,r);return t.put(i)})}Ci(e,t){let n=t.store(eR),r=[];return n.ee((e,n)=>{let i=t.store(ez),s=(n.document?new W(G.fromString(n.document.name).popFirst(5)):n.noDocument?W.fromSegments(n.noDocument.path):n.unknownDocument?W.fromSegments(n.unknownDocument.path):x(36783)).path.toArray(),a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))}).next(()=>ef.waitFor(r))}Fi(e,t){let n=t.store(eP),r=new i3(this.serializer),i=new sd(sm.mi,this.serializer.yt);return n.J().next(e=>{let n=new Map;return e.forEach(e=>{let t=n.get(e.userId)??n6();io(this.serializer,e).keys().forEach(e=>t=t.add(e)),n.set(e.userId,t)}),ef.forEach(n,(e,n)=>{let s=new y(n),a=ip.wt(this.serializer,s),o=i.getIndexManager(s);return new sn(r,ij.wt(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new tT(t,eD.ce),e).next()})})}}function sy(e){e.createObjectStore(eZ,{keyPath:e0}).createIndex(e1,e2,{unique:!0}),e.createObjectStore(eJ,{keyPath:"targetId"}).createIndex(eX,eY,{unique:!0}),e.createObjectStore(e6)}let sw="IndexedDbPersistence",sv="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 sI{constructor(e,t,n,r,i,s,a,o,l,u,h=18){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Mi=i,this.window=s,this.document=a,this.xi=l,this.Oi=u,this.Ni=h,this.ci=null,this.li=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Bi=null,this.inForeground=!1,this.Li=null,this.ki=null,this.qi=-1/0,this.Qi=e=>Promise.resolve(),!sI.v())throw new N(D.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new i5(this,r),this.$i=t+"main",this.serializer=new it(o),this.Ui=new ep(this.$i,this.Ni,new sp(this.serializer)),this.hi=new iy,this.Pi=new iJ(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new i3(this.serializer),this.Ii=new ig,this.window&&this.window.localStorage?this.Ki=this.window.localStorage:(this.Ki=null,!1===u&&T(sw,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Wi().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new N(D.FAILED_PRECONDITION,sv);return this.Gi(),this.zi(),this.ji(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Pi.getHighestSequenceNumber(e))}).then(e=>{this.ci=new eD(e,this.xi)}).then(()=>{this.li=!0}).catch(e=>(this.Ui&&this.Ui.close(),Promise.reject(e)))}Ji(e){return this.Qi=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.Ui.$(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Mi.enqueueAndForget(async()=>{this.started&&await this.Wi()}))}Wi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>tS(e,e8).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Hi(e).next(e=>{e||(this.isPrimary=!1,this.Mi.enqueueRetryable(()=>this.Qi(!1)))})}).next(()=>this.Yi(e)).next(t=>this.isPrimary&&!t?this.Zi(e).next(()=>!1):!!t&&this.Xi(e).next(()=>!0))).catch(e=>{if(eI(e))return E(sw,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return E(sw,"Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Mi.enqueueRetryable(()=>this.Qi(e)),this.isPrimary=e})}Hi(e){return tS(e,eV).get(eO).next(e=>ef.resolve(this.es(e)))}ts(e){return tS(e,e8).delete(this.clientId)}async ns(){if(this.isPrimary&&!this.rs(this.qi,18e5)){this.qi=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let t=tS(e,e8);return t.J().next(e=>{let n=this.ss(e,18e5),r=e.filter(e=>-1===n.indexOf(e));return ef.forEach(r,e=>t.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.Ki)for(let t of e)this.Ki.removeItem(this._s(t.clientId))}}ji(){this.ki=this.Mi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Wi().then(()=>this.ns()).then(()=>this.ji()))}es(e){return!!e&&e.ownerId===this.clientId}
6Yi(e){return this.Oi?ef.resolve(!0):tS(e,eV).get(eO).next(t=>{if(null!==t&&this.rs(t.leaseTimestampMs,5e3)&&!this.us(t.ownerId)){if(this.es(t)&&this.networkEnabled)return!0;if(!this.es(t)){if(!t.allowTabSynchronization)throw new N(D.FAILED_PRECONDITION,sv);return!1}}return!(!this.networkEnabled||!this.inForeground)||tS(e,e8).J().next(e=>void 0===this.ss(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&&E(sw,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.li=!1,this.cs(),this.ki&&(this.ki.cancel(),this.ki=null),this.ls(),this.hs(),await this.Ui.runTransaction("shutdown","readwrite",[eV,e8],e=>{let t=new tT(e,eD.ce);return this.Zi(t).next(()=>this.ts(t))}),this.Ui.close(),this.Ps()}ss(e,t){return e.filter(e=>this.rs(e.updateTimeMs,t)&&!this.us(e.clientId))}Ts(){return this.runTransaction("getActiveClients","readonly",e=>tS(e,e8).J().next(e=>this.ss(e,18e5).map(e=>e.clientId)))}get started(){return this.li}getGlobalsCache(){return this.hi}getMutationQueue(e,t){return ij.wt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Pi}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new iB(e,this.serializer.yt.databaseId)}getDocumentOverlayCache(e){return ip.wt(this.serializer,e)}getBundleCache(){return this.Ii}runTransaction(e,t,n){var r;let i;E(sw,"Starting transaction:",e);let s=18===(r=this.Ni)||17===r?tE:16===r||15===r?tI:14===r||13===r?tv:12===r?tw:11===r?ty:void x(60245);return this.Ui.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,r=>(i=new tT(r,this.ci?this.ci.next():eD.ce),"readwrite-primary"===t?this.Hi(i).next(e=>!!e||this.Yi(i)).next(t=>{if(!t)throw T(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.Mi.enqueueRetryable(()=>this.Qi(!1)),new N(D.FAILED_PRECONDITION,eh);return n(i)}).next(e=>
6this.Xi(i).next(()=>e)):this.Is(i).next(()=>n(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Is(e){return tS(e,eV).get(eO).next(e=>{if(null!==e&&this.rs(e.leaseTimestampMs,5e3)&&!this.us(e.ownerId)&&!this.es(e)&&!(this.Oi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new N(D.FAILED_PRECONDITION,sv)})}Xi(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return tS(e,eV).put(eO,t)}static v(){return ep.v()}Zi(e){let t=tS(e,eV);return t.get(eO).next(e=>this.es(e)?(E(sw,"Releasing primary lease."),t.delete(eO)):ef.resolve())}rs(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))}Gi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Li=()=>{this.Mi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Wi()))},this.document.addEventListener("visibilitychange",this.Li),this.inForeground="visible"===this.document.visibilityState)}ls(){this.Li&&(this.document.removeEventListener("visibilitychange",this.Li),this.Li=null)}zi(){"function"==typeof this.window?.addEventListener&&(this.Bi=()=>{this.cs();let e=/(?:Version|Mobile)\/1[456]/;(0,h.nr)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.Mi.enterRestrictedMode(!0),this.Mi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Bi))}hs(){this.Bi&&(this.window.removeEventListener("pagehide",this.Bi),this.Bi=null)}us(e){try{let t=null!==this.Ki?.getItem(this._s(e));return E(sw,`Client '${e}' ${t?"is":"is not"} zombied in LocalStorage`),t}catch(e){return T(sw,"Failed to get zombied client id.",e),!1}}cs(){if(this.Ki)try{this.Ki.setItem(this._s(this.clientId),String(Date.now()))}catch(e){T("Failed to set zombie client id.",e)}}Ps(){if(this.Ki)try{this.Ki.removeItem(this._s(this.clientId))}catch(e){}}_s(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sE(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class sT{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Es=n,this.ds=r}static As(e,t){let n=n6(),r=n6();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 sT(e,t.fromCache,n,r)}}class sS{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class sb{constructor(){this.Rs=!1,this.Vs=!1,this.fs=100,this.gs=(0,h.nr)()?8:ey((0,h.ZQ)())>0?6:4}initialize(e,t){this.ps=e,this.indexManager=t,this.Rs=!0}getDocumentsMatchingQuery(e,t,n,r){let i={result:null};return this.ys(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.ws(e,t,r,n).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let n=new sS;return this.Ss(e,t,n).next(r=>{if(i.result=r,this.Vs)return this.bs(e,t,n,r.size)})}).next(()=>i.result)}bs(e,t,n,r){return n.documentReadCount<this.fs?(I()<=u.$b.DEBUG&&E("QueryEngine","SDK will not create cache indexes for query:",nQ(t),"since it only creates cache indexes for collection contains","more than or equal to",this.fs,"documents"),ef.resolve()):(I()<=u.$b.DEBUG&&E("QueryEngine","Query:",nQ(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.gs*r?(I()<=u.$b.DEBUG&&E("QueryEngine","The SDK decides to create cache indexes for query:",nQ(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,nK(t))):ef.resolve())}ys(e,t){if(nq(t))return ef.resolve(null);let n=nK(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=nK(t=n$(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let i=n6(...r);return this.ps.getDocuments(e,i).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{let s=this.Ds(t,r);return this.Cs(t,s,i,n.readTime)?this.ys(e,n$(t,null,"F")):this.vs(e,s,t,n)}))})))}ws(e,t,n,r){return nq(t)||r.isEqual(ee.min())?ef.resolve(null):this.ps.getDocuments(e,n).next(i=>{let s=this.Ds(t,i);return this.Cs(t,s,n,r)?ef.resolve(null):(I()<=u.$b.DEBUG&&E("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),nQ(t)),this.vs(e,s,t,ea(r,-1)).next(e=>e))})}Ds(e,t){let n=new tN(nJ(e));return t.forEach((t,r)=>{nW(e,r)&&(n=n.add(r))}),n}Cs(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)}Ss(e,t,n){return I()<=u.$b.DEBUG&&E("QueryEngine","Using full collection scan to execute query:",nQ(t)),this.ps.getDocumentsMatchingQuery(e,t,el.min(),n)}vs(e,t,n,r){return this.ps.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let sx="LocalStore";class s_{constructor(e,t,n,r){this.persistence=e,this.Fs=t,this.serializer
6=r,this.Ms=new t_(U),this.xs=new nX(e=>nO(e),nM),this.Os=new Map,this.Ns=e.getRemoteDocumentCache(),this.Pi=e.getTargetCache(),this.Ii=e.getBundleCache(),this.Bs(n)}Bs(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new sn(this.Ns,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Ns.setIndexManager(this.indexManager),this.Fs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Ms))}}async function sC(e,t){return await e.persistence.runTransaction("Handle user change","readonly",n=>{let r;return e.mutationQueue.getAllMutationBatches(n).next(i=>(r=i,e.Bs(t),e.mutationQueue.getAllMutationBatches(n))).next(t=>{let i=[],s=[],a=n6();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=>({Ls:e,removedBatchIds:i,addedBatchIds:s}))})})}function sD(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Pi.getLastRemoteSnapshotVersion(t))}function sN(e,t){return e.persistence.runTransaction("Allocate target","readwrite",n=>{let r;return e.Pi.getTargetData(n,t).next(i=>i?(r=i,ef.resolve(r)):e.Pi.allocateTargetId(n).next(i=>(r=new ie(t,i,"TargetPurposeListen",n.currentSequenceNumber),e.Pi.addTargetData(n,r).next(()=>r))))}).then(n=>{let r=e.Ms.get(n.targetId);return(null===r||n.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(e.Ms=e.Ms.insert(n.targetId,n),e.xs.set(t,n.targetId)),n})}async function sk(e,t,n){let r=e.Ms.get(t);try{n||await e.persistence.runTransaction("Release target",n?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,r))}catch(e){if(!eI(e))throw e;E(sx,`Failed to update sequence numbers for target ${t}: ${e}`)}e.Ms=e.Ms.remove(t),e.xs.delete(r.target)}function sA(e,t,n){let r=ee.min(),i=n6();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,n){let r=e.xs.get(n);return void 0!==r?ef.resolve(e.Ms.get(r)):e.Pi.getTargetData(t,n)})(e,s,nK(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,e.Pi.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e.Fs.getDocumentsMatchingQuery(s,t,n?r:ee.min(),n?i:n6())).next(n=>(sO(e,nH(t),n),{documents:n,Qs:i})))}function sR(e,t){let n=e.Pi,r=e.Ms.get(t);return r?Promise.resolve(r.target):e.persistence.runTransaction("Get target data","readonly",e=>n.At(e,t).next(e=>e?e.target:null))}function sV(e,t){let n=e.Os.get(t)||ee.min();return e.persistence.runTransaction("Get new document changes","readonly",r=>e.Ns.getAllFromCollectionGroup(r,t,ea(n,-1),Number.MAX_SAFE_INTEGER)).then(n=>(sO(e,t,n),n))}function sO(e,t,n){let r=e.Os.get(t)||ee.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.Os.set(t,r)}let sM="firestore_clients";function sP(e,t){return`${sM}_${e}_${t}`}let sF="firestore_mutations";function sL(e,t,n){let r=`${sF}_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}let sU="firestore_targets";function sB(e,t){return`${sU}_${e}_${t}`}let sq="SharedClientState";class sz{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Ws(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 N(r.error.code,r.error.message)),s?new sz(e,t,r.state,i):(T(sq,`Failed to parse mutation state for ID '${t}': ${n}`),null)}Gs(){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 sK{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Ws(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 N(n.error.code,n.error.message)),i?new sK(e,n.state,r):(T(sq,`Failed to parse target state for ID '${e}': ${t}`),null)}Gs(){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 s${constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Ws(e,t){let n=JSON.parse(t),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=n4;for(let e=0;r&&e<n.activeTargetIds.length;++e){var s;r="number"==typeof(s=n.activeTargetIds[e])&&Number.isInteger(s)&&!eN(s)&&s<=Number.MAX_SAFE_INTEGER&&s>=Number.MIN_SAFE_INTEGER,i=i.add(n.activeTargetIds[e])}return r?new s$(e,i):(T(sq,`Failed to parse client data for instance '${e}': ${t}`),null)}}class sG{constructor(e,t){this.clientId=e,this.onlineState=t}static Ws(e){let t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new sG(t.clientId,t.onlineState):(T(sq,`Failed to parse online state: ${e}`),null)}}class sj{constructor(){this.activeTargetIds=n4}zs(e){this.activeTargetIds=this.activeTargetIds.add(e)}js(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Gs(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class sQ{constructor(e,t,n,r,i){var s,a,o;this.window=e,this.Mi=t,this.persistenceKey=n,this.Js=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Hs=this.Ys.bind(this),this.Zs=new t_(U),this.started=!1,this.Xs=[];let l=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.eo=sP(this.persistenceKey,this.Js),this.no=(s=this.persistenceKey,`firestore_sequence_number_${s}`),this.Zs=this.Zs.insert(this.Js,new sj),this.ro=RegExp(`^${sM}_${l}_([^_]*)$`),this.io=RegExp(`^${sF}_${l}_(\\d+)(?:_(.*))?$`),this.so=RegExp(`^${sU}_${l}_(\\d+)$`),this.oo=(a=this.persistenceKey,`firestore_online_state_${a}`),this._o=(o=this.persistenceKey,`firestore_bundle_loaded_v2_${o}`),this.window.addEventListener("storage",this.Hs)}static v(e){return!(!e||!e.localStorage)}async start(){for(let e of(await this.syncEngine.Ts())){if(e===this.Js)continue;let t=this.getItem(sP(this.persistenceKey,e));if(t){let n=s$.Ws(e,t);n&&(this.Zs=this.Zs.insert(n.clientId,n))}}this.ao();let e=this.storage.getItem(this.oo);if(e){let t=this.uo(e);t&&this.co(t)}for(let e of this.Xs)this.Ys(e);this.Xs=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.no,JSON.stringify(e))}getAllActiveQueryTargets(){return this.lo(this.Zs)}isActiveQueryTarget(e){let t=!1;return this.Zs.forEach((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.ho(e,"pending")}
6updateMutationState(e,t,n){this.ho(e,t,n),this.Po(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){let t=this.storage.getItem(sB(this.persistenceKey,e));if(t){let r=sK.Ws(e,t);r&&(n=r.state)}}return t&&this.To.zs(e),this.ao(),n}removeLocalQueryTarget(e){this.To.js(e),this.ao()}isLocalQueryTarget(e){return this.To.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(sB(this.persistenceKey,e))}updateQueryState(e,t,n){this.Io(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Po(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Eo(e)}notifyBundleLoaded(e){this.Ao(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Hs),this.removeItem(this.eo),this.started=!1)}getItem(e){let t=this.storage.getItem(e);return E(sq,"READ",e,t),t}setItem(e,t){E(sq,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){E(sq,"REMOVE",e),this.storage.removeItem(e)}Ys(e){if(e.storageArea===this.storage){if(E(sq,"EVENT",e.key,e.newValue),e.key===this.eo)return void T("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Mi.enqueueRetryable(async()=>{if(this.started){if(null!==e.key){if(this.ro.test(e.key)){if(null==e.newValue){let t=this.Ro(e.key);return this.Vo(t,null)}{let t=this.mo(e.key,e.newValue);if(t)return this.Vo(t.clientId,t)}}else if(this.io.test(e.key)){if(null!==e.newValue){let t=this.fo(e.key,e.newValue);if(t)return this.po(t)}}else if(this.so.test(e.key)){if(null!==e.newValue){let t=this.yo(e.key,e.newValue);if(t)return this.wo(t)}}else if(e.key===this.oo){if(null!==e.newValue){let t=this.uo(e.newValue);if(t)return this.co(t)}}else if(e.key===this.no){let t=function(e){let t=eD.ce;if(null!=e)try{let n=JSON.parse(e);C("number"==typeof n,30636,{So:e}),t=n}catch(e){T(sq,"Failed to read sequence number from WebStorage",e)}return t}(e.newValue);t!==eD.ce&&this.sequenceNumberHandler(t)}else if(e.key===this._o){let t=this.bo(e.newValue);await Promise.all(t.map(e=>this.syncEngine.Do(e)))}}}else this.Xs.push(e)})}}get To(){return this.Zs.get(this.Js)}ao(){this.setItem(this.eo,this.To.Gs())}ho(e,t,n){let r=new sz(this.currentUser,e,t,n),i=sL(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Gs())}Po(e){let t=sL(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Eo(e){let t={clientId:this.Js,onlineState:e};this.storage.setItem(this.oo,JSON.stringify(t))}Io(e,t,n){let r=sB(this.persistenceKey,e),i=new sK(e,t,n);this.setItem(r,i.Gs())}Ao(e){let t=JSON.stringify(Array.from(e));this.setItem(this._o,t)}Ro(e){let t=this.ro.exec(e);return t?t[1]:null}mo(e,t){let n=this.Ro(e);return s$.Ws(n,t)}fo(e,t){let n=this.io.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return sz.Ws(new y(i),r,t)}yo(e,t){let n=Number(this.so.exec(e)[1]);return sK.Ws(n,t)}uo(e){return sG.Ws(e)}bo(e){return JSON.parse(e)}async po(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Co(e.batchId,e.state,e.error);E(sq,`Ignoring mutation for non-active user ${e.user.uid}`)}wo(e){return this.syncEngine.vo(e.targetId,e.state,e.error)}Vo(e,t){let n=t?this.Zs.insert(e,t):this.Zs.remove(e),r=this.lo(this.Zs),i=this.lo(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Fo(s,a).then(()=>{this.Zs=n})}co(e){this.Zs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}lo(e){let t=n4;return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class sW{constructor(){this.Mo=new sj,this.xo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.Mo.zs(e),this.xo[e]||"not-current"}updateQueryState(e,t,n){this.xo[e]=t}removeLocalQueryTarget(e){this.Mo.js(e)}isLocalQueryTarget(e){return this.Mo.activeTargetIds.has(e)}clearQueryState(e){delete this.xo[e]}getAllActiveQueryTargets(){return this.Mo.activeTargetIds}isActiveQueryTarget(e){return this.Mo.activeTargetIds.has(e)}start(){return this.Mo=new sj,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class sH{Oo(e){}shutdown(){}}let sJ="ConnectivityMonitor";class sX{constructor(){this.No=()=>this.Bo(),this.Lo=()=>this.ko(),this.qo=[],this.Qo()}Oo(e){this.qo.push(e)}shutdown(){window.removeEventListener("online",this.No),window.removeEventListener("offline",this.Lo)}Qo(){window.addEventListener("online",this.No),window.addEventListener("offline",this.Lo)}Bo(){for(let e of(E(sJ,"Network connectivity changed: AVAILABLE"),this.qo))e(0)}ko(){for(let e of(E(sJ,"Network connectivity changed: UNAVAILABLE"),this.qo))e(1)}static v(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let sY=null;function sZ(){return null===sY?sY=0x10000000+Math.round(0x80000000*Math.random()):sY++,"0x"+sY.toString(16)}let s0="RestConnection",s1={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
6Query:"runAggregationQuery"};class s2{get $o(){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.Uo=t+"://"+e.host,this.Ko=`projects/${n}/databases/${r}`,this.Wo=this.databaseId.database===tQ?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Go(e,t,n,r,i){let s=sZ(),a=this.zo(e,t.toUriEncodedString());E(s0,`Sending RPC '${e}' ${s}:`,a,n);let o={"google-cloud-resource-prefix":this.Ko,"x-goog-request-params":this.Wo};this.jo(o,r,i);let{host:l}=new URL(a),u=(0,h.zJ)(l);return this.Jo(e,a,o,n,u).then(t=>(E(s0,`Received RPC '${e}' ${s}: `,t),t),t=>{throw S(s0,`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",n),t})}Ho(e,t,n,r,i,s){return this.Go(e,t,n,r,i)}jo(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)}zo(e,t){let n=s1[e];return`${this.Uo}/v1/${t}:${n}`}terminate(){}}class s5{constructor(e){this.Yo=e.Yo,this.Zo=e.Zo}Xo(e){this.e_=e}t_(e){this.n_=e}r_(e){this.i_=e}onMessage(e){this.s_=e}close(){this.Zo()}send(e){this.Yo(e)}o_(){this.e_()}__(){this.n_()}a_(e){this.i_(e)}u_(e){this.s_(e)}}let s6="WebChannelConnection";class s4 extends s2{constructor(e){super(e),this.c_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Jo(e,t,n,r,i){let s=sZ();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();E(s6,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case d.O4.TIMEOUT:E(s6,`RPC '${e}' ${s} timed out`),a(new N(D.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(E(s6,`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=e?.error;if(t&&t.status&&t.message){let e=function(e){let t=e.toLowerCase().replace(/_/g,"-");return Object.values(D).indexOf(t)>=0?t:D.UNKNOWN}(t.status);a(new N(e,t.message))}else a(new N(D.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new N(D.UNAVAILABLE,"Connection failed."));break;default:x(9055,{l_:e,streamId:s,h_:o.getLastErrorCode(),P_:o.getLastError()})}}finally{E(s6,`RPC '${e}' ${s} completed.`)}});let l=JSON.stringify(r);E(s6,`RPC '${e}' ${s} sending request:`,r),o.send(t,"POST",l,n,15)})}T_(e,t,n){let i=sZ(),s=[this.Uo,"/","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.jo(l.initMessageHeaders,t,n),l.encodeInitMessageHeaders=!0;let h=s.join("");E(s6,`Creating RPC '${e}' stream ${i}: ${h}`,l);let c=a.createWebChannel(h,l);this.I_(c);let f=!1,m=!1,g=new s5({Yo:t=>{m?E(s6,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(f||(E(s6,`Opening RPC '${e}' stream ${i} transport.`),c.open(),f=!0),E(s6,`RPC '${e}' stream ${i} sending:`,t),c.send(t))},Zo:()=>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||(E(s6,`RPC '${e}' stream ${i} transport opened.`),g.o_())}),p(c,d.iO.EventType.CLOSE,()=>{m||(m=!0,E(s6,`RPC '${e}' stream ${i} transport closed`),g.a_(),this.E_(c))}),p(c,d.iO.EventType.ERROR,t=>{m||(m=!0,S(s6,`RPC '${e}' stream ${i} transport errored. Name:`,t.name,"Message:",t.message),g.a_(new N(D.UNAVAILABLE,"The operation could not be completed")))}),p(c,d.iO.EventType.MESSAGE,t=>{if(!m){let n=t.data[0];C(!!n,16349);let s=n?.error||n[0]?.error;if(s){E(s6,`RPC '${e}' stream ${i} received error:`,s);let t=s.status,n=function(e){let t=r[e];if(void 0!==t)return rb(t)}(t),a=s.message;void 0===n&&(n=D.INTERNAL,a="Unknown error status: "+t+" with message "+s.message),m=!0,g.a_(new N(n,a)),c.close()}else E(s6,`RPC '${e}' stream ${i} received:`,n),g.u_(n)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?E(s6,`RPC '${e}' stream ${i} detected buffering proxy`):t.stat===d.ro.NOPROXY&&E(s6,`RPC '${e}' stream ${i} detected no buffering proxy`)}),setTimeout(()=>{g.__()},0),g}
6terminate(){this.c_.forEach(e=>e.close()),this.c_=[]}I_(e){this.c_.push(e)}E_(e){this.c_=this.c_.filter(t=>t===e)}}function s3(){return"undefined"!=typeof window?window:null}function s8(){return"undefined"!=typeof document?document:null}class s9{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Mi=e,this.timerId=t,this.d_=n,this.A_=r,this.R_=i,this.V_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.V_=0}g_(){this.V_=this.R_}p_(e){this.cancel();let t=Math.floor(this.V_+this.y_()),n=Math.max(0,Date.now()-this.f_),r=Math.max(0,t-n);r>0&&E("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.V_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.m_=this.Mi.enqueueAfterDelay(this.timerId,r,()=>(this.f_=Date.now(),e())),this.V_*=this.A_,this.V_<this.d_&&(this.V_=this.d_),this.V_>this.R_&&(this.V_=this.R_)}w_(){null!==this.m_&&(this.m_.skipDelay(),this.m_=null)}cancel(){null!==this.m_&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.V_}}let s7="PersistentStream";class ae{constructor(e,t,n,r,i,s,a,o){this.Mi=e,this.S_=n,this.b_=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new s9(e,t)}x_(){return 1===this.state||5===this.state||this.O_()}O_(){return 2===this.state||3===this.state}start(){this.F_=0,4!==this.state?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&null===this.C_&&(this.C_=this.Mi.enqueueAfterDelay(this.S_,6e4,()=>this.k_()))}q_(e){this.Q_(),this.stream.send(e)}async k_(){if(this.O_())return this.close(0)}Q_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.Q_(),this.U_(),this.M_.cancel(),this.D_++,4!==e?this.M_.reset():t&&t.code===D.RESOURCE_EXHAUSTED?(T(t.toString()),T("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):t&&t.code===D.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.K_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.r_(t)}K_(){}auth(){this.state=1;let e=this.W_(this.D_),t=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.D_===t&&this.G_(e,n)},t=>{e(()=>{let e=new N(D.UNKNOWN,"Fetching auth token failed: "+t.message);return this.z_(e)})})}G_(e,t){let n=this.W_(this.D_);this.stream=this.j_(e,t),this.stream.Xo(()=>{n(()=>this.listener.Xo())}),this.stream.t_(()=>{n(()=>(this.state=2,this.v_=this.Mi.enqueueAfterDelay(this.b_,1e4,()=>(this.O_()&&(this.state=3),Promise.resolve())),this.listener.t_()))}),this.stream.r_(e=>{n(()=>this.z_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.F_?this.J_(e):this.onNext(e))})}N_(){this.state=5,this.M_.p_(async()=>{this.state=0,this.start()})}z_(e){return E(s7,`close with error: ${e}`),this.stream=null,this.close(4,e)}W_(e){return t=>{this.Mi.enqueueAndForget(()=>this.D_===e?t():(E(s7,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class at extends ae{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}j_(e,t){return this.connection.T_("Listen",e,t)}J_(e){return this.onNext(e)}onNext(e){this.M_.reset();let t=function(e,t){let n;if("targetChange"in t){var r,i;t.targetChange;let s="NO_CHANGE"===(r=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===r?1:"REMOVE"===r?2:"CURRENT"===r?3:"RESET"===r?4:x(39313,{state:r}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(C(void 0===i||"string"==typeof i,58123),tO.fromBase64String(i||"")):(C(void 0===i||i instanceof m||i instanceof Uint8Array,16193),tO.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;n=new rO(s,a,o,l&&new N(void 0===l.code?D.UNKNOWN:rb(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=rJ(e,r.document.name),s=rG(r.document.updateTime),a=r.document.createTime?rG(r.document.createTime):ee.min(),o=new nh({mapValue:{fields:r.document.fields}}),l=nc.newFoundDocument(i,s,a,o);n=new rR(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let i=rJ(e,r.document),s=r.readTime?rG(r.readTime):ee.min(),a=nc.newNoDocument(i,s);n=new rR([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let i=rJ(e,r.document);n=new rR([],r.removedTargetIds||[],i,null)}else{if(!("filter"in t))return x(11601,{Rt:t});{t.filter;let e=t.filter;e.targetId;
6let{count:r=0,unchangedNames:i}=e,s=new rS(r,i);n=new rV(e.targetId,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ee.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?ee.min():t.readTime?rG(t.readTime):ee.min()}(e);return this.listener.H_(t,n)}Y_(e){let t={};t.database=rZ(this.serializer),t.addTarget=function(e,t){let n,r=t.target;if((n=nP(r)?{documents:r6(e,r)}:{query:r4(e,r).ft}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){var i;i=t.resumeToken,n.resumeToken=e.useProto3Json?i.toBase64():i.toUint8Array();let r=rK(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(ee.min())>0){n.readTime=r$(e,t.snapshotVersion.toTimestamp());let r=rK(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);let n=function(e,t){let n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return x(28987,{purpose:e})}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.q_(t)}Z_(e){let t={};t.database=rZ(this.serializer),t.removeTarget=e,this.q_(t)}}class an extends ae{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 X_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}K_(){this.X_&&this.ea([])}j_(e,t){return this.connection.T_("Write",e,t)}J_(e){return C(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,C(!e.writeResults||0===e.writeResults.length,55816),this.listener.ta()}onNext(e){var t,n;C(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.M_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(C(void 0!==n,14353),t.map(e=>{let t;return(t=e.updateTime?rG(e.updateTime):rG(n)).isEqual(ee.min())&&(t=rG(n)),new ra(t,e.transformResults||[])})):[]),i=rG(e.commitTime);return this.listener.na(i,r)}ra(){let e={};e.database=rZ(this.serializer),this.q_(e)}ea(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>r2(this.serializer,e))};this.q_(t)}}class ar{}class ai extends ar{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.ia=!1}sa(){if(this.ia)throw new N(D.FAILED_PRECONDITION,"The client has already been terminated.")}Go(e,t,n,r){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.Go(e,rQ(t,n),r,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===D.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(D.UNKNOWN,e.toString())})}Ho(e,t,n,r,i){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.Ho(e,rQ(t,n),r,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===D.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(D.UNKNOWN,e.toString())})}terminate(){this.ia=!0,this.connection.terminate()}}class as{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){0===this.oa&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve())))}ha(e){"Online"===this.state?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ca("Offline")))}set(e){this.Pa(),this.oa=0,"Online"===e&&(this.aa=!1),this.ca(e)}ca(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}la(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.aa?(T(t),this.aa=!1):E("OnlineStateTracker",t)}Pa(){null!==this._a&&(this._a.cancel(),this._a=null)}}let aa="RemoteStore";class ao{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Ta=[],this.Ia=new Map,this.Ea=new Set,this.da=[],this.Aa=i,this.Aa.Oo(e=>{n.enqueueAndForget(async()=>
7{ap(this)&&(E(aa,"Restarting streams for network reachability change."),await async function(e){e.Ea.add(4),await au(e),e.Ra.set("Unknown"),e.Ea.delete(4),await al(e)}(this))})}),this.Ra=new as(n,r)}}async function al(e){if(ap(e))for(let t of e.da)await t(!0)}async function au(e){for(let t of e.da)await t(!1)}function ah(e,t){e.Ia.has(t.targetId)||(e.Ia.set(t.targetId,t),ag(e)?am(e):aR(e).O_()&&ad(e,t))}function ac(e,t){let n=aR(e);e.Ia.delete(t),n.O_()&&af(e,t),0===e.Ia.size&&(n.O_()?n.L_():ap(e)&&e.Ra.set("Unknown"))}function ad(e,t){if(e.Va.Ue(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(ee.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}aR(e).Y_(t)}function af(e,t){e.Va.Ue(t),aR(e).Z_(t)}function am(e){e.Va=new rP({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),At:t=>e.Ia.get(t)||null,ht:()=>e.datastore.serializer.databaseId}),aR(e).start(),e.Ra.ua()}function ag(e){return ap(e)&&!aR(e).x_()&&e.Ia.size>0}function ap(e){return 0===e.Ea.size}async function ay(e){e.Ra.set("Online")}async function aw(e){e.Ia.forEach((t,n)=>{ad(e,t)})}async function av(e,t){e.Va=void 0,ag(e)?(e.Ra.ha(t),am(e)):e.Ra.set("Unknown")}
7async function aI(e,t,n){if(e.Ra.set("Online"),t instanceof rO&&2===t.state&&t.cause)try{await async function(e,t){let n=t.cause;for(let r of t.targetIds)e.Ia.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Ia.delete(r),e.Va.removeTarget(r))}(e,t)}catch(n){E(aa,"Failed to remove targets %s: %s ",t.targetIds.join(","),n),await aE(e,n)}else if(t instanceof rR?e.Va.Ze(t):t instanceof rV?e.Va.st(t):e.Va.tt(t),!n.isEqual(ee.min()))try{let t=await sD(e.localStore);n.compareTo(t)>=0&&await function(e,t){let n=e.Va.Tt(t);return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){let i=e.Ia.get(r);i&&e.Ia.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{let r=e.Ia.get(t);if(!r)return;e.Ia.set(t,r.withResumeToken(tO.EMPTY_BYTE_STRING,r.snapshotVersion)),af(e,t);let i=new ie(r.target,t,n,r.sequenceNumber);ad(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){E(aa,"Failed to raise snapshot:",t),await aE(e,t)}}async function aE(e,t,n){if(!eI(t))throw t;e.Ea.add(1),await au(e),e.Ra.set("Offline"),n||(n=()=>sD(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{E(aa,"Retrying IndexedDB access"),await n(),e.Ea.delete(1),await al(e)})}function aT(e,t){return t().catch(n=>aE(e,n,t))}async function aS(e){var t;let n=aV(e),r=e.Ta.length>0?e.Ta[e.Ta.length-1].batchId:-1;for(;ap(t=e)&&t.Ta.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.Ta.length&&n.L_();break}r=t.batchId,function(e,t){e.Ta.push(t);let n=aV(e);n.O_()&&n.X_&&n.ea(t.mutations)}(e,t)}catch(t){await aE(e,t)}ab(e)&&ax(e)}function ab(e){return ap(e)&&!aV(e).x_()&&e.Ta.length>0}function ax(e){aV(e).start()}async function a_(e){aV(e).ra()}async function aC(e){let t=aV(e);for(let n of e.Ta)t.ea(n.mutations)}async function aD(e,t,n){let r=e.Ta.shift(),i=rE.from(r,t,n);await aT(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await aS(e)}async function aN(e,t){t&&aV(e).X_&&await async function(e,t){var n;if(function(e){switch(e){case D.OK:return x(64938);case D.CANCELLED:case D.UNKNOWN:case D.DEADLINE_EXCEEDED:case D.RESOURCE_EXHAUSTED:case D.INTERNAL:case D.UNAVAILABLE:case D.UNAUTHENTICATED:return!1;case D.INVALID_ARGUMENT:case D.NOT_FOUND:case D.ALREADY_EXISTS:case D.PERMISSION_DENIED:case D.FAILED_PRECONDITION:case D.ABORTED:case D.OUT_OF_RANGE:case D.UNIMPLEMENTED:case D.DATA_LOSS:return!0;default:return x(15467,{code:e})}}(n=t.code)&&n!==D.ABORTED){let n=e.Ta.shift();aV(e).B_(),await aT(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await aS(e)}}(e,t),ab(e)&&ax(e)}async function ak(e,t){e.asyncQueue.verifyOperationInProgress(),E(aa,"RemoteStore received new credentials");let n=ap(e);e.Ea.add(3),await au(e),n&&e.Ra.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.Ea.delete(3),await al(e)}async function aA(e,t){t?(e.Ea.delete(2),await al(e)):t||(e.Ea.add(2),await au(e),e.Ra.set("Unknown"))}function aR(e){var t,n,r;return e.ma||(t=e.datastore,n=e.asyncQueue,r={Xo:ay.bind(null,e),t_:aw.bind(null,e),r_:av.bind(null,e),H_:aI.bind(null,e)},t.sa(),e.ma=new at(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.ma.B_(),ag(e)?am(e):e.Ra.set("Unknown")):(await e.ma.stop(),e.Va=void 0)})),e.ma}function aV(e){var t,n,r;return e.fa||(t=e.datastore,n=e.asyncQueue,r={Xo:()=>Promise.resolve(),t_:a_.bind(null,e),r_:aN.bind(null,e),ta:aC.bind(null,e),na:aD.bind(null,e)},t.sa(),e.fa=new an(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.da.push(async t=>{t?(e.fa.B_(),await aS(e)):(await e.fa.stop(),e.Ta.length>0&&(E(aa,`Stopping write stream with ${e.Ta.length} pending writes`),e.Ta=[]))})),e.fa}class aO{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 aO(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 N(D.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 aM(e,t){if(T("AsyncQueue",`${t}: ${e}`),eI(e))return new N(D.UNAVAILABLE,`${t}: ${e}`);throw e}class aP{static emptySet(e){return new aP(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||W.comparator(t.key,n.key):(e,t)=>W.comparator(e.key,t.key),this.keyedMap=n0(),this.sortedSet=new t_(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 aP)||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 aP;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class aF{constructor(){this.ga=new t_(W.comparator)}track(e){let t=e.doc.key,n=this.ga.get(t);n?0!==e.type&&3===n.type?this.ga=this.ga.insert(t,e):3===e.type&&1!==n.type?this.ga=this.ga.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.ga=this.ga.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.ga=this.ga.remove(t):1===e.type&&2===n.type?this.ga=this.ga.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):x(63341,{Rt:e,pa:n}):this.ga=this.ga.insert(t,e)}ya(){let e=[];return this.ga.inorderTraversal((t,n)=>{e.push(n)}),e}}class aL{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 aL(e,t,aP.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)&&nG(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 aU{constructor(){this.wa=void 0,this.Sa=[]}ba(){return this.Sa.some(e=>e.Da())}}class aB{constructor(){this.queries=aq(),this.onlineState="Unknown",this.Ca=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=aq(),n.forEach((e,n)=>{for(let e of n.Sa)e.onError(t)})}(this,new N(D.ABORTED,"Firestore shutting down"))}}function aq(){return new nX(e=>nj(e),nG)}async function az(e,t){let n=3,r=t.query,i=e.queries.get(r);i?!i.ba()&&t.Da()&&(n=2):(i=new aU,n=+!t.Da());try{switch(n){case 0:i.wa=await e.onListen(r,!0);break;case 1:i.wa=await e.onListen(r,!1);break;case 2:await e.onFirstRemoteStoreListen(r)}}catch(n){let e=aM(n,`Initialization of query '${nQ(t.query)}' failed`);return void t.onError(e)}e.queries.set(r,i),i.Sa.push(t),t.va(e.onlineState),i.wa&&t.Fa(i.wa)&&aj(e)}async function aK(e,t){let n=t.query,r=3,i=e.queries.get(n);if(i){let e=i.Sa.indexOf(t);e>=0&&(i.Sa.splice(e,1),0===i.Sa.length?r=+!t.Da():!i.ba()&&t.Da()&&(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 a$(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.Sa)e.Fa(r)&&(n=!0);i.wa=r}}n&&aj(e)}function aG(e,t,n){let r=e.queries.get(t);if(r)for(let e of r.Sa)e.onError(n);e.queries.delete(t)}function aj(e){e.Ca.forEach(e=>{e.next()})}(a=s||(s={})).Ma="default",a.Cache="cache";class aQ{constructor(e,t,n){this.query=e,this.xa=t,this.Oa=!1,this.Na=null,this.onlineState="Unknown",this.options=n||{}}Fa(e){if(!this.options.includeMetadataChanges){let t=[];for(let n of e.docChanges)3!==n.type&&t.push(n);e=new aL(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Oa?this.Ba(e)&&(this.xa.next(e),t=!0):this.La(e,this.onlineState)&&(this.ka(e),t=!0),this.Na=e,t}onError(e){this.xa.error(e)}va(e){this.onlineState=e;let t=!1;return this.Na&&!this.Oa&&this.La(this.Na,e)&&(this.ka(this.Na),t=!0),t}La(e,t){return!(e.fromCache&&this.Da())||(!this.options.qa||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Ba(e){if(e.docChanges.length>0)return!0;let t=this.Na&&this.Na.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}ka(e){e=aL.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Oa=!0,this.xa.next(e)}Da(){return this.options.source!==s.Cache}}class aW{constructor(e){this.key=e}}class aH{constructor(e){this.key=e}}class aJ{constructor(e,t){this.query=e,this.Ya=t,this.Za=null,this.hasCachedResults=!1,this.current=!1,this.Xa=n6(),this.mutatedKeys=n6(),this.eu=nJ(e),this.tu=new aP(this.eu)}get nu(){return this.Ya}ru(e,t){let n=t?t.iu:new aF,r=t?t.tu:this.tu,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=nW(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.su(u,h)||(n.track({type:2,doc:h}),f=!0,(o&&this.eu(h,o)>0||l&&0>this.eu(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;
7){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{tu:s,iu:n,Cs:a,mutatedKeys:i}}su(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){let i=this.tu;this.tu=e.tu,this.mutatedKeys=e.mutatedKeys;let s=e.iu.ya();s.sort((e,t)=>(function(e,t){let n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return x(20277,{Rt:e})}};return n(e)-n(t)})(e.type,t.type)||this.eu(e.doc,t.doc)),this.ou(n),r=r??!1;let a=t&&!r?this._u():[],o=0===this.Xa.size&&this.current&&!r?1:0,l=o!==this.Za;return(this.Za=o,0!==s.length||l)?{snapshot:new aL(this.query,e.tu,i,s,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),au:a}:{au:a}}va(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({tu:this.tu,iu:new aF,mutatedKeys:this.mutatedKeys,Cs:!1},!1)):{au:[]}}uu(e){return!this.Ya.has(e)&&!!this.tu.has(e)&&!this.tu.get(e).hasLocalMutations}ou(e){e&&(e.addedDocuments.forEach(e=>this.Ya=this.Ya.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ya=this.Ya.delete(e)),this.current=e.current)}_u(){if(!this.current)return[];let e=this.Xa;this.Xa=n6(),this.tu.forEach(e=>{this.uu(e.key)&&(this.Xa=this.Xa.add(e.key))});let t=[];return e.forEach(e=>{this.Xa.has(e)||t.push(new aH(e))}),this.Xa.forEach(n=>{e.has(n)||t.push(new aW(n))}),t}cu(e){this.Ya=e.Qs,this.Xa=n6();let t=this.ru(e.documents);return this.applyChanges(t,!0)}lu(){return aL.fromInitialDocuments(this.query,this.tu,this.mutatedKeys,0===this.Za,this.hasCachedResults)}}let aX="SyncEngine";class aY{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class aZ{constructor(e){this.key=e,this.hu=!1}}class a0{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.Pu={},this.Tu=new nX(e=>nj(e),nG),this.Iu=new Map,this.Eu=new Set,this.du=new t_(W.comparator),this.Au=new Map,this.Ru=new sa,this.Vu={},this.mu=new Map,this.fu=iH.cr(),this.onlineState="Unknown",this.gu=void 0}get isPrimaryClient(){return!0===this.gu}}async function a1(e,t,n=!0){let r,i=oI(e),s=i.Tu.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),r=s.view.lu()):r=await a5(i,t,n,!0),r}async function a2(e,t){let n=oI(e);await a5(n,t,!0,!1)}async function a5(e,t,n,r){let i,s=await sN(e.localStore,nK(t)),a=s.targetId,o=e.sharedCl
7ientState.addLocalQueryTarget(a,n);return r&&(i=await a6(e,t,a,"current"===o,s.resumeToken)),e.isPrimaryClient&&n&&ah(e.remoteStore,s),i}async function a6(e,t,n,r,i){e.pu=(t,n,r)=>(async function(e,t,n,r){let i=t.view.ru(n);i.Cs&&(i=await sA(e.localStore,t.query,!1).then(({documents:e})=>t.view.ru(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 oa(e,t.targetId,o.au),o.snapshot})(e,t,n,r);let s=await sA(e.localStore,t,!0),a=new aJ(t,s.Qs),o=a.ru(s.documents),l=rA.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);oa(e,n,u.au);let h=new aY(t,n,a);return e.Tu.set(t,h),e.Iu.has(n)?e.Iu.get(n).push(t):e.Iu.set(n,[t]),u.snapshot}async function a4(e,t,n){let r=e.Tu.get(t),i=e.Iu.get(r.targetId);if(i.length>1)return e.Iu.set(r.targetId,i.filter(e=>!nG(e,t))),void e.Tu.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(r.targetId),e.sharedClientState.isActiveQueryTarget(r.targetId)||await sk(e.localStore,r.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(r.targetId),n&&ac(e.remoteStore,r.targetId),oi(e,r.targetId)}).catch(ed)):(oi(e,r.targetId),await sk(e.localStore,r.targetId,!0))}async function a3(e,t){let n=e.Tu.get(t),r=e.Iu.get(n.targetId);e.isPrimaryClient&&1===r.length&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),ac(e.remoteStore,n.targetId))}async function a8(e,t){try{let n=await function(e,t){let n=t.snapshotVersion,r=e.Ms;return e.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{var s,a,o;let l,u,h=e.Ns.newChangeBuffer({trackRemovals:!0});r=e.Ms;let c=[];
7t.targetChanges.forEach((s,a)=>{var o;let l=r.get(a);if(!l)return;c.push(e.Pi.removeMatchingKeys(i,s.removedDocuments,a).next(()=>e.Pi.addMatchingKeys(i,s.addedDocuments,a)));let u=l.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(tO.EMPTY_BYTE_STRING,ee.min()).withLastLimboFreeSnapshotVersion(ee.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,n)),r=r.insert(a,u),o=u,(0===l.resumeToken.approximateByteSize()||o.snapshotVersion.toMicroseconds()-l.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&c.push(e.Pi.updateTargetData(i,u))});let d=nY,f=n6();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&c.push(e.persistence.referenceDelegate.updateLimboDocument(i,n))}),c.push((s=i,a=h,o=t.documentUpdates,l=n6(),u=n6(),o.forEach(e=>l=l.add(e)),a.getEntries(s,l).next(e=>{let t=nY;return o.forEach((n,r)=>{let i=e.get(n);r.isFoundDocument()!==i.isFoundDocument()&&(u=u.add(n)),r.isNoDocument()&&r.version.isEqual(ee.min())?(a.removeEntry(n,r.readTime),t=t.insert(n,r)):!i.isValidDocument()||r.version.compareTo(i.version)>0||0===r.version.compareTo(i.version)&&i.hasPendingWrites?(a.addEntry(r),t=t.insert(n,r)):E(sx,"Ignoring outdated watch update for ",n,". Current version:",i.version," Watch version:",r.version)}),{ks:t,qs:u}})).next(e=>{d=e.ks,f=e.qs})),!n.isEqual(ee.min())){let t=e.Pi.getLastRemoteSnapshotVersion(i).next(t=>e.Pi.setTargetsMetadata(i,i.currentSequenceNumber,n));c.push(t)}return ef.waitFor(c).next(()=>h.apply(i)).next(()=>e.localDocuments.getLocalViewOfDocuments(i,d,f)).next(()=>d)}).then(t=>(e.Ms=r,t))}(e.localStore,t);
7t.targetChanges.forEach((t,n)=>{let r=e.Au.get(n);r&&(C(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?r.hu=!0:t.modifiedDocuments.size>0?C(r.hu,14607):t.removedDocuments.size>0&&(C(r.hu,42227),r.hu=!1))}),await ol(e,n,t)}catch(e){await ed(e)}}function a9(e,t,n){var r;if(e.isPrimaryClient&&0===n||!e.isPrimaryClient&&1===n){let n,i=[];e.Tu.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.Sa)e.va(t)&&(n=!0)}),n&&aj(r),i.length&&e.Pu.H_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function a7(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Au.get(t),i=r&&r.key;if(i){let n=new t_(W.comparator);n=n.insert(i,nc.newNoDocument(i,ee.min()));let r=n6().add(i),s=new rk(ee.min(),new Map,new t_(U),n,r);await a8(e,s),e.du=e.du.remove(i),e.Au.delete(t),oo(e)}else await sk(e.localStore,t,!1).then(()=>oi(e,t,n)).catch(ed)}async function oe(e,t){var n;let r=t.batch.batchId;try{let i=await (n=e.localStore,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),i=n.Ns.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let i=n.batch,s=i.keys(),a=ef.resolve();return s.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let s=n.docVersions.get(e);C(null!==s,48541),0>t.version.compareTo(s)&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))})(n,e,t,i).next(()=>i.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=n6();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),on(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await ol(e,i)}catch(e){await ed(e)}}async function ot(e,t,n){var r;try{let i=await (r=e.localStore,r.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(C(null!==t,37113),n=t.keys(),r.mutationQueue.removeMutationBatch(e,t))).next(()=>r.mutationQueue.performConsistencyCheck(e)).next(()=>r.documentOverlayCache.removeOverlaysForBatchId(e,n,t)).next(()=>r.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,n)).next(()=>r.localDocuments.getDocuments(e,n))}));or(e,t,n),on(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await ol(e,i)}catch(e){await ed(e)}}function on(e,t){(e.mu.get(t)||[]).forEach(e=>{e.resolve()}),e.mu.delete(t)}function or(e,t,n){let r=e.Vu[e.currentUser.toKey()];if(r){let i=r.get(t);i&&(n?i.reject(n):i.resolve(),r=r.remove(t)),e.Vu[e.currentUser.toKey()]=r}}function oi(e,t,n=null){for(let r of(e.sharedClientState.removeLocalQueryTarget(t),e.Iu.get(t)))e.Tu.delete(r),n&&e.Pu.yu(r,n);e.Iu.delete(t),e.isPrimaryClient&&e.Ru.jr(t).forEach(t=>{e.Ru.containsKey(t)||os(e,t)})}function os(e,t){e.Eu.delete(t.path.canonicalString());let n=e.du.get(t);null!==n&&(ac(e.remoteStore,n),e.du=e.du.remove(t),e.Au.delete(n),oo(e))}function oa(e,t,n){for(let r of n)r instanceof aW?(e.Ru.addReference(r.key,t),function(e,t){let n=t.key,r=n.path.canonicalString();e.du.get(n)||e.Eu.has(r)||(E(aX,"New document in limbo: "+n),e.Eu.add(r),oo(e))}(e,r)):r instanceof aH?(E(aX,"Document no longer in limbo: "+r.key),e.Ru.removeReference(r.key,t),e.Ru.containsKey(r.key)||os(e,r.key)):x(19791,{wu:r})}function oo(e){for(;e.Eu.size>0&&e.du.size<e.maxConcurrentLimboResolutions;){let t=e.Eu.values().next().value;e.Eu.delete(t);let n=new W(G.fromString(t)),r=e.fu.next();e.Au.set(r,new aZ(n)),e.du=e.du.insert(n,r),ah(e.remoteStore,new ie(nK(new nB(n.path)),r,"TargetPurposeLimboResolution",eD.ce))}}async function ol(e,t,n){let r=[],i=[],s=[];e.Tu.isEmpty()||(e.Tu.forEach((a,o)=>{s.push(e.pu(o,t,n).then(t=>{if((t||n)&&e.isPrimaryClient){let r=t?!t.fromCache:n?.targetChanges.get(o.targetId)?.current;
7e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=sT.As(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.Pu.H_(r),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>ef.forEach(t,t=>ef.forEach(t.Es,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>ef.forEach(t.ds,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!eI(e))throw e;E(sx,"Failed to update sequence numbers: "+e)}for(let n of t){let t=n.targetId;if(!n.fromCache){let n=e.Ms.get(t),r=n.snapshotVersion,i=n.withLastLimboFreeSnapshotVersion(r);e.Ms=e.Ms.insert(t,i)}}}(e.localStore,i))}async function ou(e,t){if(!e.currentUser.isEqual(t)){E(aX,"User change. New user:",t.toKey());let n=await sC(e.localStore,t);e.currentUser=t,e.mu.forEach(e=>{e.forEach(e=>{e.reject(new N(D.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.mu.clear(),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await ol(e,n.Ls)}}function oh(e,t){let n=e.Au.get(t);if(n&&n.hu)return n6().add(n.key);{let n=n6(),r=e.Iu.get(t);if(!r)return n;for(let t of r){let r=e.Tu.get(t);n=n.unionWith(r.view.nu)}return n}}async function oc(e,t){let n=await sA(e.localStore,t.query,!0),r=t.view.cu(n);return e.isPrimaryClient&&oa(e,t.targetId,r.au),r}async function od(e,t){return sV(e.localStore,t).then(t=>ol(e,t))}async function of(e,t,n,r){var i;let s=await function(e,t){let n=e.mutationQueue;return e.persistence.runTransaction("Lookup mutation documents","readonly",r=>n.er(r,t).next(t=>t?e.localDocuments.getDocuments(r,t):ef.resolve(null)))}(e.localStore,t);null!==s?("pending"===n?await aS(e.remoteStore):"acknowledged"===n||"rejected"===n?(or(e,t,r||null),on(e,t),i=e.localStore,i.mutationQueue.ir(t)):x(6720,"Unknown batchState",{Su:n}),await ol(e,s)):E(aX,"Cannot apply mutation batch with id: "+t)}async function om(e,t){if(oI(e),oE(e),!0===t&&!0!==e.gu){let t=e.sharedClientState.getAllActiveQueryTargets(),n=await og(e,t.toArray());for(let t of(e.gu=!0,await aA(e.remoteStore,!0),n))ah(e.remoteStore,t)}else if(!1===t&&!1!==e.gu){let t=[],n=Promise.resolve();e.Iu.forEach((r,i)=>{e.sharedClientState.isLocalQueryTarget(i)?t.push(i):n=n.then(()=>(oi(e,i),sk(e.localStore,i,!0))),ac(e.remoteStore,i)}),await n,await og(e,t),e.Au.forEach((t,n)=>{ac(e.remoteStore,n)}),e.Ru.Jr(),e.Au=new Map,e.du=new t_(W.comparator),e.gu=!1,await aA(e.remoteStore,!1)}}async function og(e,t,n){let r=[],i=[];for(let n of t){let t,s=e.Iu.get(n);if(s&&0!==s.length)for(let n of(t=await sN(e.localStore,nK(s[0])),s)){let t=e.Tu.get(n),r=await oc(e,t);r.snapshot&&i.push(r.snapshot)}else{let r=await sR(e.localStore,n);t=await sN(e.localStore,r),await a6(e,op(r),n,!1,t.resumeToken)}r.push(t)}return e.Pu.H_(i),r}function op(e){var t,n,r,i,s;return t=e.path,n=e.collectionGroup,r=e.orderBy,i=e.filters,s=e.limit,new nB(t,n,r,i,s,"F",e.startAt,e.endAt)}function oy(e){return e.localStore.persistence.Ts()}async function ow(e,t,n,r){if(e.gu)return void E(aX,"Ignoring unexpected query state notification.");let i=e.Iu.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{let r=await sV(e.localStore,nH(i[0])),s=rk.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,tO.EMPTY_BYTE_STRING);await ol(e,r,s);break}case"rejected":await sk(e.localStore,t,!0),oi(e,t,r);break;default:x(64155,n)}}async function ov(e,t,n){let r=oI(e);if(r.gu){for(let e of t){if(r.Iu.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){E(aX,"Adding an already active target "+e);continue}let t=await sR(r.localStore,e),n=await sN(r.localStore,t);await a6(r,op(t),n.targetId,!1,n.resumeToken),ah(r.remoteStore,n)}for(let e of n)r.Iu.has(e)&&await sk(r.localStore,e,!1).then(()=>{ac(r.remoteStore,e),oi(r,e)}).catch(ed)}}function oI(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=a8.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=oh.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=a7.bind(null,e),e.Pu.H_=a$.bind(null,e.eventManager),e.Pu.yu=aG.bind(null,e.eventManager),e}function oE(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=oe.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=ot.bind(null,e),e}class oT{constructor(){this.kind="memory",this.synchronizeTabs=!1}
7async initialize(e){this.serializer=new rz(e.databaseInfo.databaseId,!0),this.sharedClientState=this.Du(e),this.persistence=this.Cu(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Fu(e,this.localStore),this.indexBackfillerScheduler=this.Mu(e,this.localStore)}Fu(e,t){return null}Mu(e,t){return null}vu(e){var t,n;return t=this.persistence,n=new sb,new s_(t,n,e.initialUser,this.serializer)}Cu(e){return new sd(sm.mi,this.serializer)}Du(e){return new sW}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}oT.provider={build:()=>new oT};class oS extends oT{constructor(e){super(),this.cacheSizeBytes=e}Fu(e,t){return C(this.persistence.referenceDelegate instanceof sg,46915),new i1(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Cu(e){let t=void 0!==this.cacheSizeBytes?iK.withCacheSize(this.cacheSizeBytes):iK.DEFAULT;return new sd(e=>sg.mi(e,t),this.serializer)}}class ob extends oT{constructor(e,t,n){super(),this.xu=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.xu.initialize(this,e),await oE(this.xu.syncEngine),await aS(this.xu.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 sb,new s_(t,n,e.initialUser,this.serializer)}Fu(e,t){return new i1(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Mu(e,t){let n=new eC(t,this.persistence);return new e_(e.asyncQueue,n)}Cu(e){let t=sE(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?iK.withCacheSize(this.cacheSizeBytes):iK.DEFAULT;return new sI(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,s3(),s8(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Du(e){return new sW}}class ox extends ob{constructor(e,t){super(e,t,!1),this.xu=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);let t=this.xu.syncEngine;this.sharedClientState instanceof sQ&&(this.sharedClientState.syncEngine={Co:of.bind(null,t),vo:ow.bind(null,t),Fo:ov.bind(null,t),Ts:oy.bind(null,t),Do:od.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ji(async e=>{await om(this.xu.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())})}Du(e){let t=s3();if(!sQ.v(t))throw new N(D.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let n=sE(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new sQ(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class o_{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=>a9(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=ou.bind(null,this.syncEngine),await aA(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new aB}createDatastore(e){var t;let n=new rz(e.databaseInfo.databaseId,!0),r=new s4(e.databaseInfo);return t=e.authCredentials,new ai(t,e.appCheckCredentials,r,n)}createRemoteStore(e){var t,n;return t=this.localStore,n=this.datastore,new ao(t,n,e.asyncQueue,e=>a9(this.syncEngine,e,0),sX.v()?new sX:new sH)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){let o=new a0(e,t,n,r,i,s);return a&&(o.gu=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){await async function(e){E(aa,"RemoteStore shutting down."),e.Ea.add(5),await au(e),e.Aa.shutdown(),e.Ra.set("Unknown")}(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}o_.provider={build:()=>new o_};class oC{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ou(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ou(this.observer.error,e):T("Uncaught Error in snapshot listener:",e.toString()))}Nu(){this.muted=!0}
7Ou(e,t){setTimeout(()=>{this.muted||e(t)},0)}}let oD="FirestoreClient";class oN{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=y.UNAUTHENTICATED,this.clientId=L.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async e=>{E(oD,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(E(oD,"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=aM(n,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function ok(e,t){e.asyncQueue.verifyOperationInProgress(),E(oD,"Initializing OfflineComponentProvider");let n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await sC(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function oA(e,t){e.asyncQueue.verifyOperationInProgress();let n=await oR(e);E(oD,"Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>ak(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>ak(t.remoteStore,n)),e._onlineComponents=t}async function oR(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){E(oD,"Using user provided OfflineComponentProvider");try{await ok(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===D.FAILED_PRECONDITION||t.code===D.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;S("Error using user provided cache. Falling back to memory cache: "+t),await ok(e,new oT)}}else E(oD,"Using default OfflineComponentProvider"),await ok(e,new oS(void 0));return e._offlineComponents}async function oV(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(E(oD,"Using user provided OnlineComponentProvider"),await oA(e,e._uninitializedComponentsProvider._online)):(E(oD,"Using default OnlineComponentProvider"),await oA(e,new o_))),e._onlineComponents}async function oO(e){let t=await oV(e),n=t.eventManager;return n.onListen=a1.bind(null,t.syncEngine),n.onUnlisten=a4.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=a2.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=a3.bind(null,t.syncEngine),n}function oM(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let oP=new Map;class oF{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new N(D.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=e.ssl??!0;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new N(D.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new N(D.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=oM(e.experimentalLongPollingOptions??{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new N(D.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new N(D.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new N(D.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 oL{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 oF({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new N(D.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new N(D.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 oF(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new R;switch(e.type){case"firstParty":return new M(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new N(D.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
7d credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){let t=oP.get(e);t&&(E("ComponentProvider","Removing Datastore"),oP.delete(e),t.terminate())}(this),Promise.resolve()}}class oU{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new oU(this.firestore,e,this._query)}}class oB{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 oq(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new oB(this.firestore,e,this._key)}toJSON(){return{type:oB._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,n){if(Y(t,oB._jsonSchema))return new oB(e,n||null,new W(G.fromString(t.referencePath)))}}oB._jsonSchemaVersion="firestore/documentReference/1.0",oB._jsonSchema={type:X("string",oB._jsonSchemaVersion),referencePath:X("string")};class oq extends oU{constructor(e,t,n){super(e,t,new nB(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 oB(this.firestore,null,new W(e))}withConverter(e){return new oq(this.firestore,e,this._path)}}function oz(e,t,...n){if(e=(0,h.Ku)(e),function(e,t,n){if(!n)throw new N(D.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}("collection","path",t),e instanceof oL){let r=G.fromString(t,...n);return H(r),new oq(e,null,r)}{if(!(e instanceof oB||e instanceof oq))throw new N(D.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(G.fromString(t,...n));return H(r),new oq(e.firestore,null,r)}}let oK="AsyncQueue";class o${constructor(e=Promise.resolve()){this.Xu=[],this.ec=!1,this.tc=[],this.nc=null,this.rc=!1,this.sc=!1,this.oc=[],this.M_=new s9(this,"async_queue_retry"),this._c=()=>{let e=s8();e&&E(oK,"Visibility state changed to "+e.visibilityState),this.M_.w_()},this.ac=e;let t=s8();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this._c)}get isShuttingDown(){return this.ec}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.uc(),this.cc(e)}enterRestrictedMode(e){if(!this.ec){this.ec=!0,this.sc=e||!1;let t=s8();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this._c)}}enqueue(e){if(this.uc(),this.ec)return new Promise(()=>{});let t=new k;return this.cc(()=>this.ec&&this.sc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Xu.push(e),this.lc()))}async lc(){if(0!==this.Xu.length){try{await this.Xu[0](),this.Xu.shift(),this.M_.reset()}catch(e){if(!eI(e))throw e;E(oK,"Operation failed with retryable error: "+e)}this.Xu.length>0&&this.M_.p_(()=>this.lc())}}cc(e){let t=this.ac.then(()=>(this.rc=!0,e().catch(e=>{throw this.nc=e,this.rc=!1,T("INTERNAL UNHANDLED ERROR: ",oG(e)),e}).then(e=>(this.rc=!1,e))));return this.ac=t,t}enqueueAfterDelay(e,t,n){this.uc(),this.oc.indexOf(e)>-1&&(t=0);let r=aO.createAndSchedule(this,e,t,n,e=>this.hc(e));return this.tc.push(r),r}uc(){this.nc&&x(47125,{Pc:oG(this.nc)})}verifyOperationInProgress(){}async Tc(){let e;do e=this.ac,await e;while(e!==this.ac)}Ic(e){for(let t of this.tc)if(t.timerId===e)return!0;return!1}Ec(e){return this.Tc().then(()=>{for(let t of(this.tc.sort((e,t)=>
7e.targetTimeMs-t.targetTimeMs),this.tc))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Tc()})}dc(e){this.oc.push(e)}hc(e){let t=this.tc.indexOf(e);this.tc.splice(t,1)}}function oG(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}class oj extends oL{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new o$,this._persistenceKey=r?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new o$(e),this._firestoreClient=void 0,await e}}}function oQ(e,t,n){n||(n=tQ);let r=(0,o.j6)(e,"firestore");if(r.isInitialized(n)){let e=r.getImmediate({identifier:n}),i=r.getOptions(n);if((0,h.bD)(i,t))return e;throw new N(D.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&void 0!==t.localCache)throw new N(D.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new N(D.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return t.host&&(0,h.zJ)(t.host)&&(0,h.gE)(t.host),r.initialize({options:t,instanceIdentifier:n})}class oW{constructor(e){this._byteString=e}static fromBase64String(e){try{return new oW(tO.fromBase64String(e))}catch(e){throw new N(D.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new oW(tO.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:oW._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Y(e,oW._jsonSchema))return oW.fromBase64String(e.bytes)}}oW._jsonSchemaVersion="firestore/bytes/1.0",oW._jsonSchema={type:X("string",oW._jsonSchemaVersion),bytes:X("string")};class oH{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new N(D.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Q(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class oJ{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new N(D.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new N(D.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 U(this._lat,e._lat)||U(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:oJ._jsonSchemaVersion}}static fromJSON(e){if(Y(e,oJ._jsonSchema))return new oJ(e.latitude,e.longitude)}}oJ._jsonSchemaVersion="firestore/geoPoint/1.0",oJ._jsonSchema={type:X("string",oJ._jsonSchemaVersion),latitude:X("number"),longitude:X("number")};class oX{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:oX._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(Y(e,oX._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new oX(e.vectorValues);throw new N(D.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}oX._jsonSchemaVersion="firestore/vectorValue/1.0",oX._jsonSchema={type:X("string",oX._jsonSchemaVersion),vectorValues:X("object")};
7let oY=RegExp("[~\\*/\\[\\]]");function oZ(e,t,n,r,i){let s=r&&!r.isEmpty(),a=void 0!==i,o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${r}`),a&&(l+=` in document ${i}`),l+=")"),new N(D.INVALID_ARGUMENT,o+e+l)}class o0{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 oB(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new o1(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(o2("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class o1 extends o0{data(){return super.data()}}function o2(e,t){return"string"==typeof t?function(e,t,n){if(t.search(oY)>=0)throw oZ(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,void 0);try{return new oH(...t.split("."))._internalPath}catch(n){throw oZ(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,void 0)}}(e,t):t instanceof oH?t._internalPath:t._delegate._internalPath}class o5{convertValue(e,t="none"){switch(t1(e)){case 0:return null;case 1:return e.booleanValue;case 2:return tF(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(tL(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw x(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return tx(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertVectorValue(e){return new oX(e.fields?.[tZ].arrayValue?.values?.map(e=>tF(e.doubleValue)))}convertGeoPoint(e){return new oJ(tF(e.latitude),tF(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=t$(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(tG(e));default:return null}}convertTimestamp(e){let t=tP(e);return new Z(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=G.fromString(e);C(r7(n),9688,{name:e});let r=new tW(n.get(1),n.get(3)),i=new W(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}}class o6{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class o4 extends o0{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 o3(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(o2("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new N(D.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=o4._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),e&&e.isValidDocument()&&e.isFoundDocument()&&
7(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),this._firestore,this.ref.path,t.bundle="NOT SUPPORTED"),t}}o4._jsonSchemaVersion="firestore/documentSnapshot/1.0",o4._jsonSchema={type:X("string",o4._jsonSchemaVersion),bundleSource:X("string","DocumentSnapshot"),bundleName:X("string"),bundle:X("string")};class o3 extends o4{data(e={}){return super.data(e)}}class o8{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new o6(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 o3(this._firestore,this._userDataWriter,n.key,n,new o6(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new N(D.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 o3(e._firestore,e._userDataWriter,n.doc.key,n.doc,new o6(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 o3(e._firestore,e._userDataWriter,t.doc.key,t.doc,new o6(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(s=(n=n.add(t.doc)).indexOf(t.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return x(61501,{type:e})}}(t.type),doc:r,oldIndex:i,newIndex:s}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new N(D.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=o8._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=L.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}}o8._jsonSchemaVersion="firestore/querySnapshot/1.0",o8._jsonSchema={type:X("string",o8._jsonSchemaVersion),bundleSource:X("string","QuerySnapshot"),bundleName:X("string"),bundle:X("string")};class o9 extends o5{constructor(e){super(),this.firestore=e}convertBytes(e){return new oW(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new oB(this.firestore,null,t)}}function o7(e){e=J(e,oU);let t=J(e.firestore,oj),n=function(e){if(e._terminated)throw new N(D.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||function(e){var t,n;let r=e._freezeSettings(),i=(t=e._databaseId,n=e._app?.options.appId||"",new tj(t,n,e._persistenceKey,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,oM(r.experimentalLongPollingOptions),r.useFetchStreams,r.isUsingEmulator));e._componentsProvider||r.localCache?._offlineComponentProvider&&r.localCache?._onlineComponentProvider&&(e._componentsProvider={_offline:r.localCache._offlineComponentProvider,_online:r.localCache._onlineComponentProvider}),e._firestoreClient=new oN(e._authCredentials,e._appCheckCredentials,e._queue,i,e._componentsProvider&&function(e){let t=e?._online.build();return{_offline:e?._offline.build(t),_online:t}}(e._componentsProvider))}(e),e._firestoreClient}(t),r=new o9(t);return function(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new N(D.UNIMPLEMENT
7ED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query),(function(e,t,n={}){let r=new k;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new oC({next:n=>{s.Nu(),t.enqueueAndForget(()=>aK(e,a)),n.fromCache&&"server"===r.source?i.reject(new N(D.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 aQ(n,s,{includeMetadataChanges:!0,qa:!0});return az(e,a)})(await oO(e),e.asyncQueue,t,n,r)),r.promise})(n,e._query).then(n=>new o8(t,r,e,n))}class le{constructor(e){var t;let n;this.kind="persistent",e?.tabManager?(e.tabManager._initialize(e),n=e.tabManager):(t=void 0,n=new ln(t?.forceOwnership))._initialize(e),this._onlineComponentProvider=n._onlineComponentProvider,this._offlineComponentProvider=n._offlineComponentProvider}toJSON(){return{kind:this.kind}}}function lt(e){return new le(e)}class ln{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=o_.provider,this._offlineComponentProvider={build:t=>new ob(t,e?.cacheSizeBytes,this.forceOwnership)}}}class lr{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=o_.provider,this._offlineComponentProvider={build:t=>new ox(t,e?.cacheSizeBytes)}}}function li(){return new lr}new WeakMap,function(e=!0){w=o.MF,(0,o.om)(new l.uA("firestore",(t,{instanceIdentifier:n,options:r})=>{let i=t.getProvider("app").getImmediate(),s=new oj(new V(t.getProvider("auth-internal")),new F(i,t.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new N(D.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new tW(e.options.projectId,t)}(i,n),i);return r={useFetchStreams:e,...r},s._setSettings(r),s},"PUBLIC").setMultipleInstances(!0)),(0,o.KO)(g,p,void 0),(0,o.KO)(g,p,"esm2020")}()}}]);
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.